diff --git "a/3715.jsonl" "b/3715.jsonl" new file mode 100644--- /dev/null +++ "b/3715.jsonl" @@ -0,0 +1,214 @@ +{"seq_id":"636488730","text":"# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# 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, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport netaddr\nimport six\n\nfrom neutron.common import utils as n_utils\nfrom neutron.quota import resource_registry\nfrom neutron_lib.api.definitions import portbindings\nfrom neutron_lib import constants\nfrom neutron_lib import context as n_ctx\nfrom neutron_lib.plugins import constants as pconst\nfrom neutron_lib.plugins import directory\nfrom oslo_log import helpers as log\nfrom oslo_log import log as logging\nfrom oslo_utils import excutils\n\nfrom gbpservice.common import utils as gbp_utils\nfrom gbpservice.neutron.db import api as db_api\nfrom gbpservice.neutron.db.grouppolicy import group_policy_db as gpdb\nfrom gbpservice.neutron.db.grouppolicy import group_policy_mapping_db\nfrom gbpservice.neutron import extensions as gbp_extensions\nfrom gbpservice.neutron.extensions import group_policy as gpex\nfrom gbpservice.neutron.services.grouppolicy import (\n extension_manager as ext_manager)\nfrom gbpservice.neutron.services.grouppolicy import (\n group_policy_context as p_context)\nfrom gbpservice.neutron.services.grouppolicy import (\n policy_driver_manager as manager)\nfrom gbpservice.neutron.services.grouppolicy.common import constants as gp_cts\nfrom gbpservice.neutron.services.grouppolicy.common import exceptions as gp_exc\nfrom gbpservice.neutron.services.grouppolicy.common import utils\n\n\nLOG = logging.getLogger(__name__)\nSTATUS = 'status'\nSTATUS_DETAILS = 'status_details'\nSTATUS_SET = set([STATUS, STATUS_DETAILS])\n\n\nclass GroupPolicyPlugin(group_policy_mapping_db.GroupPolicyMappingDbPlugin):\n\n \"\"\"Implementation of the Group Policy Model Plugin.\n\n This class manages the workflow of Group Policy request/response.\n Most DB related works are implemented in class\n db_group_policy_mapping.GroupPolicyMappingDbMixin.\n \"\"\"\n _supported_extension_aliases = [\"group-policy\", \"group-policy-mapping\"]\n path_prefix = gp_cts.GBP_PREFIXES[pconst.GROUP_POLICY]\n\n @property\n def supported_extension_aliases(self):\n if not hasattr(self, '_aliases'):\n aliases = self._supported_extension_aliases[:]\n aliases += self.extension_manager.extension_aliases()\n self._aliases = aliases\n return self._aliases\n\n def start_rpc_listeners(self):\n return self.policy_driver_manager.start_rpc_listeners()\n\n def validate_state(self, repair, resources, tenants):\n return self.policy_driver_manager.validate_state(repair,\n resources, tenants)\n\n @property\n def servicechain_plugin(self):\n # REVISIT(rkukura): Need initialization method after all\n # plugins are loaded to grab and store plugin.\n servicechain_plugin = directory.get_plugin(pconst.SERVICECHAIN)\n if not servicechain_plugin:\n LOG.error(\"No Servicechain service plugin found.\")\n raise gp_exc.GroupPolicyDeploymentError()\n return servicechain_plugin\n\n # Shared attribute validation rules:\n # - A shared resource cannot use/link a non-shared resource\n # - A shared resource cannot be reverted to non-shared if used/linked by\n # other shared resources, or by any resource owned by any other tenant\n\n # In the usage graph, specify which resource has to be checked to validate\n # sharing policy conformity:\n # usage_graph = {: {: }, ...}\n # is the field on the dictionary that can be used\n # to retrieve the UUID/s of the specific object \n\n usage_graph = {'l3_policy': {'external_segments':\n 'external_segment'},\n 'l2_policy': {'l3_policy_id': 'l3_policy'},\n 'policy_target_group': {\n 'network_service_policy_id': 'network_service_policy',\n 'l2_policy_id': 'l2_policy',\n 'provided_policy_rule_sets': 'policy_rule_set',\n 'consumed_policy_rule_sets': 'policy_rule_set'},\n 'network_service_policy': {},\n 'policy_rule': {\n 'policy_classifier_id': 'policy_classifier',\n 'policy_actions': 'policy_action'},\n 'policy_action': {},\n 'policy_classifier': {},\n 'policy_rule_set': {\n 'parent_id': 'policy_rule_set',\n 'policy_rules': 'policy_rule'},\n 'external_segment': {},\n 'external_policy': {\n 'external_segments': 'external_segment',\n 'provided_policy_rule_sets': 'policy_rule_set',\n 'consumed_policy_rule_sets': 'policy_rule_set'},\n 'nat_pool': {'external_segment_id':\n 'external_segment'},\n 'policy_target': {'policy_target_group_id':\n 'policy_target_group'},\n 'application_policy_group': {}\n }\n\n @staticmethod\n def _validate_shared_create(self, context, obj, identity):\n # REVISIT(ivar): only validate new references\n links = self.usage_graph.get(identity, {})\n for attr in links:\n ids = obj[attr]\n if ids:\n if isinstance(ids, six.string_types):\n ids = [ids]\n ref_type = links[attr]\n linked_objects = getattr(\n self, 'get_%s' % gbp_extensions.get_plural(ref_type))(\n context, filters={'id': ids})\n link_ids = set()\n for linked in linked_objects:\n link_ids.add(linked['id'])\n GroupPolicyPlugin._verify_sharing_consistency(\n obj, linked, identity, ref_type, context.is_admin)\n # Check for missing references\n missing = set(ids) - link_ids\n if missing:\n raise gpex.GbpResourceNotFound(identity=ref_type,\n id=str(missing))\n\n @staticmethod\n def _validate_shared_update(self, context, original, updated, identity):\n # Need admin context to check sharing constraints\n\n # Even though the shared attribute may not be changed, the objects\n # it is referring to might. For this reson we run the reference\n # validation every time a shared resource is updated\n # TODO(ivar): run only when relevant updates happen\n self._validate_shared_create(self, context, updated, identity)\n if updated.get('shared') != original.get('shared'):\n context = context.elevated()\n getattr(self, '_validate_%s_unshare' % identity)(context, updated)\n\n @staticmethod\n def _check_shared_or_different_tenant(context, obj, method, attr,\n value=None):\n tenant_id = obj['tenant_id']\n refs = method(context, filters={attr: value or [obj['id']]})\n for ref in refs:\n if ref.get('shared') or tenant_id != ref['tenant_id']:\n raise gp_exc.InvalidSharedAttributeUpdate(id=obj['id'],\n rid=ref['id'])\n\n def _validate_l3_policy_unshare(self, context, obj):\n self._check_shared_or_different_tenant(\n context, obj, self.get_l2_policies, 'l3_policy_id')\n\n def _validate_l2_policy_unshare(self, context, obj):\n self._check_shared_or_different_tenant(\n context, obj, self.get_policy_target_groups, 'l2_policy_id')\n\n def _validate_policy_target_group_unshare(self, context, obj):\n self._check_shared_or_different_tenant(\n context, obj, self.get_policy_targets, 'policy_target_group_id')\n\n def _validate_network_service_policy_unshare(self, context, obj):\n self._check_shared_or_different_tenant(\n context, obj, self.get_policy_target_groups,\n 'network_service_policy_id')\n\n def _validate_policy_rule_set_unshare(self, context, obj):\n self._check_shared_or_different_tenant(\n context, obj, self.get_policy_target_groups, 'id',\n obj['providing_policy_target_groups'] +\n obj['consuming_policy_target_groups'])\n self._check_shared_or_different_tenant(\n context, obj, self.get_external_policies, 'id',\n obj['providing_external_policies'] +\n obj['consuming_external_policies'])\n\n def _validate_policy_classifier_unshare(self, context, obj):\n self._check_shared_or_different_tenant(\n context, obj, self.get_policy_rules, 'policy_classifier_id')\n\n def _validate_policy_rule_unshare(self, context, obj):\n c_ids = self._get_policy_rule_policy_rule_sets(context, obj['id'])\n self._check_shared_or_different_tenant(\n context, obj, self.get_policy_rule_sets, 'id', c_ids)\n\n def _validate_policy_action_unshare(self, context, obj):\n r_ids = self._get_policy_action_rules(context, obj['id'])\n self._check_shared_or_different_tenant(\n context, obj, self.get_policy_rules, 'id', r_ids)\n\n def _validate_external_segment_unshare(self, context, obj):\n self._check_shared_or_different_tenant(\n context, obj, self.get_l3_policies, 'id', obj['l3_policies'])\n self._check_shared_or_different_tenant(\n context, obj, self.get_external_policies, 'id',\n obj['external_policies'])\n self._check_shared_or_different_tenant(\n context, obj, self.get_nat_pools, 'external_segment_id')\n\n def _validate_external_policy_unshare(self, context, obj):\n pass\n\n def _validate_nat_pool_unshare(self, context, obj):\n pass\n\n def _validate_routes(self, context, current, original=None):\n if original:\n added = (set((x['destination'], x['nexthop']) for x in\n current['external_routes']) -\n set((x['destination'], x['nexthop']) for x in\n original['external_routes']))\n else:\n added = set((x['destination'], x['nexthop']) for x in\n current['external_routes'])\n if added:\n # Verify new ones don't overlap with the existing L3P\n added_dest = set(x[0] for x in added)\n # Remove default routes\n added_dest.discard('0.0.0.0/0')\n added_dest.discard('::/0')\n added_ipset = netaddr.IPSet(added_dest)\n if current['l3_policies']:\n l3ps = self.get_l3_policies(\n context, filters={'id': current['l3_policies']})\n for l3p in l3ps:\n ip_pool_list = utils.convert_ip_pool_string_to_list(\n l3p['ip_pool'])\n if netaddr.IPSet(ip_pool_list) & added_ipset:\n raise gp_exc.ExternalRouteOverlapsWithL3PIpPool(\n destination=added_dest, l3p_id=l3p['id'],\n es_id=current['id'])\n es_list = [current]\n es_list.extend(self.get_external_segments(\n context.elevated(),\n filters={'id': [e for e in l3p['external_segments']\n if e != current['id']]}))\n self._validate_identical_external_routes(es_list)\n # Verify NH in ES pool\n added_nexthop = netaddr.IPSet(x[1] for x in added if x[1])\n es_subnet = netaddr.IPSet([current['cidr']])\n if added_nexthop & es_subnet != added_nexthop:\n raise gp_exc.ExternalRouteNextHopNotInExternalSegment(\n cidr=current['cidr'])\n\n def _validate_l3p_es(self, context, current, original=None):\n if original:\n added = (set(current['external_segments'].keys()) -\n set(original['external_segments'].keys()))\n else:\n added = set(current['external_segments'].keys())\n if added:\n es_list = self.get_external_segments(context,\n filters={'id': added})\n ip_pool_list = utils.convert_ip_pool_string_to_list(\n current['ip_pool'])\n l3p_ipset = netaddr.IPSet(ip_pool_list)\n for es in es_list:\n # Verify no route overlap\n dest_set = set(x['destination'] for x in\n es['external_routes'])\n dest_set.discard('0.0.0.0/0')\n dest_set.discard('::/0')\n if l3p_ipset & netaddr.IPSet(dest_set):\n raise gp_exc.ExternalRouteOverlapsWithL3PIpPool(\n destination=dest_set, l3p_id=current['id'],\n es_id=es['id'])\n # Verify segment CIDR doesn't overlap with L3P's\n cidr = es['cidr']\n if es['subnet_id']:\n core_plugin = directory.get_plugin()\n cidr = core_plugin.get_subnet(context,\n es['subnet_id'])['cidr']\n if l3p_ipset & netaddr.IPSet([cidr]):\n raise gp_exc.ExternalSegmentSubnetOverlapsWithL3PIpPool(\n subnet=cidr, l3p_id=current['id'],\n es_id=current['id'])\n # Verify allocated address correctly in subnet\n for addr in current['external_segments'][es['id']]:\n if addr != gpdb.ADDRESS_NOT_SPECIFIED:\n if addr not in netaddr.IPNetwork(cidr):\n raise gp_exc.InvalidL3PExternalIPAddress(\n ip=addr, es_id=es['id'], l3p_id=current['id'],\n es_cidr=cidr)\n es_list_all = self.get_external_segments(\n context.elevated(),\n filters={'id': list(current['external_segments'].keys())})\n self._validate_identical_external_routes(es_list_all)\n\n def _validate_identical_external_routes(self, es_list):\n if len(es_list) < 2:\n return\n route_dict = {netaddr.IPNetwork(route['destination']).cidr: es\n for es in es_list[1:]\n for route in es['external_routes']}\n for route in es_list[0]['external_routes']:\n cidr = netaddr.IPNetwork(route['destination']).cidr\n if cidr in route_dict:\n raise gp_exc.IdenticalExternalRoute(\n es1=es_list[0]['id'], es2=route_dict[cidr]['id'],\n cidr=cidr)\n\n def _validate_action_value(self, context, action):\n if action.get('action_type') == gp_cts.GP_ACTION_REDIRECT:\n if action.get('action_value'):\n # Verify sc spec existence and visibility\n spec = self.servicechain_plugin.get_servicechain_spec(\n context, action['action_value'])\n GroupPolicyPlugin._verify_sharing_consistency(\n action, spec, 'policy_action', 'servicechain_spec',\n context.is_admin)\n\n @staticmethod\n def _verify_sharing_consistency(primary, reference, primary_type,\n reference_type, is_admin):\n if not reference.get('shared'):\n if primary.get('shared'):\n raise gp_exc.SharedResourceReferenceError(\n res_type=primary_type, res_id=primary['id'],\n ref_type=reference_type, ref_id=reference['id'])\n if not is_admin:\n if primary.get('tenant_id') != reference.get('tenant_id'):\n raise gp_exc.InvalidCrossTenantReference(\n res_type=primary_type, res_id=primary['id'],\n ref_type=reference_type, ref_id=reference['id'])\n\n def _get_status_from_drivers(self, context, context_name, resource_name,\n resource_id, resource):\n status = resource['status']\n status_details = resource['status_details']\n policy_context = getattr(p_context, context_name)(\n self, context, resource, resource)\n getattr(self.policy_driver_manager,\n \"get_\" + resource_name + \"_status\")(policy_context)\n _resource = getattr(policy_context, \"_\" + resource_name)\n updated_status = _resource['status']\n updated_status_details = _resource['status_details']\n if status != updated_status or (\n status_details != updated_status_details):\n new_status = {resource_name: {'status': updated_status,\n 'status_details':\n updated_status_details}}\n with db_api.CONTEXT_WRITER.using(context):\n getattr(super(GroupPolicyPlugin, self),\n \"update_\" + resource_name)(\n context, _resource['id'], new_status)\n resource['status'] = updated_status\n resource['status_details'] = updated_status_details\n return resource\n\n def _get_resource(self, context, resource_name, resource_id,\n gbp_context_name, fields=None):\n # The following is a writer because we do DB write for status\n with db_api.CONTEXT_WRITER.using(context):\n session = context.session\n get_method = \"\".join(['get_', resource_name])\n result = getattr(super(GroupPolicyPlugin, self), get_method)(\n context, resource_id, None)\n extend_resources_method = \"\".join(['extend_', resource_name,\n '_dict'])\n getattr(self.extension_manager, extend_resources_method)(\n session, result)\n\n # Invoke drivers only if status attributes are requested\n if not fields or STATUS_SET.intersection(set(fields)):\n result = self._get_status_from_drivers(\n context, gbp_context_name, resource_name, resource_id,\n result)\n return db_api.resource_fields(result, fields)\n\n def _get_resources(self, context, resource_name, gbp_context_name,\n filters=None, fields=None, sorts=None, limit=None,\n marker=None, page_reverse=False):\n # The following is a writer because we do DB write for status\n with db_api.CONTEXT_WRITER.using(context):\n session = context.session\n resource_plural = gbp_utils.get_resource_plural(resource_name)\n get_resources_method = \"\".join(['get_', resource_plural])\n results = getattr(super(GroupPolicyPlugin, self),\n get_resources_method)(\n context, filters, None, sorts, limit, marker, page_reverse)\n filtered_results = []\n for result in results:\n extend_resources_method = \"\".join(['extend_', resource_name,\n '_dict'])\n getattr(self.extension_manager, extend_resources_method)(\n session, result)\n filtered = self._filter_extended_result(result, filters)\n if filtered:\n filtered_results.append(filtered)\n\n new_filtered_results = []\n # Invoke drivers only if status attributes are requested\n if not fields or STATUS_SET.intersection(set(fields)):\n for result in filtered_results:\n result = self._get_status_from_drivers(\n context, gbp_context_name, resource_name, result['id'],\n result)\n new_filtered_results.append(result)\n new_filtered_results = new_filtered_results or filtered_results\n return [db_api.resource_fields(nfresult, fields) for nfresult in\n new_filtered_results]\n\n @resource_registry.tracked_resources(\n l3_policy=group_policy_mapping_db.L3PolicyMapping,\n l2_policy=group_policy_mapping_db.L2PolicyMapping,\n policy_target=group_policy_mapping_db.PolicyTargetMapping,\n policy_target_group=group_policy_mapping_db.PolicyTargetGroupMapping,\n application_policy_group=gpdb.ApplicationPolicyGroup,\n policy_classifier=gpdb.PolicyClassifier,\n policy_action=gpdb.PolicyAction,\n policy_rule=gpdb.PolicyRule,\n policy_rule_set=gpdb.PolicyRuleSet,\n external_policy=gpdb.ExternalPolicy,\n external_segment=group_policy_mapping_db.ExternalSegmentMapping,\n nat_pool=group_policy_mapping_db.NATPoolMapping,\n network_service_policy=gpdb.NetworkServicePolicy)\n def __init__(self):\n self.extension_manager = ext_manager.ExtensionManager()\n self.policy_driver_manager = manager.PolicyDriverManager()\n super(GroupPolicyPlugin, self).__init__()\n self.extension_manager.initialize()\n self.policy_driver_manager.initialize()\n\n def _filter_extended_result(self, result, filters):\n filters = filters or {}\n for field in filters:\n # Ignore unknown fields\n if field in result:\n if result[field] not in filters[field]:\n break\n else:\n return result\n\n def _add_fixed_ips_to_port_attributes(self, policy_target):\n if 'fixed_ips' in policy_target['policy_target'] and (\n policy_target['policy_target']['fixed_ips'] is not (\n constants.ATTR_NOT_SPECIFIED)):\n port_attributes = {'fixed_ips': policy_target[\n 'policy_target']['fixed_ips']}\n policy_target['policy_target'].update(\n {'port_attributes': port_attributes})\n\n @log.log_method_call\n @n_utils.transaction_guard\n @db_api.retry_if_session_inactive()\n def create_policy_target(self, context, policy_target):\n self._ensure_tenant(context, policy_target['policy_target'])\n with db_api.CONTEXT_WRITER.using(context):\n session = context.session\n self._add_fixed_ips_to_port_attributes(policy_target)\n result = super(GroupPolicyPlugin,\n self).create_policy_target(context, policy_target)\n self.extension_manager.process_create_policy_target(\n session, policy_target, result)\n self._validate_shared_create(\n self, context, result, 'policy_target')\n policy_context = p_context.PolicyTargetContext(self, context,\n result)\n self.policy_driver_manager.create_policy_target_precommit(\n policy_context)\n\n try:\n self.policy_driver_manager.create_policy_target_postcommit(\n policy_context)\n except Exception:\n with excutils.save_and_reraise_exception():\n LOG.exception(\"create_policy_target_postcommit \"\n \"failed, deleting policy_target %s\",\n result['id'])\n self.delete_policy_target(context, result['id'])\n\n return self.get_policy_target(context, result['id'])\n\n @log.log_method_call\n @n_utils.transaction_guard\n @db_api.retry_if_session_inactive()\n def update_policy_target(self, context, policy_target_id, policy_target):\n with db_api.CONTEXT_WRITER.using(context):\n session = context.session\n self._add_fixed_ips_to_port_attributes(policy_target)\n original_policy_target = self.get_policy_target(context,\n policy_target_id)\n updated_policy_target = super(\n GroupPolicyPlugin, self).update_policy_target(\n context, policy_target_id, policy_target)\n self.extension_manager.process_update_policy_target(\n session, policy_target, updated_policy_target)\n self._validate_shared_update(self, context, original_policy_target,\n updated_policy_target,\n 'policy_target')\n policy_context = p_context.PolicyTargetContext(\n self, context, updated_policy_target,\n original_policy_target=original_policy_target)\n self.policy_driver_manager.update_policy_target_precommit(\n policy_context)\n\n self.policy_driver_manager.update_policy_target_postcommit(\n policy_context)\n return self.get_policy_target(context, policy_target_id)\n\n @log.log_method_call\n @n_utils.transaction_guard\n @db_api.retry_if_session_inactive()\n def delete_policy_target(self, context, policy_target_id):\n with db_api.CONTEXT_WRITER.using(context):\n policy_target = self.get_policy_target(context, policy_target_id)\n policy_context = p_context.PolicyTargetContext(\n self, context, policy_target)\n self.policy_driver_manager.delete_policy_target_precommit(\n policy_context)\n super(GroupPolicyPlugin, self).delete_policy_target(\n context, policy_target_id)\n\n try:\n self.policy_driver_manager.delete_policy_target_postcommit(\n policy_context)\n except Exception:\n LOG.exception(\"delete_policy_target_postcommit failed \"\n \"for policy_target %s\",\n policy_target_id)\n\n @log.log_method_call\n @db_api.retry_if_session_inactive()\n def get_policy_target(self, context, policy_target_id, fields=None):\n return self._get_resource(context, 'policy_target', policy_target_id,\n 'PolicyTargetContext', fields=fields)\n\n @log.log_method_call\n @db_api.retry_if_session_inactive()\n def get_policy_targets(self, context, filters=None, fields=None,\n sorts=None, limit=None, marker=None,\n page_reverse=False):\n return self._get_resources(\n context, 'policy_target', 'PolicyTargetContext',\n filters=filters, fields=fields, sorts=sorts, limit=limit,\n marker=marker, page_reverse=page_reverse)\n\n @log.log_method_call\n @n_utils.transaction_guard\n @db_api.retry_if_session_inactive()\n def create_policy_target_group(self, context, policy_target_group):\n self._ensure_tenant(context,\n policy_target_group['policy_target_group'])\n with db_api.CONTEXT_WRITER.using(context):\n session = context.session\n result = super(GroupPolicyPlugin,\n self).create_policy_target_group(\n context, policy_target_group)\n self.extension_manager.process_create_policy_target_group(\n session, policy_target_group, result)\n self._validate_shared_create(self, context, result,\n 'policy_target_group')\n policy_context = p_context.PolicyTargetGroupContext(\n self, context, result)\n self.policy_driver_manager.create_policy_target_group_precommit(\n policy_context)\n\n try:\n self.policy_driver_manager.create_policy_target_group_postcommit(\n policy_context)\n except Exception:\n with excutils.save_and_reraise_exception():\n LOG.exception(\"create_policy_target_group_postcommit \"\n \"failed, deleting policy_target_group %s\",\n result['id'])\n self.delete_policy_target_group(context, result['id'])\n\n return self.get_policy_target_group(context, result['id'])\n\n @log.log_method_call\n @n_utils.transaction_guard\n @db_api.retry_if_session_inactive()\n def update_policy_target_group(self, context, policy_target_group_id,\n policy_target_group):\n with db_api.CONTEXT_WRITER.using(context):\n session = context.session\n original_policy_target_group = self.get_policy_target_group(\n context, policy_target_group_id)\n updated_policy_target_group = super(\n GroupPolicyPlugin, self).update_policy_target_group(\n context, policy_target_group_id, policy_target_group)\n # REVISIT(rkukura): We could potentially allow updates to\n # l2_policy_id when no policy targets exist. This would\n # involve removing each old subnet from the l3_policy's\n # router, deleting each old subnet, creating a new subnet on\n # the new l2_policy's network, and adding that subnet to the\n # l3_policy's router in postcommit. Its also possible that new\n # subnet[s] would be provided explicitly as part of the\n # update.\n old_l2p = original_policy_target_group['l2_policy_id']\n new_l2p = updated_policy_target_group['l2_policy_id']\n if old_l2p and old_l2p != new_l2p:\n raise gp_exc.L2PolicyUpdateOfPolicyTargetGroupNotSupported()\n\n self.extension_manager.process_update_policy_target_group(\n session, policy_target_group, updated_policy_target_group)\n self._validate_shared_update(\n self, context, original_policy_target_group,\n updated_policy_target_group, 'policy_target_group')\n policy_context = p_context.PolicyTargetGroupContext(\n self, context, updated_policy_target_group,\n original_policy_target_group=original_policy_target_group)\n self.policy_driver_manager.update_policy_target_group_precommit(\n policy_context)\n\n self.policy_driver_manager.update_policy_target_group_postcommit(\n policy_context)\n\n return self.get_policy_target_group(context, policy_target_group_id)\n\n @log.log_method_call\n @n_utils.transaction_guard\n @db_api.retry_if_session_inactive()\n def delete_policy_target_group(self, context, policy_target_group_id):\n with db_api.CONTEXT_WRITER.using(context):\n policy_target_group = self.get_policy_target_group(\n context, policy_target_group_id)\n pt_ids = policy_target_group['policy_targets']\n for pt in self.get_policy_targets(context.elevated(),\n {'id': pt_ids}):\n if pt['port_id'] and self._is_port_bound(pt['port_id']):\n raise gp_exc.PolicyTargetGroupInUse(\n policy_target_group=policy_target_group_id)\n policy_context = p_context.PolicyTargetGroupContext(\n self, context, policy_target_group)\n self.policy_driver_manager.delete_policy_target_group_precommit(\n policy_context)\n\n # Disassociate all the PRSs first, this will trigger service chains\n # deletion.\n self.update_policy_target_group(\n context, policy_target_group_id,\n {'policy_target_group': {'provided_policy_rule_sets': {},\n 'consumed_policy_rule_sets': {}}})\n policy_context.current['provided_policy_rule_sets'] = []\n policy_context.current['consumed_policy_rule_sets'] = []\n\n # Proxy PTGs must be deleted before the group itself.\n if policy_target_group.get('proxy_group_id'):\n try:\n self.delete_policy_target_group(\n context, policy_target_group['proxy_group_id'])\n except gpex.PolicyTargetGroupNotFound:\n LOG.warning('PTG %s already deleted',\n policy_target_group['proxy_group_id'])\n\n # Delete the PTG's PTs, which should not be in-use.\n for pt in self.get_policy_targets(context, {'id': pt_ids}):\n self.delete_policy_target(context, pt['id'])\n\n # REVISIT: The DB layer method called here manages its own\n # transaction, but ideally would be called within the same\n # transaction as the precommit calls above. Maybe the cleanup\n # of PRSs, proxy PTGs and PTs, which much be done outside any\n # transaction, could be moved before the initial transaction,\n # possibly within a loop to ensure no PTs concurrently become\n # in-use before proceding with the PTG deletion transaction.\n super(GroupPolicyPlugin, self).delete_policy_target_group(\n context, policy_target_group_id)\n\n try:\n self.policy_driver_manager.delete_policy_target_group_postcommit(\n policy_context)\n except Exception:\n LOG.exception(\"delete_policy_target_group_postcommit failed \"\n \"for policy_target_group %s\",\n policy_target_group_id)\n\n @log.log_method_call\n @db_api.retry_if_session_inactive()\n def get_policy_target_group(self, context, policy_target_group_id,\n fields=None):\n return self._get_resource(context, 'policy_target_group',\n policy_target_group_id,\n 'PolicyTargetGroupContext', fields=fields)\n\n @log.log_method_call\n @db_api.retry_if_session_inactive()\n def get_policy_target_groups(self, context, filters=None, fields=None,\n sorts=None, limit=None, marker=None,\n page_reverse=False):\n return self._get_resources(\n context, 'policy_target_group', 'PolicyTargetGroupContext',\n filters=filters, fields=fields, sorts=sorts, limit=limit,\n marker=marker, page_reverse=page_reverse)\n\n @log.log_method_call\n @n_utils.transaction_guard\n @db_api.retry_if_session_inactive()\n def create_application_policy_group(self, context,\n application_policy_group):\n self._ensure_tenant(\n context, application_policy_group['application_policy_group'])\n with db_api.CONTEXT_WRITER.using(context):\n session = context.session\n pdm = self.policy_driver_manager\n result = super(GroupPolicyPlugin,\n self).create_application_policy_group(\n context, application_policy_group)\n self.extension_manager.process_create_application_policy_group(\n session, application_policy_group, result)\n self._validate_shared_create(self, context, result,\n 'application_policy_group')\n policy_context = p_context.ApplicationPolicyGroupContext(\n self, context, result)\n pdm.create_application_policy_group_precommit(policy_context)\n\n try:\n pdm.create_application_policy_group_postcommit(policy_context)\n except Exception:\n with excutils.save_and_reraise_exception():\n LOG.exception(\"create_application_policy_group_postcommit \"\n \"failed, deleting APG %s\",\n result['id'])\n self.delete_application_policy_group(context, result['id'])\n\n return self.get_application_policy_group(context, result['id'])\n\n @log.log_method_call\n @n_utils.transaction_guard\n @db_api.retry_if_session_inactive()\n def update_application_policy_group(self, context,\n application_policy_group_id,\n application_policy_group):\n with db_api.CONTEXT_WRITER.using(context):\n session = context.session\n pdm = self.policy_driver_manager\n original_application_policy_group = (\n self.get_application_policy_group(\n context, application_policy_group_id))\n updated_application_policy_group = super(\n GroupPolicyPlugin, self).update_application_policy_group(\n context, application_policy_group_id,\n application_policy_group)\n\n self.extension_manager.process_update_application_policy_group(\n session, application_policy_group,\n updated_application_policy_group)\n self._validate_shared_update(\n self, context, original_application_policy_group,\n updated_application_policy_group, 'application_policy_group')\n policy_context = p_context.ApplicationPolicyGroupContext(\n self, context, updated_application_policy_group,\n original_application_policy_group=(\n original_application_policy_group))\n pdm.update_application_policy_group_precommit(policy_context)\n\n pdm.update_application_policy_group_postcommit(policy_context)\n\n return self.get_application_policy_group(context,\n application_policy_group_id)\n\n @log.log_method_call\n @n_utils.transaction_guard\n @db_api.retry_if_session_inactive()\n def delete_application_policy_group(self, context,\n application_policy_group_id):\n with db_api.CONTEXT_WRITER.using(context):\n pdm = self.policy_driver_manager\n application_policy_group = self.get_application_policy_group(\n context, application_policy_group_id)\n policy_context = p_context.ApplicationPolicyGroupContext(\n self, context, application_policy_group)\n pdm.delete_application_policy_group_precommit(policy_context)\n\n super(GroupPolicyPlugin, self).delete_application_policy_group(\n context, application_policy_group_id)\n\n try:\n pdm.delete_application_policy_group_postcommit(policy_context)\n except Exception:\n LOG.exception(\"delete_application_policy_group_postcommit \"\n \"failed for application_policy_group %s\",\n application_policy_group_id)\n\n @log.log_method_call\n @db_api.retry_if_session_inactive()\n def get_application_policy_group(self, context,\n application_policy_group_id, fields=None):\n return self._get_resource(context, 'application_policy_group',\n application_policy_group_id,\n 'ApplicationPolicyGroupContext',\n fields=fields)\n\n @log.log_method_call\n @db_api.retry_if_session_inactive()\n def get_application_policy_groups(self, context, filters=None, fields=None,\n sorts=None, limit=None, marker=None,\n page_reverse=False):\n return self._get_resources(\n context, 'application_policy_group',\n 'ApplicationPolicyGroupContext', filters=filters, fields=fields,\n sorts=sorts, limit=limit, marker=marker, page_reverse=page_reverse)\n\n @log.log_method_call\n @n_utils.transaction_guard\n @db_api.retry_if_session_inactive()\n def create_l2_policy(self, context, l2_policy):\n self._ensure_tenant(context, l2_policy['l2_policy'])\n with db_api.CONTEXT_WRITER.using(context):\n session = context.session\n result = super(GroupPolicyPlugin,\n self).create_l2_policy(context, l2_policy)\n self.extension_manager.process_create_l2_policy(\n session, l2_policy, result)\n self._validate_shared_create(self, context, result, 'l2_policy')\n policy_context = p_context.L2PolicyContext(self, context, result)\n self.policy_driver_manager.create_l2_policy_precommit(\n policy_context)\n\n try:\n self.policy_driver_manager.create_l2_policy_postcommit(\n policy_context)\n except Exception:\n with excutils.save_and_reraise_exception():\n LOG.exception(\"create_l2_policy_postcommit \"\n \"failed, deleting l2_policy %s\",\n result['id'])\n self.delete_l2_policy(context, result['id'])\n\n return self.get_l2_policy(context, result['id'])\n\n @log.log_method_call\n @n_utils.transaction_guard\n @db_api.retry_if_session_inactive()\n def update_l2_policy(self, context, l2_policy_id, l2_policy):\n with db_api.CONTEXT_WRITER.using(context):\n session = context.session\n original_l2_policy = self.get_l2_policy(context, l2_policy_id)\n updated_l2_policy = super(GroupPolicyPlugin,\n self).update_l2_policy(\n context, l2_policy_id, l2_policy)\n self.extension_manager.process_update_l2_policy(\n session, l2_policy, updated_l2_policy)\n self._validate_shared_update(self, context, original_l2_policy,\n updated_l2_policy, 'l2_policy')\n policy_context = p_context.L2PolicyContext(\n self, context, updated_l2_policy,\n original_l2_policy=original_l2_policy)\n self.policy_driver_manager.update_l2_policy_precommit(\n policy_context)\n\n self.policy_driver_manager.update_l2_policy_postcommit(\n policy_context)\n\n return self.get_l2_policy(context, l2_policy_id)\n\n @log.log_method_call\n @n_utils.transaction_guard\n @db_api.retry_if_session_inactive()\n def delete_l2_policy(self, context, l2_policy_id):\n with db_api.CONTEXT_WRITER.using(context):\n l2_policy = self.get_l2_policy(context, l2_policy_id)\n policy_context = p_context.L2PolicyContext(self, context,\n l2_policy)\n self.policy_driver_manager.delete_l2_policy_precommit(\n policy_context)\n super(GroupPolicyPlugin, self).delete_l2_policy(context,\n l2_policy_id)\n\n try:\n self.policy_driver_manager.delete_l2_policy_postcommit(\n policy_context)\n except Exception:\n LOG.exception(\"delete_l2_policy_postcommit failed \"\n \"for l2_policy %s\", l2_policy_id)\n\n @log.log_method_call\n @db_api.retry_if_session_inactive()\n def get_l2_policy(self, context, l2_policy_id, fields=None):\n return self._get_resource(context, 'l2_policy',\n l2_policy_id,\n 'L2PolicyContext', fields=fields)\n\n @log.log_method_call\n @db_api.retry_if_session_inactive()\n def get_l2_policies(self, context, filters=None, fields=None,\n sorts=None, limit=None, marker=None,\n page_reverse=False):\n return self._get_resources(\n context, 'l2_policy', 'L2PolicyContext',\n filters=filters, fields=fields, sorts=sorts, limit=limit,\n marker=marker, page_reverse=page_reverse)\n\n @log.log_method_call\n @n_utils.transaction_guard\n @db_api.retry_if_session_inactive()\n def create_network_service_policy(self, context, network_service_policy):\n self._ensure_tenant(\n context, network_service_policy['network_service_policy'])\n with db_api.CONTEXT_WRITER.using(context):\n session = context.session\n result = super(GroupPolicyPlugin,\n self).create_network_service_policy(\n context, network_service_policy)\n self.extension_manager.process_create_network_service_policy(\n session, network_service_policy, result)\n self._validate_shared_create(self, context, result,\n 'network_service_policy')\n policy_context = p_context.NetworkServicePolicyContext(\n self, context, result)\n pdm = self.policy_driver_manager\n pdm.create_network_service_policy_precommit(\n policy_context)\n\n try:\n pdm.create_network_service_policy_postcommit(\n policy_context)\n except Exception:\n with excutils.save_and_reraise_exception():\n LOG.exception(\n \"create_network_service_policy_postcommit \"\n \"failed, deleting network_service_policy %s\",\n result['id'])\n self.delete_network_service_policy(context, result['id'])\n\n return self.get_network_service_policy(context, result['id'])\n\n @log.log_method_call\n @n_utils.transaction_guard\n @db_api.retry_if_session_inactive()\n def update_network_service_policy(self, context, network_service_policy_id,\n network_service_policy):\n with db_api.CONTEXT_WRITER.using(context):\n session = context.session\n original_network_service_policy = super(\n GroupPolicyPlugin, self).get_network_service_policy(\n context, network_service_policy_id)\n updated_network_service_policy = super(\n GroupPolicyPlugin, self).update_network_service_policy(\n context, network_service_policy_id, network_service_policy)\n self.extension_manager.process_update_network_service_policy(\n session, network_service_policy,\n updated_network_service_policy)\n self._validate_shared_update(\n self, context, original_network_service_policy,\n updated_network_service_policy, 'network_service_policy')\n policy_context = p_context.NetworkServicePolicyContext(\n self, context, updated_network_service_policy,\n original_network_service_policy=(\n original_network_service_policy))\n self.policy_driver_manager.update_network_service_policy_precommit(\n policy_context)\n\n self.policy_driver_manager.update_network_service_policy_postcommit(\n policy_context)\n return self.get_network_service_policy(context,\n network_service_policy_id)\n\n @log.log_method_call\n @n_utils.transaction_guard\n @db_api.retry_if_session_inactive()\n def delete_network_service_policy(\n self, context, network_service_policy_id):\n with db_api.CONTEXT_WRITER.using(context):\n network_service_policy = self.get_network_service_policy(\n context, network_service_policy_id)\n policy_context = p_context.NetworkServicePolicyContext(\n self, context, network_service_policy)\n self.policy_driver_manager.delete_network_service_policy_precommit(\n policy_context)\n super(GroupPolicyPlugin, self).delete_network_service_policy(\n context, network_service_policy_id)\n\n try:\n pdm = self.policy_driver_manager\n pdm.delete_network_service_policy_postcommit(policy_context)\n except Exception:\n LOG.exception(\n \"delete_network_service_policy_postcommit failed \"\n \"for network_service_policy %s\", network_service_policy_id)\n\n @log.log_method_call\n @db_api.retry_if_session_inactive()\n def get_network_service_policy(self, context, network_service_policy_id,\n fields=None):\n return self._get_resource(context, 'network_service_policy',\n network_service_policy_id,\n 'NetworkServicePolicyContext', fields=fields)\n\n @log.log_method_call\n @db_api.retry_if_session_inactive()\n def get_network_service_policies(self, context, filters=None, fields=None,\n sorts=None, limit=None, marker=None,\n page_reverse=False):\n return self._get_resources(\n context, 'network_service_policy', 'NetworkServicePolicyContext',\n filters=filters, fields=fields, sorts=sorts, limit=limit,\n marker=marker, page_reverse=page_reverse)\n\n @log.log_method_call\n @n_utils.transaction_guard\n @db_api.retry_if_session_inactive()\n def create_l3_policy(self, context, l3_policy):\n self._ensure_tenant(context, l3_policy['l3_policy'])\n with db_api.CONTEXT_WRITER.using(context):\n session = context.session\n result = super(GroupPolicyPlugin,\n self).create_l3_policy(context, l3_policy)\n self.extension_manager.process_create_l3_policy(\n session, l3_policy, result)\n self._validate_shared_create(self, context, result, 'l3_policy')\n self._validate_l3p_es(context, result)\n policy_context = p_context.L3PolicyContext(self, context,\n result)\n self.policy_driver_manager.create_l3_policy_precommit(\n policy_context)\n\n try:\n self.policy_driver_manager.create_l3_policy_postcommit(\n policy_context)\n except Exception:\n with excutils.save_and_reraise_exception():\n LOG.exception(\"create_l3_policy_postcommit \"\n \"failed, deleting l3_policy %s\",\n result['id'])\n self.delete_l3_policy(context, result['id'])\n\n return self.get_l3_policy(context, result['id'])\n\n @log.log_method_call\n @n_utils.transaction_guard\n @db_api.retry_if_session_inactive()\n def update_l3_policy(self, context, l3_policy_id, l3_policy):\n with db_api.CONTEXT_WRITER.using(context):\n session = context.session\n original_l3_policy = self.get_l3_policy(context, l3_policy_id)\n updated_l3_policy = super(\n GroupPolicyPlugin, self).update_l3_policy(\n context, l3_policy_id, l3_policy)\n self.extension_manager.process_update_l3_policy(\n session, l3_policy, updated_l3_policy)\n self._validate_shared_update(self, context, original_l3_policy,\n updated_l3_policy, 'l3_policy')\n self._validate_l3p_es(context, updated_l3_policy,\n original_l3_policy)\n policy_context = p_context.L3PolicyContext(\n self, context, updated_l3_policy,\n original_l3_policy=original_l3_policy)\n self.policy_driver_manager.update_l3_policy_precommit(\n policy_context)\n\n self.policy_driver_manager.update_l3_policy_postcommit(\n policy_context)\n return self.get_l3_policy(context, l3_policy_id)\n\n @log.log_method_call\n @n_utils.transaction_guard\n @db_api.retry_if_session_inactive()\n def delete_l3_policy(self, context, l3_policy_id, check_unused=False):\n with db_api.CONTEXT_WRITER.using(context):\n session = context.session\n if (check_unused and\n (session.query(group_policy_mapping_db.L2PolicyMapping).\n filter_by(l3_policy_id=l3_policy_id).count())):\n return False\n l3_policy = self.get_l3_policy(context, l3_policy_id)\n policy_context = p_context.L3PolicyContext(self, context,\n l3_policy)\n self.policy_driver_manager.delete_l3_policy_precommit(\n policy_context)\n super(GroupPolicyPlugin, self).delete_l3_policy(context,\n l3_policy_id)\n\n try:\n self.policy_driver_manager.delete_l3_policy_postcommit(\n policy_context)\n except Exception:\n LOG.exception(\"delete_l3_policy_postcommit failed \"\n \"for l3_policy %s\", l3_policy_id)\n return True\n\n @log.log_method_call\n @db_api.retry_if_session_inactive()\n def get_l3_policy(self, context, l3_policy_id, fields=None):\n return self._get_resource(context, 'l3_policy',\n l3_policy_id,\n 'L3PolicyContext', fields=fields)\n\n @log.log_method_call\n @db_api.retry_if_session_inactive()\n def get_l3_policies(self, context, filters=None, fields=None,\n sorts=None, limit=None, marker=None,\n page_reverse=False):\n return self._get_resources(\n context, 'l3_policy', 'L3PolicyContext',\n filters=filters, fields=fields, sorts=sorts, limit=limit,\n marker=marker, page_reverse=page_reverse)\n\n @log.log_method_call\n @n_utils.transaction_guard\n @db_api.retry_if_session_inactive()\n def create_policy_classifier(self, context, policy_classifier):\n self._ensure_tenant(context, policy_classifier['policy_classifier'])\n with db_api.CONTEXT_WRITER.using(context):\n session = context.session\n result = super(\n GroupPolicyPlugin, self).create_policy_classifier(\n context, policy_classifier)\n self.extension_manager.process_create_policy_classifier(\n session, policy_classifier, result)\n self._validate_shared_create(\n self, context, result, 'policy_classifier')\n policy_context = p_context.PolicyClassifierContext(self, context,\n result)\n self.policy_driver_manager.create_policy_classifier_precommit(\n policy_context)\n\n try:\n self.policy_driver_manager.create_policy_classifier_postcommit(\n policy_context)\n except Exception:\n with excutils.save_and_reraise_exception():\n LOG.exception(\n \"policy_driver_manager.create_policy_classifier_postcommit\"\n \" failed, deleting policy_classifier %s\", result['id'])\n self.delete_policy_classifier(context, result['id'])\n\n return self.get_policy_classifier(context, result['id'])\n\n @log.log_method_call\n @n_utils.transaction_guard\n @db_api.retry_if_session_inactive()\n def update_policy_classifier(self, context, id, policy_classifier):\n with db_api.CONTEXT_WRITER.using(context):\n session = context.session\n original_policy_classifier = super(\n GroupPolicyPlugin, self).get_policy_classifier(context, id)\n updated_policy_classifier = super(\n GroupPolicyPlugin, self).update_policy_classifier(\n context, id, policy_classifier)\n self.extension_manager.process_update_policy_classifier(\n session, policy_classifier, updated_policy_classifier)\n self._validate_shared_update(\n self, context, original_policy_classifier,\n updated_policy_classifier, 'policy_classifier')\n policy_context = p_context.PolicyClassifierContext(\n self, context, updated_policy_classifier,\n original_policy_classifier=original_policy_classifier)\n self.policy_driver_manager.update_policy_classifier_precommit(\n policy_context)\n\n self.policy_driver_manager.update_policy_classifier_postcommit(\n policy_context)\n return self.get_policy_classifier(context, id)\n\n @log.log_method_call\n @n_utils.transaction_guard\n @db_api.retry_if_session_inactive()\n def delete_policy_classifier(self, context, id):\n with db_api.CONTEXT_WRITER.using(context):\n policy_classifier = self.get_policy_classifier(context, id)\n policy_context = p_context.PolicyClassifierContext(\n self, context, policy_classifier)\n self.policy_driver_manager.delete_policy_classifier_precommit(\n policy_context)\n super(GroupPolicyPlugin, self).delete_policy_classifier(\n context, id)\n\n try:\n self.policy_driver_manager.delete_policy_classifier_postcommit(\n policy_context)\n except Exception:\n LOG.exception(\"delete_policy_classifier_postcommit failed \"\n \"for policy_classifier %s\", id)\n\n @log.log_method_call\n @db_api.retry_if_session_inactive()\n def get_policy_classifier(self, context, policy_classifier_id,\n fields=None):\n return self._get_resource(context, 'policy_classifier',\n policy_classifier_id,\n 'PolicyClassifierContext', fields=fields)\n\n @log.log_method_call\n @db_api.retry_if_session_inactive()\n def get_policy_classifiers(self, context, filters=None, fields=None,\n sorts=None, limit=None, marker=None,\n page_reverse=False):\n return self._get_resources(\n context, 'policy_classifier', 'PolicyClassifierContext',\n filters=filters, fields=fields, sorts=sorts, limit=limit,\n marker=marker, page_reverse=page_reverse)\n\n @log.log_method_call\n @n_utils.transaction_guard\n @db_api.retry_if_session_inactive()\n def create_policy_action(self, context, policy_action):\n self._ensure_tenant(context, policy_action['policy_action'])\n with db_api.CONTEXT_WRITER.using(context):\n session = context.session\n result = super(GroupPolicyPlugin,\n self).create_policy_action(context, policy_action)\n self.extension_manager.process_create_policy_action(\n session, policy_action, result)\n self._validate_shared_create(self, context, result,\n 'policy_action')\n self._validate_action_value(context, result)\n policy_context = p_context.PolicyActionContext(self, context,\n result)\n self.policy_driver_manager.create_policy_action_precommit(\n policy_context)\n\n try:\n self.policy_driver_manager.create_policy_action_postcommit(\n policy_context)\n except Exception:\n with excutils.save_and_reraise_exception():\n LOG.exception(\n \"policy_driver_manager.create_policy_action_postcommit \"\n \"failed, deleting policy_action %s\", result['id'])\n self.delete_policy_action(context, result['id'])\n\n return self.get_policy_action(context, result['id'])\n\n @log.log_method_call\n @n_utils.transaction_guard\n @db_api.retry_if_session_inactive()\n def update_policy_action(self, context, id, policy_action):\n with db_api.CONTEXT_WRITER.using(context):\n session = context.session\n original_policy_action = super(\n GroupPolicyPlugin, self).get_policy_action(context, id)\n updated_policy_action = super(\n GroupPolicyPlugin, self).update_policy_action(context, id,\n policy_action)\n self.extension_manager.process_update_policy_action(\n session, policy_action, updated_policy_action)\n self._validate_shared_update(self, context, original_policy_action,\n updated_policy_action,\n 'policy_action')\n self._validate_action_value(context, updated_policy_action)\n policy_context = p_context.PolicyActionContext(\n self, context, updated_policy_action,\n original_policy_action=original_policy_action)\n self.policy_driver_manager.update_policy_action_precommit(\n policy_context)\n\n self.policy_driver_manager.update_policy_action_postcommit(\n policy_context)\n return self.get_policy_action(context, id)\n\n @log.log_method_call\n @n_utils.transaction_guard\n @db_api.retry_if_session_inactive()\n def delete_policy_action(self, context, id):\n with db_api.CONTEXT_WRITER.using(context):\n policy_action = self.get_policy_action(context, id)\n policy_context = p_context.PolicyActionContext(self, context,\n policy_action)\n self.policy_driver_manager.delete_policy_action_precommit(\n policy_context)\n super(GroupPolicyPlugin, self).delete_policy_action(context, id)\n\n try:\n self.policy_driver_manager.delete_policy_action_postcommit(\n policy_context)\n except Exception:\n LOG.exception(\"delete_policy_action_postcommit failed \"\n \"for policy_action %s\", id)\n\n @log.log_method_call\n @db_api.retry_if_session_inactive()\n def get_policy_action(self, context, policy_action_id, fields=None):\n return self._get_resource(context, 'policy_action',\n policy_action_id,\n 'PolicyActionContext', fields=fields)\n\n @log.log_method_call\n @db_api.retry_if_session_inactive()\n def get_policy_actions(self, context, filters=None, fields=None,\n sorts=None, limit=None, marker=None,\n page_reverse=False):\n return self._get_resources(\n context, 'policy_action', 'PolicyActionContext',\n filters=filters, fields=fields, sorts=sorts, limit=limit,\n marker=marker, page_reverse=page_reverse)\n\n @log.log_method_call\n @n_utils.transaction_guard\n @db_api.retry_if_session_inactive()\n def create_policy_rule(self, context, policy_rule):\n self._ensure_tenant(context, policy_rule['policy_rule'])\n with db_api.CONTEXT_WRITER.using(context):\n session = context.session\n result = super(\n GroupPolicyPlugin, self).create_policy_rule(\n context, policy_rule)\n self.extension_manager.process_create_policy_rule(\n session, policy_rule, result)\n self._validate_shared_create(self, context, result, 'policy_rule')\n policy_context = p_context.PolicyRuleContext(self, context,\n result)\n self.policy_driver_manager.create_policy_rule_precommit(\n policy_context)\n\n try:\n self.policy_driver_manager.create_policy_rule_postcommit(\n policy_context)\n except Exception:\n with excutils.save_and_reraise_exception():\n LOG.exception(\n \"policy_driver_manager.create_policy_rule_postcommit\"\n \" failed, deleting policy_rule %s\", result['id'])\n self.delete_policy_rule(context, result['id'])\n\n return self.get_policy_rule(context, result['id'])\n\n @log.log_method_call\n @n_utils.transaction_guard\n @db_api.retry_if_session_inactive()\n def update_policy_rule(self, context, id, policy_rule):\n with db_api.CONTEXT_WRITER.using(context):\n session = context.session\n original_policy_rule = super(\n GroupPolicyPlugin, self).get_policy_rule(context, id)\n updated_policy_rule = super(\n GroupPolicyPlugin, self).update_policy_rule(\n context, id, policy_rule)\n self.extension_manager.process_update_policy_rule(\n session, policy_rule, updated_policy_rule)\n self._validate_shared_update(self, context, original_policy_rule,\n updated_policy_rule, 'policy_rule')\n policy_context = p_context.PolicyRuleContext(\n self, context, updated_policy_rule,\n original_policy_rule=original_policy_rule)\n self.policy_driver_manager.update_policy_rule_precommit(\n policy_context)\n\n self.policy_driver_manager.update_policy_rule_postcommit(\n policy_context)\n return self.get_policy_rule(context, id)\n\n @log.log_method_call\n @n_utils.transaction_guard\n @db_api.retry_if_session_inactive()\n def delete_policy_rule(self, context, id):\n with db_api.CONTEXT_WRITER.using(context):\n policy_rule = self.get_policy_rule(context, id)\n policy_context = p_context.PolicyRuleContext(self, context,\n policy_rule)\n self.policy_driver_manager.delete_policy_rule_precommit(\n policy_context)\n super(GroupPolicyPlugin, self).delete_policy_rule(\n context, id)\n\n try:\n self.policy_driver_manager.delete_policy_rule_postcommit(\n policy_context)\n except Exception:\n LOG.exception(\"delete_policy_rule_postcommit failed \"\n \"for policy_rule %s\", id)\n\n @log.log_method_call\n @db_api.retry_if_session_inactive()\n def get_policy_rule(self, context, policy_rule_id, fields=None):\n return self._get_resource(context, 'policy_rule',\n policy_rule_id,\n 'PolicyRuleContext', fields=fields)\n\n @log.log_method_call\n @db_api.retry_if_session_inactive()\n def get_policy_rules(self, context, filters=None, fields=None,\n sorts=None, limit=None, marker=None,\n page_reverse=False):\n return self._get_resources(\n context, 'policy_rule', 'PolicyRuleContext',\n filters=filters, fields=fields, sorts=sorts, limit=limit,\n marker=marker, page_reverse=page_reverse)\n\n @log.log_method_call\n @n_utils.transaction_guard\n @db_api.retry_if_session_inactive()\n def create_policy_rule_set(self, context, policy_rule_set):\n self._ensure_tenant(context, policy_rule_set['policy_rule_set'])\n with db_api.CONTEXT_WRITER.using(context):\n session = context.session\n result = super(GroupPolicyPlugin,\n self).create_policy_rule_set(\n context, policy_rule_set)\n self.extension_manager.process_create_policy_rule_set(\n session, policy_rule_set, result)\n self._validate_shared_create(\n self, context, result, 'policy_rule_set')\n policy_context = p_context.PolicyRuleSetContext(\n self, context, result)\n self.policy_driver_manager.create_policy_rule_set_precommit(\n policy_context)\n\n try:\n self.policy_driver_manager.create_policy_rule_set_postcommit(\n policy_context)\n except Exception:\n with excutils.save_and_reraise_exception():\n LOG.exception(\n \"policy_driver_manager.create_policy_rule_set_postcommit \"\n \"failed, deleting policy_rule_set %s\", result['id'])\n self.delete_policy_rule_set(context, result['id'])\n\n return self.get_policy_rule_set(context, result['id'])\n\n @log.log_method_call\n @n_utils.transaction_guard\n @db_api.retry_if_session_inactive()\n def update_policy_rule_set(self, context, id, policy_rule_set):\n with db_api.CONTEXT_WRITER.using(context):\n session = context.session\n original_policy_rule_set = super(\n GroupPolicyPlugin, self).get_policy_rule_set(context, id)\n updated_policy_rule_set = super(\n GroupPolicyPlugin, self).update_policy_rule_set(\n context, id, policy_rule_set)\n self.extension_manager.process_update_policy_rule_set(\n session, policy_rule_set, updated_policy_rule_set)\n self._validate_shared_update(\n self, context, original_policy_rule_set,\n updated_policy_rule_set, 'policy_rule_set')\n policy_context = p_context.PolicyRuleSetContext(\n self, context, updated_policy_rule_set,\n original_policy_rule_set=original_policy_rule_set)\n self.policy_driver_manager.update_policy_rule_set_precommit(\n policy_context)\n\n self.policy_driver_manager.update_policy_rule_set_postcommit(\n policy_context)\n return self.get_policy_rule_set(context, id)\n\n @log.log_method_call\n @n_utils.transaction_guard\n @db_api.retry_if_session_inactive()\n def delete_policy_rule_set(self, context, id):\n with db_api.CONTEXT_WRITER.using(context):\n policy_rule_set = self.get_policy_rule_set(context, id)\n policy_context = p_context.PolicyRuleSetContext(\n self, context, policy_rule_set)\n self.policy_driver_manager.delete_policy_rule_set_precommit(\n policy_context)\n super(GroupPolicyPlugin, self).delete_policy_rule_set(context, id)\n\n try:\n self.policy_driver_manager.delete_policy_rule_set_postcommit(\n policy_context)\n except Exception:\n LOG.exception(\"delete_policy_rule_set_postcommit failed \"\n \"for policy_rule_set %s\", id)\n\n @log.log_method_call\n @db_api.retry_if_session_inactive()\n def get_policy_rule_set(self, context, policy_rule_set_id, fields=None):\n return self._get_resource(context, 'policy_rule_set',\n policy_rule_set_id,\n 'PolicyRuleSetContext', fields=fields)\n\n @log.log_method_call\n @db_api.retry_if_session_inactive()\n def get_policy_rule_sets(self, context, filters=None, fields=None,\n sorts=None, limit=None, marker=None,\n page_reverse=False):\n return self._get_resources(\n context, 'policy_rule_set', 'PolicyRuleSetContext',\n filters=filters, fields=fields, sorts=sorts, limit=limit,\n marker=marker, page_reverse=page_reverse)\n\n @log.log_method_call\n @n_utils.transaction_guard\n @db_api.retry_if_session_inactive()\n def create_external_segment(self, context, external_segment):\n self._ensure_tenant(context, external_segment['external_segment'])\n with db_api.CONTEXT_WRITER.using(context):\n session = context.session\n result = super(GroupPolicyPlugin,\n self).create_external_segment(context,\n external_segment)\n self.extension_manager.process_create_external_segment(\n session, external_segment, result)\n self._validate_shared_create(self, context, result,\n 'external_segment')\n policy_context = p_context.ExternalSegmentContext(\n self, context, result)\n (self.policy_driver_manager.\n create_external_segment_precommit(policy_context))\n # Validate the routes after the drivers had the chance to fill\n # the cidr field.\n self._validate_routes(context, result)\n\n try:\n (self.policy_driver_manager.\n create_external_segment_postcommit(policy_context))\n except Exception:\n with excutils.save_and_reraise_exception():\n LOG.exception(\"create_external_segment_postcommit \"\n \"failed, deleting external_segment \"\n \"%s\", result['id'])\n self.delete_external_segment(context, result['id'])\n\n return self.get_external_segment(context, result['id'])\n\n @log.log_method_call\n @n_utils.transaction_guard\n @db_api.retry_if_session_inactive()\n def update_external_segment(self, context, external_segment_id,\n external_segment):\n with db_api.CONTEXT_WRITER.using(context):\n session = context.session\n original_external_segment = super(\n GroupPolicyPlugin, self).get_external_segment(\n context, external_segment_id)\n updated_external_segment = super(\n GroupPolicyPlugin, self).update_external_segment(\n context, external_segment_id,\n external_segment)\n self.extension_manager.process_update_external_segment(\n session, external_segment, updated_external_segment)\n self._validate_shared_update(\n self, context, original_external_segment,\n updated_external_segment, 'external_segment')\n self._validate_routes(context, updated_external_segment,\n original_external_segment)\n # TODO(ivar): Validate Routes' GW in es subnet\n policy_context = p_context.ExternalSegmentContext(\n self, context, updated_external_segment,\n original_external_segment)\n (self.policy_driver_manager.\n update_external_segment_precommit(policy_context))\n\n self.policy_driver_manager.update_external_segment_postcommit(\n policy_context)\n return self.get_external_segment(context, external_segment_id)\n\n @log.log_method_call\n @n_utils.transaction_guard\n @db_api.retry_if_session_inactive()\n def delete_external_segment(self, context, external_segment_id):\n with db_api.CONTEXT_WRITER.using(context):\n es = self.get_external_segment(context, external_segment_id)\n if es['l3_policies'] or es['nat_pools'] or es['external_policies']:\n raise gpex.ExternalSegmentInUse(es_id=es['id'])\n policy_context = p_context.ExternalSegmentContext(\n self, context, es)\n (self.policy_driver_manager.\n delete_external_segment_precommit(policy_context))\n super(GroupPolicyPlugin, self).delete_external_segment(\n context, external_segment_id)\n\n try:\n (self.policy_driver_manager.\n delete_external_segment_postcommit(policy_context))\n except Exception:\n LOG.exception(\"delete_external_segment_postcommit failed \"\n \"for external_segment %s\",\n external_segment_id)\n return True\n\n @log.log_method_call\n @db_api.retry_if_session_inactive()\n def get_external_segment(self, context, external_segment_id, fields=None):\n return self._get_resource(context, 'external_segment',\n external_segment_id,\n 'ExternalSegmentContext', fields=fields)\n\n @log.log_method_call\n @db_api.retry_if_session_inactive()\n def get_external_segments(self, context, filters=None, fields=None,\n sorts=None, limit=None, marker=None,\n page_reverse=False):\n return self._get_resources(\n context, 'external_segment', 'ExternalSegmentContext',\n filters=filters, fields=fields, sorts=sorts, limit=limit,\n marker=marker, page_reverse=page_reverse)\n\n @log.log_method_call\n @n_utils.transaction_guard\n @db_api.retry_if_session_inactive()\n def create_external_policy(self, context, external_policy):\n self._ensure_tenant(context, external_policy['external_policy'])\n with db_api.CONTEXT_WRITER.using(context):\n session = context.session\n result = super(GroupPolicyPlugin,\n self).create_external_policy(\n context, external_policy)\n self.extension_manager.process_create_external_policy(\n session, external_policy, result)\n self._validate_shared_create(self, context, result,\n 'external_policy')\n policy_context = p_context.ExternalPolicyContext(\n self, context, result)\n (self.policy_driver_manager.\n create_external_policy_precommit(policy_context))\n\n try:\n (self.policy_driver_manager.\n create_external_policy_postcommit(policy_context))\n except Exception:\n with excutils.save_and_reraise_exception():\n LOG.exception(\"create_external_policy_postcommit \"\n \"failed, deleting external_policy \"\n \"%s\", result['id'])\n self.delete_external_policy(context, result['id'])\n\n return self.get_external_policy(context, result['id'])\n\n @log.log_method_call\n @n_utils.transaction_guard\n @db_api.retry_if_session_inactive()\n def update_external_policy(self, context, external_policy_id,\n external_policy):\n with db_api.CONTEXT_WRITER.using(context):\n session = context.session\n original_external_policy = super(\n GroupPolicyPlugin, self).get_external_policy(\n context, external_policy_id)\n updated_external_policy = super(\n GroupPolicyPlugin, self).update_external_policy(\n context, external_policy_id,\n external_policy)\n self.extension_manager.process_update_external_policy(\n session, external_policy, updated_external_policy)\n self._validate_shared_update(\n self, context, original_external_policy,\n updated_external_policy, 'external_policy')\n policy_context = p_context.ExternalPolicyContext(\n self, context, updated_external_policy,\n original_external_policy)\n (self.policy_driver_manager.\n update_external_policy_precommit(policy_context))\n\n self.policy_driver_manager.update_external_policy_postcommit(\n policy_context)\n return self.get_external_policy(context, external_policy_id)\n\n @log.log_method_call\n @n_utils.transaction_guard\n @db_api.retry_if_session_inactive()\n def delete_external_policy(self, context, external_policy_id,\n check_unused=False):\n with db_api.CONTEXT_WRITER.using(context):\n es = self.get_external_policy(context, external_policy_id)\n policy_context = p_context.ExternalPolicyContext(\n self, context, es)\n (self.policy_driver_manager.\n delete_external_policy_precommit(policy_context))\n super(GroupPolicyPlugin, self).delete_external_policy(\n context, external_policy_id)\n\n try:\n self.policy_driver_manager.delete_external_policy_postcommit(\n policy_context)\n except Exception:\n LOG.exception(\"delete_external_policy_postcommit failed \"\n \"for external_policy %s\", external_policy_id)\n\n @log.log_method_call\n @db_api.retry_if_session_inactive()\n def get_external_policy(self, context, external_policy_id, fields=None):\n return self._get_resource(context, 'external_policy',\n external_policy_id,\n 'ExternalPolicyContext', fields=fields)\n\n @log.log_method_call\n @db_api.retry_if_session_inactive()\n def get_external_policies(self, context, filters=None, fields=None,\n sorts=None, limit=None, marker=None,\n page_reverse=False):\n return self._get_resources(\n context, 'external_policy', 'ExternalPolicyContext',\n filters=filters, fields=fields, sorts=sorts, limit=limit,\n marker=marker, page_reverse=page_reverse)\n\n @log.log_method_call\n @n_utils.transaction_guard\n @db_api.retry_if_session_inactive()\n def create_nat_pool(self, context, nat_pool):\n self._ensure_tenant(context, nat_pool['nat_pool'])\n with db_api.CONTEXT_WRITER.using(context):\n session = context.session\n result = super(GroupPolicyPlugin, self).create_nat_pool(\n context, nat_pool)\n self.extension_manager.process_create_nat_pool(session, nat_pool,\n result)\n self._validate_shared_create(self, context, result, 'nat_pool')\n policy_context = p_context.NatPoolContext(self, context, result)\n (self.policy_driver_manager.\n create_nat_pool_precommit(policy_context))\n\n try:\n (self.policy_driver_manager.\n create_nat_pool_postcommit(policy_context))\n except Exception:\n with excutils.save_and_reraise_exception():\n LOG.exception(\n \"create_nat_pool_postcommit failed, deleting \"\n \"nat_pool %s\", result['id'])\n self.delete_nat_pool(context, result['id'])\n\n return self.get_nat_pool(context, result['id'])\n\n @log.log_method_call\n @n_utils.transaction_guard\n @db_api.retry_if_session_inactive()\n def update_nat_pool(self, context, nat_pool_id, nat_pool):\n with db_api.CONTEXT_WRITER.using(context):\n session = context.session\n original_nat_pool = super(\n GroupPolicyPlugin, self).get_nat_pool(context, nat_pool_id)\n updated_nat_pool = super(\n GroupPolicyPlugin, self).update_nat_pool(context, nat_pool_id,\n nat_pool)\n self.extension_manager.process_update_nat_pool(\n session, nat_pool, updated_nat_pool)\n self._validate_shared_update(self, context, original_nat_pool,\n updated_nat_pool, 'nat_pool')\n policy_context = p_context.NatPoolContext(\n self, context, updated_nat_pool, original_nat_pool)\n (self.policy_driver_manager.\n update_nat_pool_precommit(policy_context))\n\n self.policy_driver_manager.update_nat_pool_postcommit(policy_context)\n return self.get_nat_pool(context, nat_pool_id)\n\n @log.log_method_call\n @n_utils.transaction_guard\n @db_api.retry_if_session_inactive()\n def delete_nat_pool(self, context, nat_pool_id, check_unused=False):\n with db_api.CONTEXT_WRITER.using(context):\n es = self.get_nat_pool(context, nat_pool_id)\n policy_context = p_context.NatPoolContext(self, context, es)\n (self.policy_driver_manager.delete_nat_pool_precommit(\n policy_context))\n super(GroupPolicyPlugin, self).delete_nat_pool(context,\n nat_pool_id)\n\n try:\n self.policy_driver_manager.delete_nat_pool_postcommit(\n policy_context)\n except Exception:\n LOG.exception(\"delete_nat_pool_postcommit failed \"\n \"for nat_pool %s\",\n nat_pool_id)\n\n @log.log_method_call\n @db_api.retry_if_session_inactive()\n def get_nat_pool(self, context, nat_pool_id, fields=None):\n return self._get_resource(context, 'nat_pool',\n nat_pool_id,\n 'NatPoolContext', fields=fields)\n\n @log.log_method_call\n @db_api.retry_if_session_inactive()\n def get_nat_pools(self, context, filters=None, fields=None,\n sorts=None, limit=None, marker=None,\n page_reverse=False):\n return self._get_resources(\n context, 'nat_pool', 'NatPoolContext',\n filters=filters, fields=fields, sorts=sorts, limit=limit,\n marker=marker, page_reverse=page_reverse)\n\n def _is_port_bound(self, port_id):\n # REVISIT(ivar): This operation shouldn't be done within a DB lock\n # once we refactor the server.\n not_bound = [portbindings.VIF_TYPE_UNBOUND,\n portbindings.VIF_TYPE_BINDING_FAILED]\n context = n_ctx.get_admin_context()\n port = directory.get_plugin().get_port(context, port_id)\n return (port.get('binding:vif_type') not in not_bound) and port.get(\n 'binding:host_id') and (port['device_owner'] or port['device_id'])\n\n def _ensure_tenant(self, context, resource):\n # TODO(Sumit): This check is ideally not required, but a bunch of UTs\n # are not setup correctly to populate the tenant_id, hence we\n # temporarily need to perform this check. This will go with the fix\n # for the deprecated get_tenant_id_for_create method.\n if 'tenant_id' in resource:\n tenant_id = resource['tenant_id']\n self.policy_driver_manager.ensure_tenant(context, tenant_id)\n","sub_path":"gbpservice/neutron/services/grouppolicy/plugin.py","file_name":"plugin.py","file_ext":"py","file_size_in_byte":86044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"549065362","text":"def read_file(file):\n with open(file) as f:\n content = [x.strip('\\n') for x in f.readlines()]\n f.close()\n return content\n\ndef create_bins(list):\n if list == listDec:\n sortBins = {item : [] for item in dictionIndexes[:10]}\n return sortBins\n elif list == listOct:\n sortBins = {item : [] for item in dictionIndexes[:8]}\n return sortBins\n elif list == listHex:\n sortBins = {item : [] for item in dictionIndexes}\n return sortBins\n\ndef sort(list, index):\n bins = create_bins(list)\n for key in bins:\n for num in list:\n if num[index] == key:\n bins[key].append(num)\n return bins\n\nmainBin = []\ndictionIndexes = \"0123456789ABCDEF\"\nsortBins = {}\n#Number lists\nlistDec = read_file(\"Number Lists/random_numbers10.txt\")\nlistHex = read_file(\"Number Lists/random_numbers4.txt\")\nlistOct = read_file(\"Number Lists/random_numbers3.txt\")\noutputFile = open(\"output.txt\", \"w\")\n\n#The main sort part, just need to change between listHex, Oct and Dec\nindex = -1\nwhile index > -11:\n sortBins = sort(listHex, index)\n for key in sorted(sortBins):\n for items in sortBins[key]:\n mainBin.append(items)\n if index == -10:\n break\n else:\n listHex = mainBin\n mainBin = []\n index = index - 1\n\nfor item in mainBin:\n outputFile.write(item + \"\\n\")","sub_path":"Assignment 1/Radix Sort/Radix Sort.py","file_name":"Radix Sort.py","file_ext":"py","file_size_in_byte":1376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"370806938","text":"from django.conf.urls import patterns, include, url\nfrom django.contrib import admin\nimport os\nadmin.autodiscover()\n\nfrom django.conf import settings\n\n\nfrom blog import urls as blog_urls\n\n\nurlpatterns = patterns('',\n\n # Examples:\n # url(r'^$', 'myFirstDjango.views.home', name='home'),\n # url(r'^blog/', include('blog.urls')),\n url(r'^admin/', include(admin.site.urls),name='admin'),\n url(r'^$',include(blog_urls)),\n url(r'blog/',include(blog_urls)),\n url('^markdown/', include('django_markdown.urls')),\n\n\t\n\n\n\n)\nif settings.DEBUG: \n urlpatterns += patterns('',\n\turl(r'^static/(?P.*)$', 'django.views.static.serve',\n\t\t{'document_root': os.path.join(settings.BASE_DIR,'media')},name=\"static\"),\n )\n\n\n","sub_path":"myFirstDjango/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"648489001","text":"from . import views\nfrom django.conf.urls import url\n\nurlpatterns = [\n url(r'^$', views.main_page, name='main_page'),\n url(r'^program/$', views.program, name='program'),\n url(r'^support/$', views.support, name='support'),\n url(r'^resettlement/$', views.resettlement, name='resettlement'),\n url(r'^about/$', views.about, name='about'),\n]","sub_path":"conference/pages/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"335371421","text":"\n\nfrom xai.brain.wordbase.verbs._blush import _BLUSH\n\n#calss header\nclass _BLUSHED(_BLUSH, ):\n\tdef __init__(self,): \n\t\t_BLUSH.__init__(self)\n\t\tself.name = \"BLUSHED\"\n\t\tself.specie = 'verbs'\n\t\tself.basic = \"blush\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/verbs/_blushed.py","file_name":"_blushed.py","file_ext":"py","file_size_in_byte":233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"614553897","text":"n,l=map(int,input().split())\na=[int(j)for j in input().split()]\nfor i in range(1,n):\n if a[i-1]+a[i]>=l:\n print(\"Possible\")\n for j in range(i+1,n)[::-1]:\n print(j)\n for j in range(1,i+1):\n print(j)\n exit()\nprint(\"Impossible\")","sub_path":"Python_codes/p04035/s836614544.py","file_name":"s836614544.py","file_ext":"py","file_size_in_byte":278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"291832826","text":"import os\nimport pickle\nimport salaga.utils.slgcodes as scd\n\n# The 2 main functions provided by local man to the upper layers\n\n\ndef store(key, data):\n retCode = checkDir()\n if(retCode != scd.SUCCESS):\n scd.printCode(retCode)\n return(None)\n try:\n slghomefd = open(scd.SLGHOME+\"/\"+key+\".salg\", 'wb')\n except FileNotFoundError:\n scd.printCode(scd.NOENT)\n return(None)\n pickle.dump(data, slghomefd)\n slghomefd.close()\n return(scd.SUCCESS)\n\n\ndef retrieve(key):\n retCode = checkDir()\n if(retCode != scd.SUCCESS):\n scd.printCode(retCode)\n return(None)\n try:\n slghomefd = open(scd.SLGHOME+\"/\"+key+\".salg\", 'rb')\n except FileNotFoundError:\n scd.printCode(scd.NOENT)\n return(None)\n data = pickle.load(slghomefd)\n slghomefd.close()\n return(data)\n\n# sub-Utility functions used by the above\n# functions\n\n\ndef checkDir():\n if(os.environ.get('SLGHOME') is None):\n return(scd.NOHOME)\n if(not os.access(scd.SLGHOME, os.W_OK)):\n return(scd.NOWPEM)\n if(not os.access(scd.SLGHOME, os.R_OK)):\n return(scd.NORPEM)\n return(scd.SUCCESS)\n","sub_path":"salaga/utils/localMan.py","file_name":"localMan.py","file_ext":"py","file_size_in_byte":1158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"396965290","text":"from DBUtils import update # 导入方法\nfrom DBUtils import select\n# 增、删、改测试\nsql = \"insert into user values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)\"\nparam = [\"s002\",\"旺财\",\"798946\",\"印度\",\"南京\",\"幸福大街\",\"s002\",8900.3,\"2021-09-07\",\"日本花旗银行\"]\n\n\n# 查询测试\nsql1 = \"select * from user where username = %s\"\nparam1 = [\"旺财\"]\n\ndata = select(sql1,param1)\nprint(data)\n","sub_path":"day07/工具测试.py","file_name":"工具测试.py","file_ext":"py","file_size_in_byte":399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"622716342","text":"import pandas as pd\nimport collections\n\ncsv_path = '/home/ec2usr/ds/metis/mteisgh/prework/dsp/python/faculty.csv'\n\nfaculty_df = pd.read_csv(csv_path)\n\n# Q1 unique degrees and frequencies\ndef dot_fix(w):\n if len(w)>2:\n if w != 'MPH':\n w = ''.join('.'.join([w[:2], w[2:], '']))\n return w\n \ndef re_dot(x):\n return ' '.join([dot_fix(w) for w in x.split()])\n\nfaculty_df[' degree'] = faculty_df[' degree'].apply(lambda x: str(x).replace('.', '').lstrip()).apply(re_dot)\n\ndegrees = []\nfor d in faculty_df[' degree']:\n for w in d.split():\n degrees.append(w)\n \nprint(collections.Counter(degrees))\n\n#Q2 titles\ndef of_change(w):\n if w == 'is':\n w = 'of'\n return w\n \ndef is_fix(x):\n if 'is' in set(x.split()):\n x = ' '.join([of_change(w) for w in x.split()])\n return x\n\nfaculty_df[' title'] = faculty_df[' title'].apply(is_fix)\nprint(collections.Counter(faculty_df[' title'].tolist()))\n\n#Q3 emails list\nemails = faculty_df[' email']\n\nprint(emails.tolist())\n\n#Q4 domains\ndef get_domain(x):\n start_loc = x.find('@')\n domain = x[start_loc+1:]\n return domain\n\nunique_domains = set(emails.map(get_domain).tolist())\n\nprint(unique_domains)\n\ndomain_count = len(unique_domains)\n\nprint(domain_count)\n\n\n\n\n","sub_path":"python/advanced_python_regex.py","file_name":"advanced_python_regex.py","file_ext":"py","file_size_in_byte":1267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"594862308","text":"import tushare as ts\nimport baostock as bs\nfrom time import sleep\n\n\nclass Stock:\n retried_num = 0\n RETRY_MAX_NUM = 5\n RETRY_DELAY_S = 30\n subscribe_rs = None\n\n @staticmethod\n def login():\n pass\n\n @staticmethod\n def logout():\n pass\n\n @staticmethod\n def subscribe_real_time(sub_code, sub_cb, param=None):\n pass\n\n @staticmethod\n def unsubscribe_real_time():\n pass\n\n @staticmethod\n def rs_to_list(result_data):\n return result_data\n\n @staticmethod\n def query_basic(code='', code_name=''):\n assert(isinstance(code, str))\n rs = bs.query_stock_basic(code, code_name)\n while Stock.retried_num < Stock.RETRY_MAX_NUM and rs.error_code != '0':\n sleep(Stock.RETRY_DELAY_S)\n rs = bs.query_stock_basic(code, code_name)\n Stock.retried_num += 1\n assert('0' == rs.error_code)\n Stock.retried_num = 0\n return Stock.rs_to_list(rs)\n\n @staticmethod\n def query_hist_kd(code, start_date=None, end_date=None):\n fields = 'date, open, close, high, low, volume, amount, adjustflag, turn, tradestatus, '\n fields += 'pctChg, peTTM, psTTM, pcfNcfTTM, pbMRQ, isST'\n\n code = code[-6:]\n rs = ts.get_k_data(code, ktype='d', start=start_date, end=end_date)\n data = rs[['date', 'open', 'close', 'high', 'low', 'volume']].values.tolist()\n res = []\n for i in range(len(data)):\n res.append(data[i][:-1] + [int(data[i][-1])*100] + [0] * 10)\n return res\n\n @staticmethod\n def query_hist_k5(code, start_date='', end_date='2099-12-31'):\n fields = 'time, open, close, high, low, volume, amount' # WARNING: amount NOT used any more\n code = code[-6:]\n rs = ts.get_hist_data(code, ktype='5', start=start_date, end=end_date)\n data = rs[['open', 'close', 'high', 'low', 'volume']].values.tolist()\n date = rs.index.tolist()\n res = []\n for i in range(len(data)):\n res.append([int(date[i][2:4]+date[i][5:7]+date[i][8:10]+date[i][11:13]+date[i][14:16])] + data[i][:-1] + [int(data[i][-1])*100] + [0])\n return res\n\n @staticmethod\n def query_stock_industry(code='', date=''):\n rs = bs.query_stock_industry(code, date)\n while Stock.retried_num < Stock.RETRY_MAX_NUM and rs.error_code != '0':\n sleep(Stock.RETRY_DELAY_S)\n rs = bs.query_stock_industry(code, date)\n Stock.retried_num += 1\n assert('0' == rs.error_code)\n Stock.retried_num = 0\n return Stock.rs_to_list(rs)\n\n @staticmethod\n def query_hs300_stocks():\n rs = bs.query_hs300_stocks()\n while Stock.retried_num < Stock.RETRY_MAX_NUM and rs.error_code != '0':\n sleep(Stock.RETRY_DELAY_S)\n rs = bs.query_hs300_stocks()\n Stock.retried_num += 1\n assert('0' == rs.error_code)\n Stock.retried_num = 0\n return Stock.rs_to_list(rs)\n\n @staticmethod\n def query_sz50_stocks():\n rs = bs.query_sz50_stocks()\n while Stock.retried_num < Stock.RETRY_MAX_NUM and rs.error_code != '0':\n sleep(Stock.RETRY_DELAY_S)\n rs = bs.query_sz50_stocks()\n Stock.retried_num += 1\n assert('0' == rs.error_code)\n Stock.retried_num = 0\n return Stock.rs_to_list(rs)\n\n @staticmethod\n def query_zz500_stocks():\n rs = bs.query_zz500_stocks()\n while Stock.retried_num < Stock.RETRY_MAX_NUM and rs.error_code != '0':\n sleep(Stock.RETRY_DELAY_S)\n rs = bs.query_zz500_stocks()\n Stock.retried_num += 1\n assert('0' == rs.error_code)\n Stock.retried_num = 0\n return Stock.rs_to_list(rs)\n\nif __name__ == '__main__':\n # for x in Stock.query_hist_k5('002602', '2019-04-15', '2099-12-31'):\n # print(x)\n # for x in Stock.query_hist_kd('002602', '2017-03-16', '2099-12-31'):\n # print(x)\n from utils_data import *\n s = StockUpdateRecord('sz.002602')\n s.update_k5()\n s.update_kd()\n","sub_path":"utils_tushare.py","file_name":"utils_tushare.py","file_ext":"py","file_size_in_byte":4055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"606594586","text":"import pandas as pd\nimport os\nimport random\nimport nltk\nimport string\nfrom nltk.corpus import stopwords \nimport gensim\nfrom gensim import corpora, models, similarities\n\nimport warnings\nwarnings.simplefilter('ignore')\n\n\n# Data Preparation and Preprocessing\n\nprint(\"Loading Data Sources\")\n#Load Data Source\ndata_path = os.getcwd() + '/dataset.csv'\nprint(\"Data source : \" + data_path)\ndata = pd.read_csv(data_path)\ndata.head()\n\ntemp_data = pd.read_csv(data_path)\nquestion_data = temp_data['MESSAGE']\n#Create Stop Word\nnewstopwords = set(stopwords.words('english'))\n#define Wordnet Lemmatizer \nWNlemma = nltk.WordNetLemmatizer()\n\n#Create Preprocessing Function\ndef pre_process(text):\n tokens = nltk.word_tokenize(text)\n tokens=[WNlemma.lemmatize(t) for t in tokens]\n tokens= [ t for t in tokens if t not in string.punctuation ]\n tokens=[word for word in tokens if word.lower() not in newstopwords]\n # bigr = nltk.bigrams(tokens[:10])\n # trigr = nltk.trigrams(tokens[:10])\n return(tokens)\n\n#greeting function\nGREETING_INPUTS = (\"hello\", \"hi\", \"greetings\", \"hello i need help\", \"good day\",\"hey\",\"i need help\", \"greetings\")\nGREETING_RESPONSES = [\"Good day, How may i of help?\", \"Hello, How can i help?\", \"hello\", \"I am glad! You are talking to me.\"]\n \ndef greeting(sentence):\n for word in sentence.split():\n if word.lower() in GREETING_INPUTS:\n return random.choice(GREETING_RESPONSES)\n\n\n\n#Preprocess Question Column\n# question_data = data['MESSAGE']\ndata['MESSAGE'] = data['MESSAGE'].apply(pre_process)\n \n#Define Questions\nquestion = data['MESSAGE']\n\n\ndictionary = corpora.Dictionary(question)\ncorpus = [dictionary.doc2bow(a) for a in question]\ntfidf = models.TfidfModel(corpus)\n \ncorpus_tfidf = tfidf[corpus]\nlsi = models.LsiModel(corpus_tfidf, id2word=dictionary, num_topics=650) # Threshold A\ncorpus_lsi = lsi[corpus_tfidf]\nindex = similarities.MatrixSimilarity(corpus_lsi)\n\n\n# ChatBot Function Definition\n\n\ndef Talk_To_Tau(test_set_sentence): \n # ---------------Tokenisation of user input -----------------------------#\n tokens = pre_process(test_set_sentence)\n texts = \" \".join(tokens) \n # -----------------------------------------------------------------------#\n \n # ---------------Find and Sort Similarity -------------------------------#\n vec_bow = dictionary.doc2bow(texts.lower().split())\n vec_tfidf = tfidf[vec_bow]\n vec_lsi = lsi[vec_tfidf]\n\n #If not in the topic trained.\n if not (vec_lsi):\n \n not_understood = \"Apology, I do not understand. Can you rephrase?\"\n return not_understood, 999\n \n else: \n # sort similarity\n sims = index[vec_lsi]\n sims = sorted(enumerate(sims), key=lambda item: -item[1])\n \n index_s =[]\n score_s = []\n for i in range(len(sims)):\n x = sims[i][1]\n # If similarity is less than 0.5 ask user to rephrase.\n if x <=0.8: # Threshold B\n index_s.append(str(sims[i][0]))\n score_s.append(str(sims[i][1]))\n reply_indexes = pd.DataFrame({'index': index_s,'score': score_s})\n\n r_index = int(reply_indexes['index'].loc[0])\n r_score = float(reply_indexes['score'].loc[0])\n\n # not_understood = \"Apology, I do not understand. Can you rephrase?\"\n # return not_understood, 999\n if (r_index < len(question_data) - 3):\n return { \"result\" : {\n\n \"fulfillment\":{\n \"speech\": \"\",\n \"displayText\": \"\",\n \"messages\": [{\n \"type\": 4,\n \"platform\": \"facebook\",\n \"payload\": {\n \"facebook\": {\n \"text\": \"Apologies, can you be a little more specific? Here are some relevant questions that you might be asking about\",\n \"quick_replies\": [{\n \"content_type\": \"text\",\n \"title\": question_data[r_index],\n \"payload\": question_data[r_index]\n }, {\n \"content_type\": \"text\",\n \"title\": question_data[r_index + 1],\n \"payload\": question_data[r_index + 1]\n },\n {\n \"content_type\": \"text\",\n \"title\": question_data[r_index + 2],\n \"payload\": question_data[r_index + 2]\n }]\n }\n }\n }]\n }\n }\n }, 999\n else:\n not_understood = \"Apology, I do not understand. Can you rephrase?\"\n return not_understood, 999\n else: \n index_s.append(str(sims[i][0]))\n score_s.append(str(sims[i][1]))\n reply_indexes = pd.DataFrame({'index': index_s,'score': score_s})\n \n\n #Find Top Questions and Score \n r_index = int(reply_indexes['index'].loc[0])\n r_score = float(reply_indexes['score'].loc[0])\n reply = str(data.iloc[:,1][r_index])\n \n return reply, r_score\n\n\ndef lsa(sentence): \n \n # sentence = input(\"User says > \")\n if(sentence.lower()!='bye'):\n if(greeting(sentence.lower())!=None):\n # print('Bot says > '+ greeting(sentence.lower()))\n return greeting(sentence.lower())\n else:\n reply =[]\n score =[]\n reply, score = Talk_To_Tau(str(sentence))\n\n # print(\"Score from AlICE : \", score)\n return reply\n \n #For Tracing, comment to remove from print\n #print(\"\")\n #print(\"SCORE: \"+str(score))\n\n","sub_path":"CHATBOT_LSI.py","file_name":"CHATBOT_LSI.py","file_ext":"py","file_size_in_byte":6481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"457285598","text":"from flask import Flask, render_template, Response\nimport io\nimport cv2\n\napp = Flask(__name__)\n\n# Video Capture mode, 0 => webcam\nvc = cv2.VideoCapture(0)\n\n# Renders the file where video will be streamed.\n@app.route('/')\ndef index():\n return render_template('index.html')\n\n\n# Implement Custom Algorithm here (on frame)\n# and return new frame\ndef myAlgorithm(frame):\n modified_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n return modified_frame\n\n\n# Support function for converting frames to sequence of '.jpg' images\n# Image sequence turned to a video stream\ndef generate_frames():\n while True:\n read_return_code, frame = vc.read()\n # myAlgorithm(..) output is consumed here\n modified_frame = myAlgorithm(frame)\n encode_return_code, image_buffer = cv2.imencode('.jpg', modified_frame)\n io_buf = io.BytesIO(image_buffer)\n yield (b'--frame\\r\\n' b'Content-Type: image/jpeg\\r\\n\\r\\n' + io_buf.read() + b'\\r\\n')\n\n\n# Output stream url (similar to ip camera stream on web)\n@app.route('/video_feed')\ndef video_feed():\n return Response(\n generate_frames(),\n mimetype='multipart/x-mixed-replace; boundary=frame'\n )\n\n\n# This helps in hosting stream to ip of device (accessible across server)\n# Example : http://192.168.0.101:5000/\nif __name__ == '__main__':\n app.run(host='0.0.0.0', debug=True, threaded=True)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"122723328","text":"import xml.etree.ElementTree as ET\nfrom xml.dom import minidom\n\n\ndef prettify(elem):\n \"\"\"Return a pretty-printed XML string for the Element.\"\"\"\n rough_string = ET.tostring(elem, 'utf-8')\n reparsed = minidom.parseString(rough_string)\n return reparsed.toprettyxml(indent=\" \")\n\n\ndef write_to_file(data, path, date_format='%Y-%m-%d'):\n \"\"\"Export extracted fields to xml\n\n Appends .xml to path if missing and generates xml file in specified directory, if not then in root\n\n Parameters\n ----------\n data : dict\n Dictionary of extracted fields\n path : str\n directory to save generated xml file\n date_format : str\n Date format used in generated file\n\n Notes\n ----\n Do give file name to the function parameter path.\n Only `date`, `desc`, `amount` and `currency` are exported\n\n Examples\n --------\n >>> from invoice2data.output import to_xml\n >>> to_xml.write_to_file(data, \"/exported_xml/invoice.xml\")\n >>> to_xml.write_to_file(data, \"invoice.xml\")\n\n \"\"\"\n\n if path.endswith('.xml'):\n filename = path\n else:\n filename = path + '.xml'\n\n tag_data = ET.Element('data')\n xml_file = open(filename, \"w\")\n i = 0\n for line in data:\n i += 1\n tag_item = ET.SubElement(tag_data, 'item')\n tag_date = ET.SubElement(tag_item, 'date')\n tag_desc = ET.SubElement(tag_item, 'desc')\n tag_currency = ET.SubElement(tag_item, 'currency')\n tag_amount = ET.SubElement(tag_item, 'amount')\n tag_item.set('id', str(i))\n tag_date.text = line['date'].strftime(date_format)\n tag_desc.text = line['desc']\n tag_currency.text = line['currency']\n tag_amount.text = str(line['amount'])\n\n xml_file.write(prettify(tag_data))\n xml_file.close()\n","sub_path":"src/invoice2data/output/to_xml.py","file_name":"to_xml.py","file_ext":"py","file_size_in_byte":1807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"643768694","text":"from typing import MutableMapping\n\n\nclass Node:\n def __init__(self, name):\n self.name = name\n self.children = set()\n self.distance_to_root = -1\n\n def add_child(self, child):\n self.children.add(child)\n\n def __hash__(self):\n return self.name.__hash__()\n\n def __eq__(self, other):\n \"\"\"Overrides the default implementation\"\"\"\n if isinstance(other, Node):\n return self.name == other.name\n return False\n\n\nnodes: MutableMapping[str, Node] = dict()\n\nfor line in open('input', 'r'):\n line = line.replace('\\n', '')\n line = line.split(')')\n parent_name = line[0]\n child_name = line[1]\n\n if parent_name not in nodes:\n nodes[parent_name] = Node(parent_name)\n\n if child_name not in nodes:\n nodes[child_name] = Node(child_name)\n\n nodes[parent_name].add_child(nodes[child_name])\n\nprint(len(nodes))\n\nroot = nodes['COM']\n\ndef dfs(node, distance):\n node.distance_to_root = distance\n\n if len(node.children) == 0:\n return\n else:\n for child in node.children:\n dfs(child, distance + 1)\n\n\ndfs(root, 0)\n\nprint(sum([n.distance_to_root for n in nodes.values()]))\n\n# part 2: for each node, find the distance to san and the distance to you. The minimum of the sum of this pair -2 is the\n# answer. (Assuming the graph contains no cycles)\nresults = []\nfor i in nodes.values():\n\n # init to -1\n for n in nodes.values():\n n.distance_to_root = -1\n\n dfs(i, 0)\n\n if nodes['SAN'].distance_to_root > -1 and nodes['YOU'].distance_to_root > -1:\n results.append((nodes['SAN'].distance_to_root, nodes['YOU'].distance_to_root))\n\nprint(min([t[0] + t[1] for t in results]) - 2)","sub_path":"day6/day6.py","file_name":"day6.py","file_ext":"py","file_size_in_byte":1705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"77310243","text":"import time\nimport random\n\nrand_list = [random.randint(0, 10) for x in range(1, random.randrange(1, 20))] # Random numbers to test VMP\nprint(rand_list)\nfirst_loop = [1, 2, 3, 1, 4, 5]\nmem_slots = [[-1,-1],[-1,-1],[-1,-1]]\n\n\ndef insert_mem_slots(alist):\n global mem_slots\n\n for i in alist:\n # print('\\ni =', i)\n time.sleep(0.5)\n epoch_time = time.time()\n time_calc = []\n for slot, val in enumerate(mem_slots):\n # print('\\nSlot: ', slot, 'Value: ', val)\n if val[1] == -1:\n # print('Slot {} is empty, have at it!'.format(slot))\n mem_slots[slot] = [epoch_time, i]\n break\n elif i == val[1]:\n # print(i, 'is already in slot, ', slot)\n val[0] = epoch_time\n break\n else:\n # print(i, 'is not in slot, ', slot)\n time_calc.append(val[0])\n\n if len(time_calc) == len(mem_slots):\n # print('For time calc: ', time_calc)\n index = time_calc.index(min(time_calc))\n mem_slots[index] = [epoch_time, i]\n print(mem_slots)\n\n\ninsert_mem_slots(rand_list)\n","sub_path":"VMP_LRU.py","file_name":"VMP_LRU.py","file_ext":"py","file_size_in_byte":1182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"323443161","text":"# Advent of Code 2015. Day 6 #\r\n#\r\n\r\nimport numpy as np\r\n\r\n\r\ndef change(array, type, x0,y0,x1,y1):\r\n if type == \"on\":\r\n array[y0:y1+1, x0:x1+1] = 1\r\n elif type == \"off\":\r\n array[y0:y1+1, x0:x1+1] = 0\r\n elif type == \"toggle\":\r\n array[y0:y1+1, x0:x1+1] = np.where(array[y0:y1+1, x0:x1+1] != 0, 0, 1)\r\n else:\r\n raise SystemError(\"Wrong change() type input.\")\r\n return array\r\n\r\narray = np.zeros((1000,1000))\r\n\r\nwith open(\"santa.txt\", \"r\") as f:\r\n data = f.read().splitlines()\r\n\r\nfor line in data:\r\n mode, X, _, Y = line.replace(\"turn \",\"\").split(\" \")\r\n x0,y0 = X.split(\",\")\r\n x1,y1 = Y.split(\",\")\r\n array = change(array,mode,int(x0),int(y0),int(x1),int(y1))\r\n \r\nprint(np.sum(array))\r\n","sub_path":"Advent of Code 2015/2015 Day 6-1.py","file_name":"2015 Day 6-1.py","file_ext":"py","file_size_in_byte":741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"522594282","text":"from xml.dom import Node\nimport xml.etree.ElementTree as ET\nfrom xml.dom.minidom import parseString\nfrom subprocess import check_output\nimport re\nimport logging\n\nfrom helium.util.colorprint import green\nfrom helium.util import srcmlutil\n\nlogger = logging.getLogger(__name__)\n\n\nstatement_elements = set()\nstatement_elements.add('expr_stmt')\nstatement_elements.add('decl_stmt')\nstatement_elements.add('break')\nstatement_elements.add('macro')\n\nblock_elements = set()\nblock_elements.add('for')\nblock_elements.add('while')\nblock_elements.add('if')\nblock_elements.add('function')\n\nvalid_AST_elements = set()\nvalid_AST_elements = statement_elements | block_elements\n\n\ndef is_element(node):\n if not node: return False\n if node.nodeType == Node.ELEMENT_NODE:\n return True\n else:\n return False\n\ndef is_blank(node):\n if node.nodeType == Node.TEXT_NODE and not get_text_content(node).strip():\n return True\n else:\n return False\n\ndef is_valid_AST_element(node):\n if is_element(node) and node.tagName in valid_AST_elements:\n return True\n else:\n return False\n\ndef get_children_by_tagname(node, name):\n result = []\n if not node or not node.hasChildNodes: return []\n for n in node.childNodes:\n if is_element(n) and n.tagName == name:\n result.append(n)\n return result\ndef get_first_child_by_tagname(node, name):\n if not node or not node.hasChildNodes: return None\n for n in node.childNodes:\n if is_element(n) and n.tagName == name:\n return n\n return None\ndef get_first_child_by_tagnames(node, *names):\n for name in names:\n node = get_first_child_by_tagname(node, name)\n if not node: return None\n return node\n\ndef get_next_sibling_by_tagname(node, name):\n while node.nextSibling:\n node = node.nextSibling\n if is_element(node) and node.tagName == name:\n return node\n return None\n\ndef in_node(node, tagname,level=1):\n \"\"\"Whether a node is inside another node with tagname\n :param node: the node we have\n :param tagname: the upperlevel tagname\n :param level: at most level node search up\n :return True if node in \n \"\"\"\n while node.parentNode and level > 0:\n node = node.parentNode\n level-=1\n if not is_element(node): return False\n if node.tagName == tagname: return True\n return False\n\ndef get_parent_by_tagname(node, tagname):\n while node.parentNode:\n node = node.parentNode\n if not is_element(node): return None\n if node.tagName == tagname:\n return node\n return None\n\n# HEBI: AST related\n\ndef get_text_content(node):\n if not node: return ''\n s=''\n if node.nodeType == Node.TEXT_NODE:\n s = node.data\n else:\n for n in node.childNodes:\n s += get_text_content(n)\n return s\n\ndef get_text_content_except(node, tag):\n \"\"\"get the content except node\n \"\"\"\n if not node: return ''\n s = ''\n if node.nodeType == Node.TEXT_NODE:\n s = node.data\n else:\n for n in node.childNodes:\n if is_element(n) and n.tagName == tag: continue\n s += get_text_content_except(n, tag)\n return s\n\ndef get_text_content_except_comment(node):\n if not node: return None\n s = ''\n if node.nodeType == Node.TEXT_NODE:\n s = node.data\n elif node.tagName == 'comment':\n return ''\n else:\n for n in node.childNodes:\n s += get_text_content_except_comment(n)\n return s\n\n\ndef has_previous_AST_element(node):\n if get_previous_AST_element(node):\n return True\n else:\n return False\n\ndef get_previous_AST_element(node):\n \"\"\"This include the text node because it may contains ,;\\n necessary spaces\n \"\"\"\n result = []\n while node and node.previousSibling:\n node = node.previousSibling\n if is_valid_AST_element(node):\n result.insert(0, node)\n return result\n else:\n result.insert(0, node)\n return None\n\ndef has_next_AST_element(node):\n if get_next_AST_element(node):\n return True\n else:\n return False\n\ndef get_next_AST_element(node):\n \"\"\"Just get the node, because it is used for segment selection\n \"\"\"\n while node.nextSibling:\n node = node.nextSibling\n if is_valid_AST_element(node):\n return node\n return None\n\ndef get_previous_AST_elements(node, number):\n elements = []\n while(number>0):\n node_list = get_previous_AST_element(node)\n number-=1\n elements = node_list + elements\n node = node_list[0]\n return elements\n\ndef get_previous_AST_element_number(node):\n count=0\n node_list = get_previous_AST_element(node)\n while node_list:\n node_list = get_previous_AST_element(node_list[0])\n count += 1\n return count\n\ndef get_parent_AST_element(node):\n if not node:\n return None\n node = node.parentNode\n while is_element(node) and node.tagName not in valid_AST_elements:\n node = node.parentNode\n if not is_element(node):\n return None\n return node\n\ndef get_previous_AST_element_number_until_function(node):\n count = 0\n while node:\n count += get_previous_AST_element_number(node)\n node = get_parent_AST_element(node)\n if node.tagName == 'function':\n return count\n\ndef get_function_element(node):\n while node:\n node = get_parent_AST_element(node)\n if node.tagName == 'function':\n return node\n\n\ndef beyond_parent(node, number):\n if get_previous_AST_element_number(node) < number:\n return True\n else:\n return False\n\ndef beyond_method(node, number):\n while node and beyond_parent(node, number):\n number -= get_previous_AST_element_number(node)\n node = node.parentNode\n while is_element(node) and node.tagName not in valid_AST_elements:\n node = node.parentNode\n if is_element(node) and node.tagName == 'function':\n return True\n return False\n\ndef get_doc_from_c_file(file):\n xml = srcmlutil.get_xml_from_file(file)\n doc = parseString(xml)\n return doc\n\ndef get_doc_from_code(code):\n xml = srcmlutil.get_xml_from_string(code)\n doc = parseString(xml)\n return doc\n","sub_path":"helium/util/domutil.py","file_name":"domutil.py","file_ext":"py","file_size_in_byte":6292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"406283147","text":"import random\n\nallowed_steps = [\".\"] # monsters cannot leave the room they spawned in\n\ndef place_sprites(rendered_map, player, monsters, max_x, max_y):\n \"\"\" This function is for giving sprites their initial board placement.\"\"\"\n sprites = [player] + monsters \n for sprite in sprites:\n sprite_needs_position = True\n while(sprite_needs_position):\n y = random.randint(0, max_y)\n x = random.randint(0, max_x)\n if (rendered_map[x][y] in allowed_steps): # all sprites start inside of a room\n sprite_needs_position = False\n sprite.x = x\n sprite.y = y\n\n rendered_map[sprite.x][sprite.y] = sprite.symbol\n \n return rendered_map \n\ndef move_monsters(board, monsters, player):\n \"\"\" This function is for giving monsters new pseudorandom positions.\"\"\"\n for monster in monsters:\n\n available_positions = []\n # Find available positions around you (e.g. of the 8 adjacent points and \".\")\n # top left (nw)\n if board[monster.x-1][monster.y-1] in allowed_steps:\n available_positions.append([monster.x-1, monster.y-1])\n # above (n)\n if board[monster.x-1][monster.y] in allowed_steps:\n available_positions.append([monster.x-1, monster.y])\n # top right (ne)\n if board[monster.x][monster.y+1] in allowed_steps:\n available_positions.append([monster.x, monster.y+1])\n # right (w)\n if board[monster.x][monster.y-1] in allowed_steps:\n available_positions.append([monster.x, monster.y-1])\n # bottom right (sw)\n if board[monster.x+1][monster.y-1] in allowed_steps:\n available_positions.append([monster.x+1, monster.y-1])\n # below (s)\n if board[monster.x+1][monster.y] in allowed_steps:\n available_positions.append([monster.x+1, monster.y])\n # bottom left (se)\n if board[monster.x+1][monster.y+1] in allowed_steps:\n available_positions.append([monster.x+1, monster.y+1])\n # left(w)\n if board[monster.x][monster.y-1] in allowed_steps:\n available_positions.append([monster.x, monster.y-1])\n \n # remove positions from available_positions that are occupied by other monsters or the player\n sprites = [player] + monsters\n temp = []\n for posn in available_positions:\n posn_allowed = True\n for sprite in sprites:\n if sprite.x == posn[0] and sprite.y == posn[1]:\n posn_allowed = False\n break\n\n if posn_allowed == True:\n temp.append(posn)\n available_positions = temp\n\n if len(available_positions) == 0:\n continue # somehow, this monster got stuck ... *hugs* for the monster\n else: # randomly pick a position and give the monster its new coordinates\n new_position = available_positions[random.randint(0,len(available_positions)-1)]\n monster.x = new_position[0]\n monster.y = new_position[1]\n","sub_path":"model/map_placement.py","file_name":"map_placement.py","file_ext":"py","file_size_in_byte":3088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"427525227","text":"'''This is a general code that reads multiple dictionaries and plot their curves in the same plot\nfor comparison purposes.\n\nFor instances, it can be used to compare the ROC curves for different networks'''\n\nimport matplotlib.pyplot as plt\nfrom operator import itemgetter\nfrom collections import OrderedDict\nimport numpy as np\n\n# A method to read the dictionary and storing it in x and y lists\n# this method can be used to threshold was metric kind of plots; e.g: precision vs threshold\n\ndef dicreader(filename):\n x=[]\n y=[]\n hash1 ={}\n dicfile = open(filename, 'r')\n for line in dicfile:\n if line !='\\n':\n a = line.strip().split('\\t')\n hash1[float(a[0])]=float(a[1])\n\n hash1 = OrderedDict(sorted(hash1.items(), key=lambda t: t[0]))\n for i in hash1:\n x.append(i)\n y.append(hash1[i])\n\n return x,y\n\nx1,y1 = dicreader('uberon_0000033precision_hash.txt')\nx2,y2 = dicreader('uberon_0001944precision_hash.txt')\n\nplt.title('Comparison of precision vs threshold curves')\nplt.xlabel('Threshold')\nplt.ylabel('Precision')\n\nplt.plot(x1, y1, label='head')\nplt.plot(x2, y2, label='pretectal region')\nplt.xlim(xmax=750)\nplt.legend()\n\nplt.savefig('precision_comparison.jpg')\n\n\n\n\n","sub_path":"single_function/precision_comparison/general_curve_plotter.py","file_name":"general_curve_plotter.py","file_ext":"py","file_size_in_byte":1229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"446153620","text":"import os\ndir = \"./Lamphosit/\"\n#method which handle all the operation regarding rename the file.\ndef rename_files():\n #variable initialization\n i=0\n for file_name in os.listdir(dir):\n dstination=\"l-\" + str(i) + \".jpg\"\n print(dstination)\n sourse=dir+ file_name\n print(sourse)\n dstination=dir+ dstination\n print(dstination)\n #rename function calls to rename the files.\n os.rename(sourse, dstination)\n #variable increment to differenciate the all files like newname1.html\n #,newname2.html ..... so on.\n i += 1\n print(\"All files has been renamed successfully...\") \n#rename_files method call.\nrename_files()","sub_path":"rename.py","file_name":"rename.py","file_ext":"py","file_size_in_byte":694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"368595073","text":"# https://www.hackerrank.com/challenges/py-set-mutations/problem?isFullScreen=true\r\n# Problem : For Line1 elements in Line2, perform Line3 no. of commands on subsequent lines of commands and sets\r\n\r\n# Sample Input\r\n# 16\r\n# 1 2 3 4 5 6 7 8 9 10 11 12 13 14 24 52\r\n# 4\r\n# intersection_update 10\r\n# 2 3 5 6 8 9 1 4 7 11\r\n# update 2\r\n# 55 66\r\n# symmetric_difference_update 5\r\n# 22 7 35 62 58\r\n# difference_update 7\r\n# 11 22 35 55 58 62 66\r\n\r\n# Sample Output\r\n# 38\r\n\r\n\r\n### initial version\r\ncountA = int(input())\r\nsetA = set(map(int, input().split()))\r\n\r\nfor _ in range(int(input())):\r\n command, count = input().split()\r\n nextSet = set(map(int, input().split()))\r\n\r\n if \"intersection\" in command:\r\n setA.intersection_update(nextSet)\r\n elif \"symmetric_difference\" in command:\r\n setA.symmetric_difference_update(nextSet)\r\n elif \"difference\" in command:\r\n setA.difference_update(nextSet)\r\n else:\r\n setA.update(nextSet)\r\n \r\nprint(sum(setA))\r\n\r\n\r\n### getAttr using existing input command\r\n# countA = int(input())\r\n# setA = set(map(int, input().split()))\r\n\r\n# for _ in range(int(input())):\r\n# command, count = input().split()\r\n# nextSet = set(map(int, input().split()))\r\n\r\n# getattr(setA, command)(nextSet)\r\n\r\n# print(sum(setA))","sub_path":"0_reference/Hackerrank/Practice Python/Sets/Set Mutation.py","file_name":"Set Mutation.py","file_ext":"py","file_size_in_byte":1289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"77303657","text":"import pandas as pd\nfrom ast import literal_eval\nfrom collections import Counter\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom wordcloud import WordCloud\npd.set_option('display.max_columns', 50)\n\ndf = pd.read_csv('output_new.csv')\nprint(df.describe())\nprint(df.info())\nprint(df.head())\n\n######################### Skills ###############################\ndef clean_skill_name(skill):\n\tnew_skill = skill.replace(' (Programming Language)', '')\n\tnew_skill = new_skill.replace('Amazon Web Services', 'AWS')\n\tif 'SQL' in new_skill:\n\t\tnew_skill = 'SQL'\n\tnew_skill = new_skill.replace('Microsoft Word', '')\n\tnew_skill = new_skill.replace('Microsoft Excel', '')\n\tnew_skill = new_skill.replace('Microsoft PowerPoint', '')\n\tnew_skill = new_skill.replace('Microsoft Office', '')\n\tnew_skill = new_skill.replace('Project Management', '')\n\tnew_skill = new_skill.replace('Management', '')\n\treturn new_skill\n\nall_skills = df['Skills'].dropna().tolist()\nall_skills = [clean_skill_name(skill) for sublist in all_skills for skill in literal_eval(sublist) if not clean_skill_name(skill)=='']\n\nprint('\\nNumber of non-distinct skills: ', len(all_skills))\nc = Counter(all_skills)\nprint(f'Number of distinct skills: {len(c.keys())}\\n')\nprint('--'*25)\nprint(\"10 Most common Skills\")\nskills_x = []\nskills_freq = []\nfor entry in c.most_common(10):\n\tskills_x.append(entry[0])\n\tskills_freq.append(int(entry[1]))\n\tprint(\" Skill: {0:^20}\\t Frequency: {1}\".format(entry[0], entry[1]))\nprint('--'*25)\n\nf, ax = plt.subplots()\nplt.bar(skills_x,skills_freq)\nplt.title('Most Common Technical Skills')\nplt.xlabel('Skills')\nplt.ylabel('Frequency')\nplt.show()\n\ncounts = np.array(list(c.most_common()))\nprint(\"\\nNumber of Skills that appear exactly once: \",sum(counts[:,1]=='1'))\nprint(\"\\nNumber of Skills that appear exactly twice:\", sum(counts[:,1]=='2'))\n\ndef generate_skills_word_cloud(list_of_skills):\n\t# Make a word cloud for skills\n\twordcloud = WordCloud(max_words=190, scale=10, mode='RGBA').generate(' '.join(list_of_skills))\n\t# Display the generated word cloud:\n\tplt.imshow(wordcloud, interpolation='bilinear')\n\tplt.axis(\"off\")\n\tplt.show()\n\ngenerate_skills_word_cloud(all_skills)\n\nexit(0)\n\n######################### Posting Age ########################################\ndef clean_posted_age(age_as_str):\n\tif not pd.isna(age_as_str):\n\t\tnew_age_str = age_as_str.replace('Posted ', '').strip()\n\t\tmultiplier = 7 if 'w' in new_age_str else 1\n\t\tmultiplier = 30 if 'm' in new_age_str else multiplier\n\t\treturn [int(s)*multiplier for s in new_age_str.split() if s.isdigit()][0] #Return the age in days\n\telse:\n\t\treturn None\n\n\ndf['Posting Age In Days'] = df['Posting Age'].apply(lambda x: clean_posted_age(x))\n\ndef intersection(lst1, lst2):\n\tlst1_cleaner = [x.lower() for x in lst1]\n\tlst2_cleaner = [x.lower() for x in lst2]\n\treturn list(set(lst1_cleaner) & set(lst2_cleaner))\n\ndef split_string_re(data):\n\timport re\n\treturn re.findall(r\"[\\w']+\", data)\n######################### Position Title #####################################\ndef clean_position_title(position_as_str):\n\tif not pd.isna(position_as_str):\n\t\tposition = split_string_re(position_as_str)\n\t\tanalysts = ['Analyst', 'Scientist', 'Strategist', 'Advisor', 'Adviser', 'Designer', 'Integrator', 'Specialist' \n\t\t\t\t\t'Analytics', 'Strategy', 'Architect', 'Researcher', 'Modeller', 'Modeler', 'Consultant', 'Research'\n\t\t\t\t\t'Associate', 'Model']\n\t\tsenior = ['Senior', 'Lead', 'Director', 'Manager', 'Sr.', 'Deputy', 'II', 'III', 'Sr', 'Instructor']\n\t\tengineer = ['Engineer', 'Administrator', 'Full-Stack', 'Full Stack', 'Developer', 'Programmer']\n\t\tif len(intersection(position, senior))>0:\n\t\t\tif len(intersection(position, analysts))>0:\n\t\t\t\tnew_position_as_str = 'Senior Analyst'\n\t\t\telif len(intersection(position, engineer))>0:\n\t\t\t\tnew_position_as_str = 'Senior Engineer'\n\t\t\telse:\n\t\t\t\tnew_position_as_str = 'Technical Manager'\n\t\telif len(intersection(position, engineer))>0:\n\t\t\tnew_position_as_str = 'Engineer'\n\t\telif len(intersection(position, analysts))>0:\n\t\t\tnew_position_as_str = 'Analyst/Scientist'\n\t\telse:\n\t\t\tnew_position_as_str = 'Other'\n\t\tif ('Intern' in position) or ('intern' in position):\n\t\t\tnew_position_as_str = 'Intern'\n\t\treturn new_position_as_str\n\telse:\n\t\treturn None\n\ndf['Position Grouping'] = df['Position Title'].apply(lambda x: clean_position_title(x))\n\n######################### Applicants Seniority ###############################\ndf['Applicants Seniority'] = df['Applicants Seniority'].apply(lambda x: literal_eval(str(x)) if not pd.isna(x) else x)\n\ndef seniority_list_to_dict(list_of_seniority_breakdown):\n\tall_levels = {'Entry Level %': 0, 'Senior Level %': 0, 'Manager Level %': 0, 'Director Level %': 0, 'VP Level %': 0}\n\ttry:\n\t\tfor level in list_of_seniority_breakdown:\n\t\t\tlst = level.split()\n\t\t\tapplicant_level = lst[1]+' Level %' if not lst[1]=='CXO' else 'VP Level %'\n\t\t\tall_levels[applicant_level] += int(lst[0])\n\t\ttotal = sum(all_levels.values())\n\t\tfor key,value in all_levels.items():\n\t\t\tall_levels[key] = format(100*(value/total), '.2f')\n\tfinally:\n\t\treturn pd.Series(all_levels, dtype='float64')\ndf2 = df['Applicants Seniority'].apply(lambda x: seniority_list_to_dict(x))\ndf2 = df2.replace(0, np.NaN)\ndf = pd.concat([df, df2], axis=1, sort=False)\n\n######################### Applicants Education ###############################\ndf['Applicants Education'] = df['Applicants Education'].apply(lambda x: literal_eval(str(x)) if not pd.isna(x) else x)\n\ndef education_list_to_dict(list_of_education_breakdown):\n\tall_levels = {'Bachelor\\'s %': 0, 'Master\\'s %': 0, 'MBA %': 0, 'PhD %': 0, 'Other Degrees %': 0}\n\ttry:\n\t\tfor level in list_of_education_breakdown:\n\t\t\tlevel = level.replace('%% have','')\n\t\t\tlst = level.split()\n\t\t\tif 'Bachelor\\'s' in lst:\n\t\t\t\tall_levels['Bachelor\\'s %'] += int(lst[0])\n\t\t\telif 'Master\\'s' in lst:\n\t\t\t\tall_levels['Master\\'s %'] += int(lst[0])\n\t\t\telif 'Business' in lst:\n\t\t\t\tall_levels['MBA %'] += int(lst[0])\n\t\t\telif 'Doctor' in lst:\n\t\t\t\tall_levels['PhD %'] += int(lst[0])\n\t\t\telif 'other' in lst:\n\t\t\t\tall_levels['Other Degrees %'] += int(lst[0])\n\tfinally:\n\t\treturn pd.Series(all_levels, dtype='float64')\n\ndf2 = df['Applicants Education'].apply(lambda x: education_list_to_dict(x))\ndf2 = df2.replace(0, np.NaN)\ndf = pd.concat([df, df2], axis=1, sort=False)\nprint(df.describe(include='all'))\n\ndef create_box_plots():\n\tfig1, ax1 = plt.subplots()\n\tax1.set_title('Applicants by Education Level')\n\teducation_box_plot = df.boxplot(ax=ax1,\n\t\t\t\t\t\t\t\t\tcolumn=['Bachelor\\'s %', 'Master\\'s %', 'MBA %', 'PhD %', 'Other Degrees %'])\n\n\tfig2, ax2 = plt.subplots()\n\tax2.set_title('Applicants by Experience')\n\texperience_box_plot = df.boxplot(ax=ax2,\n\t\t\t\t\t\t\t\t\t column=['Entry Level %', 'Senior Level %', 'Manager Level %', 'Director Level %',\n\t\t\t\t\t\t\t\t\t\t\t 'VP Level %'])\n\n\tfig3, ax3 = plt.subplots()\n\tax3.set_title('Education Level by Position')\n\teducation_by_position_box_plot = df.boxplot(ax=ax3, column=['Bachelor\\'s %', 'Master\\'s %'],\n\t\t\t\t\t\t\t\t\t\t\t\tby=['Position Grouping'])\n\tax3.set_title('Education Level by Position')\n\n\tfig4, ax4 = plt.subplots()\n\tax4.set_title('Education Level by Position')\n\texperience_by_position_box_plot = df.boxplot(ax=ax4, column=['Entry Level %', 'Senior Level %'],\n\t\t\t\t\t\t\t\t\t\t\t\t by=['Position Grouping'])\n\tax4.set_title('Education Level by Position')\n\tplt.show()\n\n######################### Job Descriptions ###############################\nimport nltk\n# nltk.download('wordnet')\n# nltk.download('punkt') # one time execution\n# nltk.download('stopwords')\n\nfrom nltk.tokenize import sent_tokenize\nfrom nltk.corpus import stopwords\n\nsentences = []\nfor s in df['Job Description']:\n\tsentences.append(sent_tokenize(str(s)))\n\nsentences = [y for x in sentences for y in x] # flatten list\n# Extract word vectors\nword_embeddings = {}\nf = open('glove.6B/glove.6B.100d.txt', encoding='utf-8')\nfor line in f:\n\tvalues = line.split()\n\tword = values[0]\n\tcoefs = np.asarray(values[1:], dtype='float32')\n\tword_embeddings[word] = coefs\nf.close()\n\n# remove punctuations, numbers and special characters\nclean_sentences = pd.Series(sentences).str.replace(\"[^a-zA-Z]\", \" \")\n\n# make sentences lowercase\nclean_sentences = [s.lower() for s in clean_sentences]\n\n\nstop_words = stopwords.words('english')\n\n# function to remove stopwords\ndef remove_stopwords(sen):\n\tsen_new = \" \".join([i for i in sen if i not in stop_words])\n\treturn sen_new\n\n# remove stopwords from the sentences\nclean_sentences = [remove_stopwords(r.split()) for r in clean_sentences]\n\nsentence_vectors = []\nfor i in clean_sentences:\n\tif len(i) != 0:\n\t\tv = sum([word_embeddings.get(w, np.zeros((100,))) for w in i.split()])/(len(i.split())+0.001)\n\telse:\n\t\tv = np.zeros((100,))\n\tsentence_vectors.append(v)\n# similarity matrix\nsim_mat = np.zeros([len(sentences), len(sentences)])\nfrom sklearn.metrics.pairwise import cosine_similarity\nfor i in range(len(sentences)):\n\tfor j in range(len(sentences)):\n\t\tif i != j:\n\t\t\tsim_mat[i][j] = cosine_similarity(sentence_vectors[i].reshape(1,100), sentence_vectors[j].reshape(1,100))[0,0]\n\nimport networkx as nx\n\nnx_graph = nx.from_numpy_array(sim_mat)\nscores = nx.pagerank(nx_graph)\n\nranked_sentences = sorted(((scores[i],s) for i,s in enumerate(sentences)), reverse=True)\n# Extract top 10 sentences as the summary\nfor i in range(10):\n\tprint(ranked_sentences[i][1])\n","sub_path":"exploratory_analysis.py","file_name":"exploratory_analysis.py","file_ext":"py","file_size_in_byte":9228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"491768744","text":"\"\"\"\nPagination fields\n\"\"\"\n# pylint: disable=no-init, too-few-public-methods, no-self-use\nfrom collections import OrderedDict\n\nfrom rest_framework import serializers\nfrom rest_framework import pagination\nfrom rest_framework.views import Response\nfrom rest_framework.templatetags.rest_framework import replace_query_param\n\n# DRF 2.4.X compatibility.\nReadOnlyField = getattr(serializers, 'ReadOnlyField', serializers.Field)\n\n\nclass NextPageLinkField(ReadOnlyField):\n \"\"\"\n Field that returns a link to the next page in paginated results.\n \"\"\"\n page_field = 'page'\n\n def to_representation(self, value):\n if not value.has_next():\n return None\n page = value.next_page_number()\n request = self.context.get('request')\n url = request and request.build_absolute_uri() or ''\n return replace_query_param(url, self.page_field, page)\n\n\nclass NextPageField(ReadOnlyField):\n \"\"\"\n Field that returns a the next page number in paginated results.\n \"\"\"\n page_field = 'page'\n\n def to_representation(self, value):\n if not value.has_next():\n return None\n return value.next_page_number()\n\n\nclass PreviousPageLinkField(ReadOnlyField):\n \"\"\"\n Field that returns a link to the previous page in paginated results.\n \"\"\"\n page_field = 'page'\n\n def to_representation(self, value):\n if not value.has_previous():\n return None\n page = value.previous_page_number()\n request = self.context.get('request')\n url = request and request.build_absolute_uri() or ''\n return replace_query_param(url, self.page_field, page)\n\n\nclass PreviousPageField(ReadOnlyField):\n \"\"\"\n Field that returns the previous page number in paginated results.\n \"\"\"\n page_field = 'page'\n\n def to_representation(self, value):\n if not value.has_previous():\n return None\n return value.previous_page_number()\n\n\nclass PageField(ReadOnlyField):\n \"\"\"\n Field that returns the current page number in paginated results.\n \"\"\"\n page_field = 'page'\n\n def to_representation(self, value):\n return value.number\n\n\n# compatibility for DRF 3.0 and older\ntry:\n BasePagination = pagination.PageNumberPagination\nexcept:\n BasePagination = pagination.BasePaginationSerializer\n\n\nclass PaginationSerializer(BasePagination):\n \"\"\"\n Pagination serializer.\n \"\"\"\n next = NextPageField(source='*')\n next_link = NextPageLinkField(source='*')\n page = PageField(source='*')\n previous = PreviousPageField(source='*')\n previous_link = PreviousPageLinkField(source='*')\n count = ReadOnlyField(source='paginator.count')\n total = ReadOnlyField(source='paginator.num_pages')\n\n\nclass EmberPaginationSerializer(PaginationSerializer):\n \"\"\"\n Backwards compatibility for name change\n \"\"\"\n pass\n\n\nclass PageNumberPagination(BasePagination):\n \"\"\"\n A json-api compatible pagination format\n \"\"\"\n\n def build_link(self, index):\n if not index:\n return None\n url = self.request and self.request.build_absolute_uri() or ''\n return replace_query_param(url, 'page', index)\n\n def get_paginated_response(self, data):\n next = None\n previous = None\n\n if self.page.has_next():\n next = self.page.next_page_number()\n if self.page.has_previous():\n previous = self.page.previous_page_number()\n\n return Response({\n 'results': data,\n 'meta': {\n 'pagination': OrderedDict([\n ('page', self.page.number),\n ('pages', self.page.paginator.num_pages),\n ('count', self.page.paginator.count),\n ])\n },\n 'links': OrderedDict([\n ('first', self.build_link(1)),\n ('last', self.build_link(self.page.paginator.num_pages)),\n ('next', self.build_link(next)),\n ('prev', self.build_link(previous))\n ])\n })\n","sub_path":"rest_framework_json_api/pagination.py","file_name":"pagination.py","file_ext":"py","file_size_in_byte":4033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"419682163","text":"from django.shortcuts import render\nfrom celery.result import AsyncResult\n\nfrom celery_state.celery import app\n\n\ndef tasks_list_view(request):\n i = app.control.inspect()\n active_tasks = i.active()\n tasks_id = []\n\n if active_tasks is not None:\n for k,v in active_tasks.items():\n for tasks in active_tasks[k]:\n tasks_id.append(tasks['id'])\n\n context = {\n 'tasks_id': tasks_id\n }\n\n return render(request, 'core/tasks_list.html', context)\n\n\ndef task_detail_view(request, task_id):\n res = AsyncResult(task_id, app=app)\n state = res.state\n\n context = {\n 'task_id': task_id,\n 'state': state\n }\n\n return render(request, 'core/task_detail.html', context=context)\n","sub_path":"celery_state/core/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"259443055","text":"# Space Rocks game.\n\nimport cartesian_coordinates as cc # Functions for rotating, scaling, etc.\nimport pygame # 2d games engine.\nimport random\nimport time\nimport datetime # Needed for logging.\n\n\n# If debugging is turned on, send the parm message to stdout.\ndef trace(config, message):\n if config.debug:\n print(datetime.datetime.now(), message)\n\n\n############################################\n# The rocks that float in space.\n############################################\n\nclass Rock:\n\n def __init__(self, config, size):\n assert size in ['Small', 'Medium', 'Large']\n\n self.size = size # Size of rock to be created, \"Large\", \"Medium\", \"Small\"\n self.vertices = [] # List of vertices of the rock, centered around origin.\n\n # Rock is based on a polygon (straight edged circle).\n if self.size == 'Large':\n self.radius = random.randint(30, 50)\n elif self.size == \"Medium\":\n self.radius = random.randint(15, 25)\n else:\n self.radius = random.randint(10, 15)\n\n self.rotation = 0 # Current rotation of the rock in degrees.\n\n max_rotation_velocity = round(100 / config.target_fps)\n self.rotation_speed = random.randint(- max_rotation_velocity, max_rotation_velocity) # Degrees per tick\n if self.rotation_speed == 0: # No rotation would look boring.\n self.rotation_speed = 1\n\n vertex_count = 12 # Number of vertices that will make up this rock.\n slice_size = 360 / vertex_count # Good for this to be an integer.\n\n for v_num in range(vertex_count):\n if self.size == \"Large\":\n vertex = [0, self.radius + random.randint(-15, 15)]\n elif self.size == \"Medium\":\n vertex = [0, self.radius + random.randint(-7, 7)]\n else:\n vertex = [0, self.radius + random.randint(-5, 5)]\n\n vertex = cc.rotate_around_origin(vertex, slice_size * v_num)\n self.vertices.append(vertex)\n\n self.kill = False # Should this rock be killed off?\n self.collision = False # Has the rock collided with something?\n self.exploding = False # Is the rock in the process of exploding?\n self.explosion_step = 0 # Current step of explosion animation.\n\n self.colour = (random.randint(60, 200), random.randint(60, 200), random.randint(60, 200))\n\n trace(config, self.size + ' rock created.') # Send trace info to stdout.\n\n def place_on_side_of_screen(self, config):\n\n start_side = random.randint(1, 4) # 1=Top, 2=Bottom, 3=Left, 4=Right\n assert start_side in [1, 2, 3, 4]\n\n if start_side == 1: # From the top of screen.\n # TODO Try simplifying the first two in same style as second two.\n\n self.coords = [random.randint(config.border, config.screen_size[0] - config.border), config.top_dead]\n\n if self.coords[0] <= config.screen_size[0] / 2: # Left hand side of top of screen.\n self.drift = [10 * random.randint(1, 3) / config.target_fps,\n 10 * random.randint(2, 4) / config.target_fps] # So drift rightwards and downwards.\n else:\n self.drift = [10 * random.randint(-3, -1) / config.target_fps,\n 10 * random.randint(2, 4) / config.target_fps] # Otherwise drift leftwards and downwards.\n\n if start_side == 2: # Bottom\n self.coords = [random.randint(config.border, config.screen_size[0] - config.border), config.bottom_dead]\n\n if self.coords[0] <= config.screen_size[0] / 2: # Left hand side of top of screen.\n self.drift = [10 * random.randint(1, 3) / config.target_fps,\n 10 * random.randint(-4, -2) / config.target_fps] # So drift rightwards and upwards.\n else:\n self.drift = [random.randint(-3, -1), random.randint(-4, -2)] # Otherwise drift leftwards and upwards.\n\n if start_side == 3:\n self.coords = [-100, random.randint(200, 400)]\n self.drift = [10 * random.randint(2, 4) / config.target_fps,\n 10 * random.randint(-3, 3) / config.target_fps]\n\n if start_side == 4:\n self.coords = [900, random.randint(200, 400)]\n self.drift = [10 * random.randint(-4, -2) / config.target_fps,\n 10 * random.randint(-3, 3) / config.target_fps]\n\n # Has the rock strayed outside of the game screen? If so, it is flagged to be killed off.\n def check_onscreen(self, config):\n if (self.coords[0] < config.left_dead\n or self.coords[0] > config.right_dead\n or self.coords[1] < config.top_dead\n or self.coords[1] > config.bottom_dead):\n self.kill = True\n\n # Is the parm vertex inside the rock?\n def check_collision(self, vertex):\n # TODO Try omitting this line of code, as this attribute was set to False when object created.\n self.collision = False # Start by assuming that vertex is outside all triangles.\n\n # Before doing the triangle analysis (which is time consuming), do a simpler clipping test.\n # Imagine a square around the centre of the rock. Is the vertex inside that square?\n if (vertex[0] > self.coords[0] - self.radius - 15 # 15 is the most that can randomly be added to a vertex\n and vertex[0] < self.coords[0] + self.radius + 15 # at the time that the rock was created.\n and vertex[1] > self.coords[1] - self.radius - 15\n and vertex[1] < self.coords[1] + self.radius + 15):\n\n # If the vertex is inside the square, then it is worth checking each triangle that makes up the\n # rock in turn, to see if the vertex is inside any of them.\n prev_vertex = self.vertices[-1] # This is so we have 3 points for first triangle.\n\n for triangle_vertex in self.vertices:\n if cc.is_inside_triangle(vertex, self.position(prev_vertex), self.position(triangle_vertex), self.coords):\n self.collision = True\n prev_vertex = triangle_vertex\n\n # Apply some transformations to calculate the coordinates of the rock's parm vertex on the game screen.\n def position(self, vertex):\n rotated = cc.rotate_around_origin(vertex, self.rotation)\n return cc.translation(rotated, self.coords)\n\n # Begin the process of exploding this rock.\n def explode(self, config):\n self.exploding = True # Flag it as exploding.\n config.explosion_channel.play(config.explosion_sound) # Play explosion sound.\n\n # Continue animation of rock's explosion.\n def animate_explosion(self, game):\n if self.explosion_step < game.config.target_fps: # Higher FPS mean, more animation steps for explosion!\n self.explosion_step += 1\n else:\n self.kill = True # Explosion animation is over, so kill off the rock.\n\n # Half way through the explosion animation, maybe spawn new rocks.\n if self.explosion_step == int(0.5 * game.config.target_fps):\n if self.size in ['Large', 'Medium']:\n for i in range(2): # range(2), because 2 child rocks will be created.\n if self.size == 'Large':\n new_rock = Rock(game.config, 'Medium')\n else:\n new_rock = Rock(game.config, 'Small')\n\n # Give it position that is near it's parent.\n new_rock.coords = cc.translation(self.coords, [random.randint(-25, 25), random.randint(-25, 25)])\n\n # New rocks's drift will be similar to parent.\n # TODO I think this is cause of some child rocks being stationary...\n # TODO Need to add some check 'if near to zero, then set to 1'\n new_drift_x = self.drift[0] + 10 * random.randint(-1, 1) / game.config.target_fps\n new_drist_y = self.drift[1] + 10 * random.randint(-1, 1) / game.config.target_fps\n\n new_rock.drift = [new_drift_x, new_drist_y]\n\n game.rocks.append(new_rock) # Add the new rocks to the game.\n\n # Draw this rock on game screen.\n def draw(self, config):\n # TODO Make the normal rock display, and exploding rock display be separate methods.\n\n prev_vertex = self.vertices[-1] # This will make it a complete polygon.\n\n for vertex in self.vertices:\n if not self.exploding:\n if config.monochrome:\n pygame.draw.line(config.screen, config.WHITE, self.position(prev_vertex), self.position(vertex), 1)\n\n # TODO Refactor to draw whole polygon in one go, rather than drawing a number of triangles.\n else:\n triangle = []\n triangle.append(self.position(prev_vertex))\n triangle.append(self.position(vertex))\n triangle.append(self.coords)\n pygame.draw.polygon(config.screen, self.colour, triangle, 0)\n\n else:\n # Higher FPS mean more explosion steps, so lower speed of explosion per step.\n scaled_vertex = cc.scale(vertex, 5 * self.explosion_step / config.target_fps)\n [x, y] = self.position(scaled_vertex)\n\n # TODO Use the function in cartesian coordinate package to make coords integers.\n if config.monochrome:\n pygame.draw.circle(config.screen, config.WHITE, [int(x), int(y)], 1, 1)\n else:\n pygame.draw.circle(config.screen, self.colour, [int(x), int(y)], 4, 4)\n\n # TODO Make the ship explosion particle randomly twinkle away.\n # if random.randint(1, 25) == 10:\n # self.explosion_vertices.remove(v)\n\n prev_vertex = vertex\n\n # Move the rock by one tick.\n def move(self):\n self.rotation += self.rotation_speed\n self.coords = cc.translation(self.coords, self.drift)\n\n\n############################################\n# BULLET\n############################################\n\nclass Bullet:\n def __init__(self, origin, angle, colour):\n\n self.coords = origin # Current [x, y] coordinates of the bullet.\n self.angle = angle # Angle that the bullet is moving in.\n self.colour = colour # Colour of bullet. Will be same as player's ship.\n\n self.drift = cc.rotate_around_origin([0, 20], self.angle) # Incremental drift this bullet will do each tick.\n self.kill = False # Flags is this bullet is to be deleted.\n\n # Draw the bullet as a little circle on the game screen.\n def draw(self, config):\n if config.monochrome:\n pygame.draw.circle(config.screen, config.WHITE, cc.integer_coord(self.coords), 1, 1)\n else:\n pygame.draw.circle(config.screen, self.colour, cc.integer_coord(self.coords), 2, 2)\n\n # Move the bullet by one tick.\n def move(self):\n self.coords = cc.translation(self.coords, self.drift)\n\n # Is the bullet still onscreen? If not, flag it to be killed.\n def check_onscreen(self, config):\n if (self.coords[0] < config.left_dead\n or self.coords[0] > config.right_dead\n or self.coords[1] < config.top_dead\n or self.coords[1] > config.bottom_dead):\n self.kill = True\n\n\n############################################\n# SPACE SHIP\n############################################\n\nclass SpaceShip:\n\n def __init__(self, origin, colour):\n\n self.coords = origin # Starting location of ship is parm origin.\n self.colour = colour # Colour of the ship.\n\n self.rotation = 0 # Direction that ship is pointing. In degrees.\n self.exploding = False # Is the ship exploding?\n self.explosion_step = 0 # Current step in explosion animation.\n self.kill = False # Is the ship flagged to be deleted?\n self.remaining_invincibility_ticks = 0\n\n # The vertex is the nose of the ship, where bullets are fired from.\n self.vertices = [[0, 10], [-5, -5], [0, 0], [5, -5]]\n\n explosion_vertex_count = 72 # Number of vertices that will make up explosion.\n slice_size = 360 / explosion_vertex_count # Good for this to be an integer.\n self.explosion_vertices = []\n\n for v_num in range(explosion_vertex_count):\n vertex = [0, 7.0 + random.randint(-2, 2)]\n\n vertex = cc.rotate_around_origin(vertex, slice_size * v_num)\n self.explosion_vertices.append(vertex)\n\n self.bullets = [] # Bullets in flight will be appended to this list when they are fired.\n\n # Rotate the ship clockwise by 10 degrees.\n def rotate_clockwise(self):\n if not self.exploding: # Exploding ships can't rotate!\n self.rotation -= 10 # In Pygame, increased y coord is down, hence this rotation is -ve.\n\n # Rotate the ship anticlockwise by 10 degrees.\n def rotate_anticlockwise(self):\n if not self.exploding: # Exploding ships can't rotate!\n self.rotation += 10 # In Pygame, increased y coord is down, hence this rotation is +ve.\n\n # If ship is not currently exploding, then fire a bullet from its nose.\n def fire_bullet(self, config):\n if len(self.bullets) < 10 and not self.exploding:\n # Bullets should originate from the ships nose.\n # Vertex 0 of the ship is it's nose.\n ship_nose = self.position(self.vertices[0])\n self.bullets.append(Bullet(ship_nose, self.rotation, self.colour))\n\n config.laser_channel.play(config.laser_sound)\n\n # Calculate position of parm ship vertex in game screen coordinates.\n def position(self, vertex):\n rotated = cc.rotate_around_origin(vertex, self.rotation)\n return cc.translation(rotated, self.coords)\n\n def draw(self, config):\n # TODO Refactor to have separate methods for drawing ship and drawing exploding ship.\n\n prev_vertex = self.vertices[-1] # This will make it a complete polygon.\n\n if not self.exploding:\n for vertex in self.vertices:\n if config.monochrome:\n pygame.draw.line(config.screen, config.WHITE, self.position(prev_vertex), self.position(vertex), 1)\n\n # TODO refactor to draw whole polygon in one go, rather than drawing a number of triangles.\n else:\n triangle = []\n triangle.append(self.position(prev_vertex))\n triangle.append(self.position(vertex))\n triangle.append(self.coords)\n pygame.draw.polygon(config.screen, self.colour, triangle, 0)\n\n prev_vertex = vertex\n\n else:\n for v in self.explosion_vertices:\n scaled_vertex = cc.scale(v, 5 * self.explosion_step / config.target_fps)\n [x, y] = cc.translation(scaled_vertex, self.coords)\n\n if config.monochrome:\n pygame.draw.circle(config.screen, config.WHITE, [int(x), int(y)], 1, 1)\n else:\n pygame.draw.circle(config.screen, self.colour, [int(x), int(y)], 4, 4)\n\n # Make the ship explosion particle randomly twinkle away.\n if random.randint(1, 100) == 50:\n self.explosion_vertices.remove(v)\n\n # Begin the explosion of the ship.\n def explode(self, config):\n self.exploding = True # Start exploding the ship.\n config.ship_explosion_channel.play(config.ship_explosion_sound)\n\n def animate_explosion(self, config):\n if self.explosion_step < 4 * config.target_fps: # Higher FPS mean, more animation steps for explosion!\n self.explosion_step += 1\n else:\n self.kill = True # Explosion animation is over, so kill off the rock.\n\n\n############################################\n# PLAYER\n############################################\n\nclass Player:\n\n def __init__(self, player_name, colour, origin):\n\n self.player_name = player_name # For example, 'Player 1'.\n self.colour = colour # Colour of player's ship, bullets and score [r, g, b].\n self.origin = origin # Starting coordinates for player's ship [x, y].\n\n self.score = 0 # Number of points that he's scored.\n self.ship = SpaceShip(origin, colour) # This player's spaceship.\n\n def killed_a_rock(self, size):\n if size == 'Large':\n self.score += 10\n elif size == 'Medium':\n self.score += 20\n else: # Small rocks are hard to hit, hence they score 30 points.\n self.score += 30\n\n def lost_a_spaceship(self):\n origin = self.ship.coords\n colour = self.ship.colour\n self.ship = SpaceShip(origin, colour) # Replace the killed spaceship with a new one.\n self.score -= 100\n\n\n############################################\n# GAME\n############################################\n\nclass Game:\n\n def __init__(self, config):\n\n self.config = config\n\n # Create some rocks for start of game.\n self.num_rocks = 20 # Target number of rocks to have on screen at once.\n self.rocks = []\n for r in range(self.num_rocks):\n new_rock = Rock(self.config, 'Large')\n new_rock.place_on_side_of_screen(self.config)\n self.rocks.append(new_rock)\n\n assert self.config.num_players in [1, 2]\n self.players = [] # List of players.\n for n in range(self.config.num_players):\n player_name = 'Player ' + str(n + 1) # players[0] is called 'Player 1', etc.\n\n if n == 0:\n colour = self.config.RED # First player has a red ship.\n else:\n colour = self.config.GREEN # Second player has a green ship.\n\n if self.config.num_players == 1: # If only one player, she can be in centre of screen.\n origin = self.config.screen_centre\n else:\n origin_y = self.config.screen_centre[1]\n screen_width = self.config.screen_size[0]\n\n if n == 0:\n # For 2 player game, first player is moved a bit to the left.\n origin_x = self.config.screen_centre[0] - int(screen_width / 4)\n else:\n # For 2 player game, second player is moved a bit to the right.\n origin_x = self.config.screen_centre[0] + int(screen_width / 4)\n\n origin = [origin_x, origin_y]\n\n self.players.append(Player(player_name, colour, origin)) # Add each player to the list of players.\n\n self.game_end_time = time.time() + 60 # '60' is the length of the game in seconds.\n\n def draw_text(self, text, x, y, colour):\n textsurface = self.config.myfont.render(text, False, colour)\n self.config.screen.blit(textsurface, (x, y))\n\n def draw_centred_white_text(self, text, position, y):\n assert position in ['Centre', 'Left', 'Right']\n\n pixels_per_char = 12 # Width of 1 char of text of screen in Courier font.\n if position == \"Centre\":\n self.draw_text(text,\n int(self.config.screen_centre[0] - pixels_per_char * len(text) / 2),\n y,\n self.config.WHITE)\n elif position == \"Left\":\n self.draw_text(text,\n int(self.config.screen_size[0] * 0.25 - pixels_per_char * len(text) / 2),\n y,\n self.config.WHITE)\n else:\n self.draw_text(text,\n int(self.config.screen_size[0] * 0.75 - pixels_per_char * len(text) / 2),\n y,\n self.config.WHITE)\n\n # Draw the frames per second at the bottom left of the screen.\n def draw_fps(self):\n self.draw_text('FPS = ' + str(round(self.config.clock.get_fps())),\n 10, self.config.screen_size[1] - 45, self.config.WHITE)\n\n def draw_game_info(self):\n # Always draw first player's score, as there is always at least 1 player.\n if self.config.monochrome:\n c1 = self.config.WHITE\n c2 = self.config.WHITE\n else:\n c1 = self.players[0].colour\n if self.config.num_players ==2:\n c2 = self.players[1].colour\n\n self.draw_text(self.players[0].player_name + ': ' + str(self.players[0].score), 10, 10, c1)\n\n if self.config.num_players == 2:\n self.draw_text(self.players[1].player_name + ': ' + str(self.players[1].score),\n self.config.screen_size[0] - 200,\n 10,\n c2)\n\n if not self.config.demo_mode:\n self.draw_centred_white_text('Time: ' + str(round(self.game_end_time - time.time())), 'Centre', 10)\n\n # Draw instruction on screen during demo mode.\n def draw_demo_info(self):\n self.draw_centred_white_text('GAME OVER', 'Centre', self.config.screen_centre[1] - 150)\n self.draw_centred_white_text('Press 1 for 1 player game', 'Centre', self.config.screen_centre[1] - 100)\n self.draw_centred_white_text('Press 2 for 2 player game', 'Centre', self.config.screen_centre[1] - 75)\n\n self.draw_centred_white_text('Player 1', 'Left', self.config.screen_centre[1] + 50)\n self.draw_centred_white_text('Z = Rotate anticlockwise', 'Left', self.config.screen_centre[1] + 75)\n self.draw_centred_white_text('X = Rotate clockwise', 'Left', self.config.screen_centre[1] + 100)\n self.draw_centred_white_text('A = Fire gun', 'Left', self.config.screen_centre[1] + 125)\n\n self.draw_centred_white_text('Player 2', 'Right', self.config.screen_centre[1] + 50)\n self.draw_centred_white_text('← = Rotate anticlockwise', 'Right', self.config.screen_centre[1] + 75)\n self.draw_centred_white_text('→ = Rotate clockwise', 'Right', self.config.screen_centre[1] + 100)\n self.draw_centred_white_text('/ = Fire gun', 'Right', self.config.screen_centre[1] + 125)\n\n # This one method does the drawing of all of the graphical elements in the game.\n def draw_all_elements(self):\n # Clear the screen and set the screen background.\n self.config.screen.fill(self.config.BLACK)\n\n for r in self.rocks: # Draw each rock.\n r.draw(self.config)\n\n # Loop through all of the players, drawing their ships, and their ship's bullets.\n for p in self.players:\n p.ship.draw(self.config) # Draw the player's space ship.\n\n for b in p.ship.bullets: # Draw each bullet.\n b.draw(self.config)\n\n self.draw_game_info()\n\n if self.config.demo_mode:\n self.draw_demo_info()\n\n # If in debug mode, draw the frames per second onscreen.\n if self.config.debug:\n self.draw_fps()\n\n pygame.display.flip()\n\n # Take a screenshot. Save it in the 'screenshots' folder.\n def take_screenshot(self):\n screenshot_name = 'screenshots/screenshot' + format(self.config.screenshot_num, '04') + '.png'\n pygame.image.save(self.config.screen, screenshot_name)\n self.config.screenshot_num += 1\n\n # Act on key presses bu game players.\n def key_handling(self):\n keys = pygame.key.get_pressed()\n\n if keys[pygame.K_z]:\n self.players[0].ship.rotate_anticlockwise()\n if keys[pygame.K_x]:\n self.players[0].ship.rotate_clockwise()\n if keys[pygame.K_a]:\n self.players[0].ship.fire_bullet(self.config) # Need config, as it contains the bullet firing sound.\n\n if self.config.num_players == 2:\n if keys[pygame.K_LEFT]:\n self.players[1].ship.rotate_anticlockwise()\n if keys[pygame.K_RIGHT]:\n self.players[1].ship.rotate_clockwise()\n if keys[pygame.K_SLASH]:\n self.players[1].ship.fire_bullet(self.config) # Need config, as it contains the bullet firing sound.\n\n if keys[pygame.K_g]:\n self.take_screenshot()\n\n if keys[pygame.K_ESCAPE]:\n return True\n else:\n return False\n\n # Do one tick of the game logic and drawing to screen, etc.\n # If in demo mode, collision detection will be skipped.\n def animate_1_tick(self):\n # Ensure that the game ticks do not exceed the target FPS.\n self.config.clock.tick(self.config.target_fps)\n\n for p in self.players:\n # If player ship exploding, do the next step of the explosion animation.\n if p.ship.exploding:\n p.ship.animate_explosion(self.config)\n\n if p.ship.kill:\n p.lost_a_spaceship()\n\n for b in p.ship.bullets:\n b.move()\n b.check_onscreen(self.config)\n if b.kill:\n p.ship.bullets.remove(b)\n trace(self.config, 'Bullet removed, bullets left for ' +\n p.player_name + ' =' + str(len(p.ship.bullets)))\n\n for r in self.rocks:\n r.move()\n r.check_onscreen(self.config)\n\n # Check whether this rock has been hit by a bullet.\n if not r.exploding:\n for p in self.players:\n\n # In demo mode, don't check for collisions.\n if not self.config.demo_mode:\n for b in p.ship.bullets:\n r.check_collision(b.coords)\n if r.collision:\n r.explode(self.config)\n b.kill = True # This bullet has killed a rock, so it must be killed itself too.\n p.killed_a_rock(r.size)\n\n # In demo mode, don't check for collisions.\n if not r.exploding and not self.config.demo_mode:\n for p in self.players:\n if not p.ship.exploding:\n\n r.check_collision(p.ship.coords)\n if r.collision: # The rock hit the ship.\n r.explode(self.config) # Start exploding the rock.\n p.ship.explode(self.config)\n\n # If this rock is exploding, do the steps of the explosion animation - including possibly, creating\n # child rocks.\n if r.exploding:\n r.animate_explosion(self)\n\n if r.kill:\n if r.exploding: # Must have collided with something.\n # If we are getting low on rocks, then create a new large rock.\n if len(self.rocks) <= self.num_rocks:\n new_rock = Rock(self.config, 'Large')\n new_rock.place_on_side_of_screen(self.config)\n self.rocks.append(new_rock)\n\n else: # Must be getting killed due to being at edge of screen.\n # Make new rock. Same size as one that is about to be removed.\n new_rock = Rock(self.config, r.size)\n new_rock.place_on_side_of_screen(self.config)\n self.rocks.append(new_rock)\n\n self.rocks.remove(r) # Rock is to be killed, so remove it from the list of rocks.\n\n trace(self.config, r.size + ' rock removed, rocks left=' + str(len(self.rocks)))\n\n self.draw_all_elements()\n\n # Actually play the game.\n def play(self):\n done = False\n self.config.demo_mode = False # This is not a demo, this is the real game.\n self.config.monochrome = False # Actual games are in colour.\n\n # Loop until the user clicks the close button, or game time is up.\n while not done:\n for event in pygame.event.get(): # User did something\n if event.type == pygame.QUIT: # If user clicked close\n self.config.quit = True\n done = True # Flag that we are done so we exit this loop\n\n # Out of time?\n if time.time() >= self.game_end_time:\n done = True\n\n escape_pressed = self.key_handling()\n if escape_pressed:\n done = True\n\n self.animate_1_tick()\n\n\n############################################\n# CONFIG\n############################################\n\nclass Config:\n\n def __init__(self, debug, target_fps):\n\n self.debug = debug # True=logging sent to stdout, and current FPS displayed on screen.\n self.target_fps = target_fps # Some game animations use target Frames Per Second to control their pace.\n\n self.monochrome = True # True=old style graphics used for rocks, etc.\n self.num_players = 1\n\n self.demo_mode = True\n self.quit = False # Will become true when the use chooses to quit the game.\n\n pygame.init() # Initialize the game engine.\n\n # Define the colors we will use in RGB format.\n self.BLACK = (0, 0, 0)\n self.WHITE = (255, 255, 255)\n self.RED = [255, 0, 0]\n self.GREEN = [0, 255, 0]\n\n # Set the height and width of the viewport.\n self.screen_size = [800, 600]\n self.screen_centre = [int(self.screen_size[0] / 2), int(self.screen_size[1] / 2)]\n self.screen = pygame.display.set_mode(self.screen_size)\n\n self.clock = pygame.time.Clock()\n\n # Start the Pygame text rendering system.\n pygame.font.init()\n self.myfont = pygame.font.SysFont('Courier New', 20)\n\n pygame.display.set_caption('Space Rocks') # The game window title.\n\n # Start the Pygame sound system.\n pygame.mixer.init()\n pygame.mixer.set_num_channels(3) # One channel for laser gun fires, one for explosions.\n\n # Get some game sounds ready, and allocate sound channels for them.\n self.explosion_sound = pygame.mixer.Sound('assets/110115__ryansnook__small-explosion.wav')\n self.laser_sound = pygame.mixer.Sound('assets/341235__sharesynth__laser01.wav')\n self.ship_explosion_sound = pygame.mixer.Sound('assets/235968__tommccann__explosion-01.wav')\n self.explosion_channel = pygame.mixer.Channel(0)\n self.laser_channel = pygame.mixer.Channel(1)\n self.ship_explosion_channel = pygame.mixer.Channel(2)\n\n # Border greater than width of largest possible rock. This ensures that when a rock is removed for being\n # outside of the screen plus border, we can be sure that all of the rock is off screen. If the border wasn't\n # wide enough rocks that are drifting off screen could be removed while part of them is still onscreen.\n self.border = 100\n\n # These are the edges of the zone where graphical objects are born and die.\n self.left_dead = - self.border\n self.top_dead = -self.border\n self.right_dead = self.screen_size[0] + self.border\n self.bottom_dead = self.screen_size[1] + self.border\n\n self.screenshot_num = 1 # Number of screenshots taken.\n\n def choose_options(self):\n this_game = Game(self)\n\n while not self.quit:\n for event in pygame.event.get(): # User did something\n if event.type == pygame.QUIT: # If user clicked close\n self.quit = True # Flag that we are done so we exit this loop, and quit the game\n\n keys = pygame.key.get_pressed()\n\n if keys[pygame.K_1]: # '1' key starts a one player game.\n self.num_players = 1\n this_game = Game(self)\n this_game.play()\n self.demo_mode = True\n self.monochrome = True # Demo mode is monochrome.\n\n if keys[pygame.K_2]: # '2' key starts a two player game.\n self.num_players = 2\n this_game = Game(self)\n this_game.play()\n self.demo_mode = True\n self.monochrome = True # Demo mode is monochrome.\n\n if keys[pygame.K_g]:\n this_game.take_screenshot()\n\n if not self.quit:\n this_game.animate_1_tick()\n\n # Be IDLE friendly.\n pygame.quit()\n","sub_path":"space_rocks.py","file_name":"space_rocks.py","file_ext":"py","file_size_in_byte":34015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"627654690","text":"import requests\nimport time\nimport pandas as pd\n# golbal variables\nmatchesInfo = []\ntry:\n api_key = 'api_key=RGAPI-17fc5594-8fac-430c-bb62-729b4420bae8'\n url = 'https://br1.api.riotgames.com/lol/'\n challengerSummoners = f'{url}league/v4/entries/RANKED_SOLO_5x5/PLATINUM/IV?{api_key}'\n response = requests.get(challengerSummoners)\n summoners = response.json()\n for summoner in summoners:\n try:\n summonerId = summoner['summonerId']\n accountBySummoner = f'{url}summoner/v4/summoners/{summonerId}?{api_key}'\n account = requests.get(accountBySummoner).json()\n accountId = account['accountId']\n beginIndex = 0\n while beginIndex < 10:\n print(accountId + \" index: \" + str(beginIndex) + \" Size: \" + str(len(matchesInfo)))\n try:\n matchlistByAccount = f'{url}match/v4/matchlists/by-account/{accountId}?beginIndex={beginIndex}&endIndex=40&{api_key}'\n beginIndex += 100\n responseMatches = requests.get(matchlistByAccount)\n matchesJson = responseMatches.json()['matches']\n for match in matchesJson:\n matchId = match['gameId']\n readed = False\n while not readed:\n try:\n matchByMatchId = f'{url}match/v4/matches/{matchId}?{api_key}'\n matchResponse = requests.get(matchByMatchId).json()\n matchId = matchResponse['gameId']\n identities = matchResponse['participantIdentities']\n duration = matchResponse['gameDuration']\n participants = matchResponse['participants']\n cont = 0\n for participant in participants:\n stats = participant['stats']\n stats['gameId'] = matchId\n stats['gameDuration'] = duration\n stats['lane'] = participant['timeline']['lane']\n stats['participantId'] = participant['participantId']\n stats['teamId'] = participant['teamId']\n stats['championId'] = participant['championId']\n stats['spell1Id'] = participant['spell1Id']\n stats['spell2Id'] = participant['spell2Id']\n stats['participantId'] = identities[cont]['player']['accountId']\n matchesInfo.append(stats)\n cont += 1\n readed = True\n \n except Exception as e:\n print(e)\n print(\"Reconectando\")\n readed = False\n time.sleep(5)\n except Exception:\n print(\"Reconectando\")\n time.sleep(30)\n df = pd.DataFrame(matchesInfo)\n df.to_csv('platParticipants.csv', index = False, header=True)\n except Exception:\n print(\"Reconectando\")\n time.sleep(30)\n df = pd.DataFrame(matchesInfo)\n df.to_csv('platParticipants.csv', index = False, header=True)\nexcept KeyboardInterrupt:\n print('interrompendo')\n df = pd.DataFrame(matchesInfo)\n df.to_csv('platParticipants.csv', index = False, header=True)\n time.sleep(5)\n exit(0)\n\ndf = pd.DataFrame(matchesInfo)\ndf.to_csv('platParticipants.csv', index = False, header=True)","sub_path":"scripts/getPlatData.py","file_name":"getPlatData.py","file_ext":"py","file_size_in_byte":3891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"244159383","text":"import numpy as np\nimport sys\nsys.path.append('..')\nfrom chap11.dubins_parameters import dubins_parameters\nfrom message_types.msg_path import msgPath\n\nclass path_manager:\n def __init__(self):\n # message sent to path follower\n self.path = msgPath()\n # pointers to previous, current, and next waypoints\n self.ptr_previous = 0\n self.ptr_current = 1\n self.ptr_next = 2\n # flag that request new waypoints from path planner\n self.flag_need_new_waypoints = True\n self.delay = False\n self.halfspace_n = np.inf * np.ones((3,1))\n self.halfspace_r = np.inf * np.ones((3,1))\n # state of the manager state machine\n self.manager_state = 1\n # dubins path parameters\n self.dubins_path = dubins_parameters()\n\n def update(self, waypoints, radius, state):\n # this flag is set for one time step to signal a redraw in the viewer\n if self.path.flag_path_changed:\n self.path.flag_path_changed = False\n self.delay = False\n if self.delay:\n self.path.flag_path_changed = True\n if waypoints.num_waypoints == 0:\n waypoints.flag_manager_requests_waypoints = True\n else:\n if waypoints.type == 'straight_line':\n self.line_manager(waypoints, state)\n elif waypoints.type == 'fillet':\n self.fillet_manager(waypoints, radius, state)\n elif waypoints.type == 'dubins':\n self.dubins_manager(waypoints, radius, state)\n else:\n print('Error in Path Manager: Undefined waypoint type.')\n return self.path\n\n def line_manager(self, waypoints, state):\n p = np.array([[state.pn], [state.pe], [-state.h]])\n w_prev = (waypoints.ned[:, self.ptr_previous]).reshape(-1,1)\n w_curr = (waypoints.ned[:, self.ptr_current]).reshape(-1,1)\n w_next = (waypoints.ned[:, self.ptr_next]).reshape(-1,1)\n vector_diff_prev = w_curr - w_prev\n q_prev = vector_diff_prev/np.linalg.norm(vector_diff_prev)\n vector_diff_next = w_next - w_curr\n q_curr = vector_diff_next/np.linalg.norm(vector_diff_next)\n self.halfspace_r = w_curr\n self.halfspace_n = q_curr + q_prev/(np.linalg.norm(q_curr + q_prev))\n if self.inHalfSpace(p):\n self.increment_pointers(waypoints)\n self.delay = True\n self.path.line_origin = w_prev\n self.path.line_direction = q_prev\n \n\n def fillet_manager(self, waypoints, radius, state):\n p = np.array([[state.pn], [state.pe], [-state.h]])\n w_prev = (waypoints.ned[:, self.ptr_previous]).reshape(-1,1)\n w_curr = (waypoints.ned[:, self.ptr_current]).reshape(-1,1)\n w_next = (waypoints.ned[:, self.ptr_next]).reshape(-1,1)\n vector_diff_prev = w_curr - w_prev\n q_prev = vector_diff_prev/np.linalg.norm(vector_diff_prev)\n vector_diff_next = w_next - w_curr\n q_curr = vector_diff_next/np.linalg.norm(vector_diff_next)\n psi = np.arccos(-q_prev.T @ q_curr)\n if self.manager_state == 1:\n self.path.type = 'line'\n self.path.line_origin = w_prev\n self.path.line_direction = q_prev\n self.halfspace_r = w_curr-(radius/np.tan(psi/2)) * q_prev\n self.halfspace_n = q_prev\n if self.inHalfSpace(p):\n self.manager_state = 2\n self.delay = True\n elif self.manager_state == 2:\n self.path.type = 'orbit'\n norm_diff = (q_prev - q_curr)/np.linalg.norm(q_prev-q_curr)\n self.path.orbit_center = w_curr - radius/np.sin(psi/2) * norm_diff\n self.path.orbit_radius = radius\n self.path.orbit_direction = self.orbit_direction_string(np.sign(q_prev.item(0)*q_curr.item(1) - q_prev.item(1)*q_curr.item(0)))\n self.halfspace_r = w_curr + (radius/np.tan(psi/2)) * q_curr\n self.halfspace_n = q_curr\n if self.inHalfSpace(p):\n self.manager_state = 1\n self.increment_pointers(waypoints)\n self.delay = True\n # self.path.line_origin = w_prev\n # self.path.line_direction = q_prev\n\n def dubins_manager(self, waypoints, radius, state):\n p = np.array([[state.pn], [state.pe], [-state.h]])\n w_prev = (waypoints.ned[:, self.ptr_previous]).reshape(-1,1)\n chi_prev = waypoints.course.item(self.ptr_previous)\n w_curr = (waypoints.ned[:, self.ptr_current]).reshape(-1,1)\n chi_curr = waypoints.course.item(self.ptr_current)\n self.dubins_path.update(w_prev, chi_prev, w_curr, chi_curr, radius)\n if self.manager_state == 1:\n self.path.type = 'orbit'\n self.path.orbit_center = self.dubins_path.center_s\n self.path.orbit_radius = self.dubins_path.radius\n self.path.orbit_direction = self.orbit_direction_string(self.dubins_path.dir_s)\n self.halfspace_r = self.dubins_path.r1\n self.halfspace_n = -self.dubins_path.n1\n if self.inHalfSpace(p):\n self.manager_state = 2\n self.delay = True\n elif self.manager_state == 2:\n self.halfspace_r = self.dubins_path.r1\n self.halfspace_n = self.dubins_path.n1\n if self.inHalfSpace(p):\n self.manager_state = 3\n self.delay = True\n elif self.manager_state == 3:\n self.path.type = 'line'\n self.path.line_origin = self.dubins_path.r1\n self.path.line_direction = self.dubins_path.n1\n self.halfspace_r = self.dubins_path.r2\n self.halfspace_n = self.dubins_path.n1\n if self.inHalfSpace(p):\n self.manager_state = 4\n self.delay = True\n elif self.manager_state == 4:\n self.path.type = 'orbit'\n self.path.orbit_center = self.dubins_path.center_e\n self.path.orbit_radius = self.dubins_path.radius\n self.path.orbit_direction = self.orbit_direction_string(self.dubins_path.dir_e)\n self.halfspace_r = self.dubins_path.r3\n self.halfspace_n = -self.dubins_path.n3\n if self.inHalfSpace(p):\n self.manager_state = 5\n self.delay = True\n elif self.manager_state == 5:\n self.halfspace_n = self.dubins_path.n3\n if self.inHalfSpace(p):\n self.manager_state = 1\n self.increment_pointers(waypoints)\n self.delay = True\n \n\n def initialize_pointers(self):\n self.ptr_previous = 0\n self.ptr_current = 1\n self.ptr_next = 2\n\n def increment_pointers(self, waypoints):\n self.ptr_previous += 1\n self.ptr_current += 1\n self.ptr_next += 1\n if self.ptr_previous == waypoints.num_waypoints:\n self.ptr_previous = 0\n if self.ptr_current == waypoints.num_waypoints:\n self.ptr_current = 0\n if self.ptr_next == waypoints.num_waypoints:\n self.ptr_next = 0\n\n def inHalfSpace(self, pos):\n if (pos - self.halfspace_r).T @ self.halfspace_n >= 0:\n return True\n else:\n return False\n\n def orbit_direction_string(self, value):\n if value == 1:\n res = 'CW'\n elif value == -1:\n res = 'CCW'\n return res","sub_path":"chap11/path_manager.py","file_name":"path_manager.py","file_ext":"py","file_size_in_byte":7426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"48312998","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.6 (62161)\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.linux-x86_64/egg/khan/session.py\n# Compiled at: 2010-05-12 10:25:54\n\"\"\"\n会话管理(Session)\n=================================\n\n本模块提供工具去管理请求期间的用户会话(Session).\n\n索引\n=================================\n\n* :attr:`session`\n* :class:`SessionContainer`\n* :class:`ISessionIdentifier`\n* :class:`CookieIdentifier`\n* :class:`HTTPHeaderIdentifier`\n* :class:`SessionMiddleware`\n* :func:`make_session_middleware`\n* :func:`make_cookie_identifier_plugin`\n* :func:`make_httpheader_identifier_plugin`\n\n=================================\n\n.. attribute:: session\n \n 该变量在 :class:`SessionMiddleware` 中间件接收到请求的时候注册并可用.\n\n.. autoclass:: SessionContainer\n.. autoclass:: ISessionIdentifier\n.. autoclass:: CookieIdentifier\n.. autoclass:: HTTPHeaderIdentifier\n.. autoclass:: SessionMiddleware\n.. autofunction:: make_session_middleware\n.. autofunction:: make_cookie_identifier_plugin\n.. autofunction:: make_httpheader_identifier_plugin\n\"\"\"\nimport logging, time\nfrom UserDict import DictMixin\nfrom webob import Request, Response\nfrom zope.interface import Interface, implements\nfrom paste.registry import StackedObjectProxy, RegistryManager\nfrom paste.util.converters import asbool\nfrom khan.utils import requestTypes, request_classifier, isiterable, unique_id\nfrom khan.store import get_backend\nfrom khan.deploy import loadobject\nfrom khan.urlparse import get_wild_domain, remove_port_from_domain\n__all__ = [\n 'session',\n 'SessionContainer',\n 'ISessionIdentifier',\n 'SessionMiddleware',\n 'HTTPHeaderIdentifier',\n 'CookieIdentifier']\nsession = StackedObjectProxy(None, name='session')\n\nclass SessionContainer(DictMixin):\n \"\"\"\n 会话容器,用于存储一个用户会话期间的数据,本容器实现 dict 接口.\n 所有数据的更改都必须调用 :meth:`save` 方法之后才生效.\n \n :data id: session id\n \"\"\"\n\n @staticmethod\n def create(store, expires=None):\n u\"\"\"\n 助手函数,用于建立一个 :class:`SessionContainer` 实例\n \n :param store: dict like object\n :param expires: 过期时间\n \n :rtype: :class:`SessionContainer`\n \"\"\"\n sid = unique_id()\n return SessionContainer(sid, store, expires)\n\n def __init__(self, sid, store, expires=None):\n u\"\"\"\n :param sid: session id, 该值应该用 :func:`unique_id` 函数建立\n :param store: 实现了 dict 接口的对象,该对象将作为存储数据的介质, \n :param expires: session 过期时间(秒), 默认为 600 (10 分钟)\n \n :type sid: string\n :type store: dict like object\n :type expires: int or None\n \"\"\"\n self._store = store\n self._expires = expires and int(expires) or 600\n if sid in self._store:\n try:\n (exp, value) = self._store[sid]\n except TypeError:\n del self._store[sid]\n self._data = {}\n else:\n if exp < time.time():\n del self._store[sid]\n self._data = {}\n else:\n self._data = value\n exp = time.time() + self._expires\n self._store[sid] = (exp, value)\n else:\n self._data = {}\n self.created = False\n self.id = sid\n\n def __setitem__(self, key, value):\n self._data[key] = value\n\n def __getitem__(self, key):\n return self._data[key]\n\n def __delitem__(self, key):\n del self._data[key]\n\n def __contains__(self, key):\n return key in self._data\n\n def keys(self):\n return self._data.keys()\n\n def save(self):\n u\"\"\"\n 保存session数据,并写入存储介质\n \"\"\"\n exp = time.time() + self._expires\n self._store[self.id] = (exp, self._data)\n self.created = True\n try:\n self._store.sync()\n except AttributeError:\n pass\n\n\nclass ISessionIdentifier(Interface):\n \"\"\"\n Session ID 获取和写入接口, 被 :class:`SessionMiddleware` 用于从用户请求中获得 session 标识(sid) \n 和保存用户 session 标识到客户端\n \"\"\"\n\n def identify(self, req):\n u\"\"\"\n 从用户请求中获得 session 标识(sid)\n \n :param environ: wsgi environ\n :type environ: dict\n \n :rtype: string\n \"\"\"\n pass\n\n def remember(self, resp, session):\n u\"\"\"\n 保存用户 session 标识到客户端, 本函数的默认行为是什么都不做\n \n :param resp: webob.Response\n :param session: 用户 session\n \n :type resp: webob.Response\n :type session: :class:`SessionContainer`\n \"\"\"\n pass\n\n\nclass CookieIdentifier(object):\n \"\"\"\n 用 Cookie 保存 session id\n \n .. seealso:: \n \n :class:`ISessionIdentifier`, :class:`SessionMiddleware`, :class:`HTTPHeaderIdentifier`\n \"\"\"\n implements(ISessionIdentifier)\n COOKIE_NAME = 'X-Kh-Sid'\n\n def __init__(self, name=COOKIE_NAME, max_age=None, path='/', domain=None, secure=False):\n self._cookie_name = name\n self._cookie_max_age = max_age\n self._cookie_path = path\n self._cookie_domain = domain\n self._cookie_secure = secure\n self._logger = logging.getLogger(__name__ + '.' + self.__class__.__name__)\n\n def decide(self, req):\n return requestTypes.BROWSER == request_classifier(req.environ)\n\n def identify(self, req):\n if not self.decide(req):\n return\n if self._cookie_name in req.cookies:\n self._logger.debug(\"get session identify from cookie '%s'.\" % self._cookie_name)\n return req.cookies[self._cookie_name]\n\n def remember(self, resp, session):\n if not self.decide(resp.request):\n return resp\n else:\n if session.created:\n self._logger.debug(\"write session identify to cookie '%s'.\" % self._cookie_name)\n if self._cookie_domain is None:\n cur_domain = resp.request.environ.get('HTTP_HOST', resp.request.environ.get('SERVER_NAME'))\n cur_domain = remove_port_from_domain(cur_domain)\n wild_domain = get_wild_domain(cur_domain)\n resp.set_cookie(self._cookie_name, session.id, max_age=self._cookie_max_age, path=self._cookie_path, secure=self._cookie_secure)\n resp.set_cookie(self._cookie_name, session.id, max_age=self._cookie_max_age, path=self._cookie_path, domain=cur_domain, secure=self._cookie_secure)\n resp.set_cookie(self._cookie_name, session.id, max_age=self._cookie_max_age, path=self._cookie_path, domain=wild_domain, secure=self._cookie_secure)\n else:\n resp.set_cookie(self._cookie_name, session.id, max_age=self._cookie_max_age, path=self._cookie_path, domain=self._cookie_domain, secure=self._cookie_secure)\n return resp\n\n\ndef make_cookie_identifier_plugin(global_conf, name=CookieIdentifier.COOKIE_NAME, max_age=None, path='/', domain=None, secure=False):\n \"\"\"\n Paste EGG entry point::\n \n session.cookie\n \n PasteDeploy example::\n\n [filter:session]\n use = egg:khan#session\n identifiers = cookie\n \n [object:cookie]\n use = egg:khan#session.cookie\n name = X-Kh-Sid\n domain = .domain.com\n path = /\n max_age = 124000\n \n .. seealso:: \n \n :class:`CookieIdentifier`, :class:`SessionMiddleware`\n \"\"\"\n secure = asbool(secure)\n if max_age:\n max_age = int(max_age)\n return CookieIdentifier(name=name, max_age=max_age, path=path, domain=domain, secure=secure)\n\n\nclass HTTPHeaderIdentifier(object):\n \"\"\"\n 用 HTTP header 保存 session id\n \n .. seealso:: \n \n :class:`ISessionIdentifier`, :class:`SessionMiddleware`, :class:`CookieIdentifier`\n \"\"\"\n implements(ISessionIdentifier)\n HEADER_NAME = 'X-Kh-Sid'\n\n def __init__(self, name=HEADER_NAME):\n self._field_name = name\n self._logger = logging.getLogger(__name__ + '.' + self.__class__.__name__)\n\n def identify(self, req):\n if self._field_name in req.headers:\n self._logger.debug(\"get session identify from http header '%s'.\" % self._field_name)\n return req.headers[self._field_name]\n\n def remember(self, resp, session):\n if session.created:\n self._logger.debug(\"write session identify to http header '%s'.\" % self._field_name)\n resp.headers[self._field_name] = session.id\n return resp\n\n\ndef make_httpheader_identifier_plugin(global_conf, name=HTTPHeaderIdentifier.HEADER_NAME):\n \"\"\"\n Paste EGG entry point::\n \n session.header\n \n PasteDeploy example::\n\n [filter:session]\n use = egg:khan#session\n identifiers = header\n \n [object:header]\n use = egg:khan#session.header\n name = X-Kh-Sid\n \n .. seealso:: \n \n :class:`HTTPHeaderIdentifier`, :class:`SessionMiddleware`\n \"\"\"\n return HTTPHeaderIdentifier(name)\n\n\nclass RequestParamIdentifier(object):\n \"\"\"\n 用 request params 保存 session id, 专门用来对付无 Cookie 会话问题\n \n .. seealso:: \n \n :class:`ISessionIdentifier`, :class:`SessionMiddleware`, :class:`CookieIdentifier`\n \"\"\"\n implements(ISessionIdentifier)\n FIELD_NAME = 'X-Kh-Sid'\n\n def __init__(self, name=None):\n self._field_name = name or RequestParamIdentifier.FIELD_NAME\n self._logger = logging.getLogger(__name__ + '.' + self.__class__.__name__)\n\n def identify(self, req):\n if self._field_name in req.params:\n self._logger.debug(\"get session identify from request params(%s) '%s'.\" % (req.method, self._field_name))\n return req.params[self._field_name]\n\n def remember(self, resp, session):\n return resp\n\n\ndef make_request_param_identifier_plugin(global_conf, name=None):\n \"\"\"\n Paste EGG entry point::\n \n session.req_param\n \n PasteDeploy example::\n\n [filter:session]\n use = egg:khan#session\n identifiers = req_param\n \n [object:req_param]\n use = egg:khan#session.req_param\n name = X-Kh-Sid\n \n .. seealso:: \n \n :class:`HTTPHeaderIdentifier`, :class:`SessionMiddleware`\n \"\"\"\n return RequestParamIdentifier(name)\n\n\nclass SessionMiddleware(object):\n \"\"\"\n Session 中间件,在 app 处理请求前本中间件会注册一个 :data:`session` (:class:`SessionContainer` 实例) 全局变量,\n 该变量在请求期间可用. \n \"\"\"\n ENVIRON_KEY = 'khan.session'\n\n def __init__(self, app, store=None, identifiers=None, expires=None):\n u\"\"\"\n :param app: wsgi app\n :param store: session 数据的存储介质, 默认用 \"memory://\"\n :param identifiers: 一个 :class:`ISessionIdentifier` 对象列表, 默认为 [:class:`CookieIdentifier`]\n :param expires: session 过期时间,默认为 600 秒(10分钟)\n \n :type store: dict like object\n :type identifiers: list\n :type expires: int or None\n \"\"\"\n if identifiers:\n if not isiterable(identifiers):\n identifiers = [\n identifiers]\n else:\n identifiers = [\n CookieIdentifier()]\n self._identifiers = identifiers\n self._app = app\n self._wapper_app = RegistryManager(self._wapper_call)\n if store is None:\n store = get_backend('memory://')\n self._store = store\n self._expires = expires\n self._logger = logging.getLogger(__name__ + '.' + self.__class__.__name__)\n return\n\n def _wapper_call(self, environ, start_response):\n req = Request(environ)\n sid = None\n for identifier in self._identifiers:\n if identifier is None:\n continue\n identify = identifier.identify(req)\n if identify:\n sid = identify.strip()\n break\n\n if not sid:\n sess = SessionContainer.create(self._store, expires=self._expires)\n elif sid in self._store:\n sess = SessionContainer(sid, self._store, expires=self._expires)\n else:\n self._logger.debug(\"sid '%s' not in store.\" % sid)\n sess = SessionContainer.create(self._store, expires=self._expires)\n reg = environ['paste.registry']\n reg.register(session, sess)\n orig_resp_data = []\n\n def repl_start_response(status, headers, exc_info=None):\n orig_resp_data[:] = (status, headers)\n return lambda x: None\n\n resp_body = self._app(environ, repl_start_response)\n resp = Response(('').join(resp_body), status=orig_resp_data[0], headerlist=orig_resp_data[1], request=req)\n if sess.created:\n for identifier in self._identifiers:\n resp = identifier.remember(resp, sess)\n\n return resp(environ, start_response)\n\n def __call__(self, environ, start_response):\n if self.ENVIRON_KEY in environ:\n self._logger.debug('`%s` exists.' % self.__class__.__name__)\n return self._app(environ, start_response)\n else:\n environ[self.ENVIRON_KEY] = self\n return self._wapper_app(environ, start_response)\n\n\ndef make_session_middleware(global_conf, store=None, expires=None, identifiers=None, conf=None):\n u\"\"\"\n Paste EGG entry point::\n \n session\n \n PasteDeploy example::\n \n [app:sessionstore]\n use = egg:khan#rpcstore\n store = dbm://session.db\n \n [filter:session]\n use = egg:khan#session\n expires = 600\n store = store\n identifiers = cookie header\n \n [object:store]\n use = egg:khan#store\n uri = khan.rpc://localhost:7040\n cache = memory://\n rpc_timeout = 30\n \n [object:cookie]\n use = egg:khan#session.cookie\n name = X-Kh-Sid\n domain = .domain.com\n path = /\n max_age = 124000\n \n [object:header]\n use = egg:khan#session.header\n name = X-Kh-Sid\n \n .. seealso:: \n \n 关于 store 请看 :mod:`khan.store`\n \n .. seealso::\n \n :class:`SessionMiddleware`\n \"\"\"\n conf = conf or global_conf['__file__']\n expires = expires and int(expires) or None\n identifier_plugins = []\n if identifiers:\n for identifier_name in identifiers.split():\n identifier_plugins.append(loadobject('config:%s' % conf, identifier_name, global_conf))\n\n if store:\n if '://' in store:\n store = get_backend(store)\n else:\n store = loadobject('config:%s' % conf, store, global_conf)\n\n def middleware(app):\n return SessionMiddleware(app, store, identifier_plugins, expires=expires)\n\n return middleware\n\n\nclass TesterIdentifier(object):\n implements(ISessionIdentifier)\n session_id = None\n\n def __init__(self):\n self._logger = logging.getLogger(__name__ + '.' + self.__class__.__name__)\n\n def identify(self, req):\n self._logger.debug('identify session id: %s' % self.session_id)\n return self.session_id\n\n def remember(self, resp, session):\n if session.created:\n self.session_id = session.id\n else:\n self.session_id = None\n self._logger.debug('remember session id: %s' % self.session_id)\n return","sub_path":"pycfiles/Khan-0.1.6dev-py2.6/session.py","file_name":"session.py","file_ext":"py","file_size_in_byte":15854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"34597569","text":"from nltk.corpus import wordnet\n\nsyn = set() # 유의어\nant = set() # 반의어\nfor synset in wordnet.synsets(\"Worse\"):\n for lemma in synset.lemmas():\n syn.add(lemma.name())\n if lemma.antonyms():\n ant.add(lemma.antonyms()[0].name())\n\nprint('단어, 품사 : ' + synset.name())\nprint('의미 : ' + synset.definition())\nprint('예문 : ' + str(synset.examples()))\nprint('유의어: ' + str(syn))\nprint('반의어: ' + str(ant))\n","sub_path":"wordnet-sample.py","file_name":"wordnet-sample.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"626538310","text":"\"\"\" Testing for the the buffer.py module\n\nThe module can be executed on its own or incorporated into a larger test suite.\n\n\"\"\"\nimport _path\nimport _unittest as unittest\n\nfrom serial.core.buffer import _ReaderBuffer\nfrom serial.core.buffer import _WriterBuffer\n\n\n# The library doesn't include any concrete implementations of _ReaderBuffer or\n# _WriterBuffer, so create sample implementations\n\nclass ReaderBuffer(_ReaderBuffer):\n \"\"\" Concrete implementation of a _ReaderBuffer for testing.\n \n \"\"\"\n def __init__(self, reader):\n \"\"\" Initialize this object.\n \n \"\"\"\n super(ReaderBuffer, self).__init__(reader)\n self._buffer = None\n return\n \n def _queue(self, record):\n \"\"\" Merge every two records.\n \n \"\"\"\n if not self._buffer:\n # First record in a pair.\n self._buffer = record\n else:\n # Complete the pair.\n record[\"int\"] = self._buffer[\"int\"]\n self._output.append(record)\n self._buffer = None\n return\n\n def _uflow(self):\n \"\"\" Handle an underflow condition.\n \n \"\"\"\n if self._buffer:\n # No more input, so output the last record as-is.\n self._output.append(self._buffer)\n self._buffer = None\n else:\n raise StopIteration\n return\n\n\nclass WriterBuffer(_WriterBuffer):\n \"\"\" Concrete implementation of a _WriterBuffer for testing.\n \n \"\"\"\n def __init__(self, writer):\n \"\"\" Initialize this object.\n \n \"\"\"\n super(WriterBuffer, self).__init__(writer)\n self._buffer = None\n return\n \n def _queue(self, record):\n \"\"\" Merge every two records.\n \n \"\"\"\n if not self._buffer:\n # First record in a pair.\n self._buffer = record\n else:\n # Complete the pair.\n record[\"int\"] = self._buffer[\"int\"]\n self._output.append(record)\n self._buffer = None\n return\n\n def _flush(self):\n \"\"\" Complete any buffering operations. \n \n \"\"\"\n if self._buffer:\n # No more input, so output the last record as-is.\n self._output.append(self._buffer)\n return\n\n\n# Mock objects to use for testing.\n\nclass MockWriter(object):\n \"\"\" Simulate a _Writer for testing purposes.\n \n \"\"\"\n def __init__(self):\n \"\"\" Initialize this object.\n \n \"\"\"\n self.output = []\n self.write = self.output.append\n return\n\n\n# Define the TestCase classes for this module. Each public component of the\n# module being tested has its own TestCase.\n\nclass _BufferTest(unittest.TestCase):\n \"\"\" Unit testing for buffer classes.\n\n This is an abstract class and should not be called directly by any test\n runners.\n\n \"\"\"\n @staticmethod\n def reject_filter(record):\n \"\"\" Filter function to reject a record.\n \n \"\"\"\n return record if record[\"int\"] != 123 else None\n\n def setUp(self):\n \"\"\" Set up the test fixture.\n\n This is called before each test is run so that they are isolated from\n any side effects. This is part of the unittest API.\n\n Derived classes need to define the appropriate filter object.\n\n \"\"\"\n self.input = (\n {\"int\": 123, \"arr\": [{\"x\": \"abc\", \"y\": \"def\"}]},\n {\"int\": 456, \"arr\": [{\"x\": \"ghi\", \"y\": \"jkl\"}]},\n {\"int\": 789, \"arr\": [{\"x\": \"mno\", \"y\": \"pqr\"}]})\n self.output = (\n {\"int\": 123, \"arr\": [{\"x\": \"ghi\", \"y\": \"jkl\"}]},\n {\"int\": 789, \"arr\": [{\"x\": \"mno\", \"y\": \"pqr\"}]})\n return\n \n\nclass ReaderBufferTest(_BufferTest):\n \"\"\" Unit testing for the ReaderBuffer class.\n\n \"\"\" \n def setUp(self):\n \"\"\" Set up the test fixture.\n\n This is called before each test is run so that they are isolated from\n any side effects. This is part of the unittest API.\n\n \"\"\"\n super(ReaderBufferTest, self).setUp()\n self.buffer = ReaderBuffer(iter(self.input))\n return\n \n def test_iter(self):\n \"\"\" Test the iterator protocol.\n\n Tests both __iter__() and next().\n\n \"\"\"\n self.assertSequenceEqual(self.output, list(self.buffer))\n return\n \n def test_filter(self):\n \"\"\" Test the filter() method.\n \n \"\"\"\n # For now, relying on _Reader's test suite for more exhaustive tests so\n # just test the basics here.\n self.buffer.filter(self.reject_filter)\n self.output = self.output[1:]\n self.test_iter() \n return\n \n\nclass WriterBufferTest(_BufferTest):\n \"\"\" Unit testing for the WriterBuffer class.\n\n \"\"\" \n def setUp(self):\n \"\"\" Set up the test fixture.\n\n This is called before each test is run so that they are isolated from\n any side effects. This is part of the unittest API.\n\n \"\"\"\n super(WriterBufferTest, self).setUp()\n self.writer = MockWriter()\n self.buffer = WriterBuffer(self.writer) \n return\n\n def test_write(self):\n \"\"\" Test the write() method.\n\n \"\"\"\n for record in self.input:\n self.buffer.write(record)\n self.buffer.close()\n self.assertSequenceEqual(self.output, self.writer.output)\n return\n\n def test_dump(self):\n \"\"\" Test the dump() method.\n\n \"\"\"\n self.buffer.dump(self.input)\n self.assertSequenceEqual(self.output, self.writer.output)\n return\n\n def test_filter(self):\n \"\"\" Test the filter() method.\n \n \"\"\"\n # For now, relying on _Writer's test suite for more exhaustive tests so\n # just test the basics here.\n self.buffer.filter(self.reject_filter)\n self.output = self.output[1:]\n self.test_dump()\n return\n\n\n# Specify the test cases to run for this module (disables automatic discovery).\n\n_TEST_CASES = (ReaderBufferTest, WriterBufferTest)\n\ndef load_tests(loader, tests, pattern):\n \"\"\" Define a TestSuite for this module.\n\n This is part of the unittest API. The last two arguments are ignored. The\n _TEST_CASES global is used to determine which TestCase classes to load\n from this module.\n\n \"\"\"\n suite = unittest.TestSuite()\n for test_case in _TEST_CASES:\n tests = loader.loadTestsFromTestCase(test_case)\n suite.addTests(tests)\n return suite\n\n\n# Make the module executable.\n\nif __name__ == \"__main__\":\n unittest.main() # main() calls sys.exit()\n","sub_path":"test/test_buffer.py","file_name":"test_buffer.py","file_ext":"py","file_size_in_byte":6606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"318431038","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Nov 14 14:35:19 2018\r\n\r\n@author: teranishis\r\n\"\"\"\r\nimport matplotlib.pyplot as plt\r\nimport pickle\r\nimport os\r\nimport numpy as np\r\nfrom PIL import Image\r\nfrom keras.models import Model\r\nfrom keras.layers import Input, Conv2D, Activation, MaxPool2D, BatchNormalization, Flatten, Dense, Dropout\r\nfrom keras.optimizers import Adam\r\nfrom keras.utils import np_utils\r\nfrom keras.utils import to_categorical\r\nfrom keras.utils import Sequence\r\nfrom keras.preprocessing.image import ImageDataGenerator\r\nfrom sklearn.model_selection import train_test_split\r\nfrom keras.callbacks import ReduceLROnPlateau\r\n\r\n#画像の読み込み\r\n#学習用のデータを作る\r\nimage_list = []\r\nlabel_list = []\r\n\r\n# ./image/ 以下のディレクトリの画像を読み込む\r\nfor dir in os.listdir(\"./images\"):\r\n if dir == \".DS_Store\":\r\n continue\r\n \r\n dir1 = \"./images/\" + dir\r\n #フォルダ0のラベルは0、、、\r\n label = dir\r\n \r\n for file in os.listdir(dir1):\r\n #配列label_listに正解ラベルを追加\r\n label_list.append(label)\r\n filepath = dir1 + \"/\" + file\r\n #画像を読み込み、グレースケールに変換し、28x28pixelに変換し、numpy配列へ変換する\r\n #画像の1ピクセルはそれぞれ0-255\r\n image = np.array(Image.open(filepath).convert(\"RGB\").resize((64, 64)))\r\n #print(filepath)\r\n #さらにフラットな1次元配列に変換\r\n #image = image.reshape(1, 784).astype(\"float32\")[0]\r\n #出来上がった配列をimage_listに追加\r\n image_list.append(image)\r\n \r\n#kerasに渡すためにnumpy配列に変換\r\nimage_list = np.array(image_list)\r\nlabel_list = np.array(label_list)\r\n\r\n#クラスの形式を変換\r\nlabel_list = np_utils.to_categorical(label_list, 37)\r\n\r\n#学習用データとテストデータ\r\nX_t, X_test, y_t, y_test = train_test_split(image_list, label_list, test_size = 0.3)\r\nX_train, X_val, y_train, y_val = train_test_split(X_t, y_t, test_size = 0.2)\r\n\r\n#モデル\r\ninput = Input(shape=(64, 64, 3))\r\nX = Conv2D(64, (1, 1), padding = \"same\")(input)\r\nX = BatchNormalization()(X)\r\nX = Activation(\"relu\")(X)\r\nX = Conv2D(64, (3, 3), padding = \"same\")(X)\r\nX = BatchNormalization()(X)\r\nX = Activation(\"relu\")(X)\r\nX = Conv2D(64, (5, 5), padding = \"same\")(X)\r\nX = BatchNormalization()(X)\r\nX = Activation(\"relu\")(X)\r\nX = MaxPool2D((2, 2), padding = \"same\")(X)\r\n#X = Dropout(0.25)(X)\r\n\r\nX = Conv2D(128, (1, 1), padding = \"same\")(X)\r\nX = BatchNormalization()(X)\r\nX = Activation(\"relu\")(X)\r\nX = Conv2D(128, (3, 3), padding = \"same\")(X)\r\nX = BatchNormalization()(X)\r\nX = Activation(\"relu\")(X)\r\nX = Conv2D(128, (5, 5), padding = \"same\")(X)\r\nX = BatchNormalization()(X)\r\nX = Activation(\"relu\")(X)\r\nX = MaxPool2D((2, 2), padding = \"same\")(X)\r\n#X = Dropout(0.25)(X)\r\n\r\nX = Conv2D(256, (1, 1), padding = \"same\")(X)\r\nX = BatchNormalization()(X)\r\nX = Activation(\"relu\")(X)\r\nX = Conv2D(256, (3, 3), padding = \"same\")(X)\r\nX = BatchNormalization()(X)\r\nX = Activation(\"relu\")(X)\r\nX = Conv2D(256, (5, 5), padding = \"same\")(X)\r\nX = BatchNormalization()(X)\r\nX = Activation(\"relu\")(X)\r\nX = MaxPool2D((2, 2), padding = \"same\")(X)\r\n#X = Dropout(0.25)(X)\r\n\r\nX = Conv2D(512, (1,1), padding = \"same\")(X)\r\nX = BatchNormalization()(X)\r\nX = Activation(\"relu\")(X)\r\nX = Conv2D(512, (3, 3), padding = \"same\")(X)\r\nX = BatchNormalization()(X)\r\nX = Activation(\"relu\")(X)\r\nX = Conv2D(512, (5, 5), padding = \"same\")(X)\r\nX = BatchNormalization()(X)\r\nX = Activation(\"relu\")(X)\r\nX = MaxPool2D((2, 2), padding = \"same\")(X)\r\n#X = Dropout(0.5)(X)\r\n\r\nX = Flatten()(X)\r\nX = Dense(4096, activation = \"relu\")(X)\r\n#X = Dropout(0.5)(X)\r\nX = Dense(4096, activation = \"relu\")(X)\r\n#X = Dropout(0.25)(X)\r\nX = Dense(1000, activation = \"relu\")(X)\r\n#X = Dropout(0.5)(X)\r\noutput = Dense(37, activation=\"softmax\")(X)\r\n\r\nmodel = Model(input, output)\r\n\r\n#コンパイル\r\nmodel.compile(optimizer=Adam(lr = 1e-4), loss = \"categorical_crossentropy\",\r\n metrics=[\"accuracy\"])\r\n\r\n# Data Augmentation\r\ndatagen = ImageDataGenerator(\r\n rescale = 1./255,\r\n featurewise_center = True,\r\n featurewise_std_normalization = True,\r\n rotation_range=20,\r\n width_shift_range=0.2,\r\n height_shift_range=0.2,\r\n channel_shift_range=50,\r\n horizontal_flip = True)\r\nvalidationgen = ImageDataGenerator(rescale=1./255)\r\n\r\n#フィット\r\n#datagen.fit(X_train)\r\n#validationgen.fit(X_val)\r\n#train_gen = ImageSequence(X_train, 37, 128)\r\n#valid_gen = ImageSequendce(X_val, 37, 128)\r\nreduce_lr = ReduceLROnPlateau(monitor = \"val_loss\", factor = 0.5, patience = 10,min_lr = 0, verbose = 1)\r\nhistory = model.fit_generator(datagen.flow(X_train, y_train, batch_size = 200),\r\n steps_per_epoch = len(X_train) / 4, validation_data=validationgen.flow(X_val, y_val),\r\n epochs = 30, validation_steps = len(X_val), callbacks = [reduce_lr], shuffle = True)\r\n#history = model.fit_generator(generator = train_gen, epochs = 1000, steps_per_epoch=len(X_train), \r\n# verbose = 1, validation_data = valid_gen, validation_steps = len(valid_gen))\r\n\r\nwith open(\"history.dat\", \"wb\") as fp:\r\n pickle.dump(history, fp)\r\n \r\n#モデルと重みを保存\r\njson_string = model.to_json()\r\nopen(\"dog_cat_cnn.json\", \"w\").write(json_string)\r\nmodel.save_weights(\"dog_cat_cnn.h5\")\r\n\r\n#モデルの表示\r\nmodel.summary()\r\n\"\"\"\r\n#評価\r\nscore = model.evaluate(X_test, y_test, verbose=0)\r\nprint(\"test loss:\", score[0])\r\nprint(\"test accuracy:\",score[1])\r\n\"\"\"\r\n#訓練時の損失値と正解率をプロット\r\nacc = history.history[\"acc\"]\r\nval_acc = history.history[\"val_acc\"]\r\nloss = history.history[\"loss\"]\r\nval_loss = history.history[\"val_loss\"]\r\nepochs = range(1, len(acc) + 1)\r\n\r\n#正解率をプロット\r\nplt.plot(epochs, acc, \"o\", label=\"Training acc\")\r\nplt.plot(epochs, val_acc, \"b\", label = \"Validation acc\")\r\nplt.title(\"Training and validation accuracy\")\r\nplt.legend()\r\n\r\nplt.figure()\r\n\r\n#損失値をプロット\r\nplt.plot(epochs, loss, \"bo\", label = \"Training loss\")\r\nplt.plot(epochs, val_loss, \"b\", label = \"Validation loss\")\r\nplt.title(\"Training and validation loss\")\r\nplt.legend()\r\n\r\nplt.show()\r\n\r\nhistory_dict = history.history\r\nhistory_dict.keys()","sub_path":"他クラス分類.py","file_name":"他クラス分類.py","file_ext":"py","file_size_in_byte":6295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"525069932","text":"from django.conf.urls import url\nfrom . import views\n\napp_name = 'qanda'\nurlpatterns = [\n url(r'^$', views.index, name='index'),\n url(r'ask/$', views.ask_question, name='ask'),\n url(r'question/(?P[0-9]+)/$', views.question, name='question'),\n url(r'answerit/(?P[0-9]+)/$', views.answer_question, name='answerit'),\n url(r'answer/(?P[0-9]+)/$', views.answer, name='answer'),\n url(r'commentquest/(?P[0-9]+)/$', views.commentquest, name='commentquest'),\n url(r'commentansw/(?P[0-9]+)/$', views.commentansw, name='commentansw'),\n url(r'questcomm/(?P[0-9]+)/$', views.question_comment, name='questcomm'),\n url(r'answcomm/(?P[0-9]+)/$', views.answer_comment, name='answcomm'),\n ]\n","sub_path":"qanda/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"553748575","text":"from flask import Blueprint\nfrom flask_restplus import Api, fields\n\n# Create a blueprint that will link the API Engine to the App\napiBlueprint = Blueprint('api', __name__)\n\napiEngine = Api(apiBlueprint, version='1.0', title='PyBlock Auth',\n description=\"PyBlock Auth Microservice API\", prefix=\"/v1\")\n\n\n# ## Utils\nclass DateFormatter(fields.Raw):\n def format(self, value):\n val = value.strftime(\"%d/%m/%Y %H:%M\")\n return val\n\n\n# Namespace Import\nfrom v1.urlUser import user_ns, admin_ns, auth_ns\n\n# clear all the namespaces\napiEngine.namespaces.clear()\n\n# Add Namespaces (and all the routes own by the resources) to the ApiEngine\napiEngine.add_namespace(user_ns)\napiEngine.add_namespace(admin_ns)\napiEngine.add_namespace(auth_ns)\n","sub_path":"python/pyAuth/v1/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"637329682","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nDoc String goes here.\n\"\"\"\n\n__author__ = \"Joshua Casara\"\n__email__ = \"jcasara@ucmerced.edu\"\n__created__ = \"Created on 06/04/2017 at 17:29:06\"\n__edited__ = \"Edited on 06/04/2017 at 17:29:06\"\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\n\noutcomes = {\n 'royal-flush' : 0.0032,\n 'straight-flush' : 0.0279,\n 'four-kind' : 0.168,\n 'full-house' : 2.60,\n 'flush' : 3.03,\n 'straight' : 4.62,\n 'three-kind' : 4.83,\n 'two-pair' : 23.5,\n 'pair' : 43.8,\n 'high' : 17.4\n}\n\npriority = [\n 'royal-flush',\n 'straight-flush',\n 'four-kind',\n 'full-house',\n 'flush',\n 'straight',\n 'three-kind',\n 'two-pair',\n 'pair',\n 'high'\n ]\n \nX = []\nY = [] \nfor i,j in enumerate(priority):\n x,y = [i,outcomes[j]]\n X.append(x)\n Y.append(y)\nX = np.array(X,dtype= float)\nY = np.array(Y,dtype = float)\nfig = plt.figure(figsize=(20,6))\nax = fig.add_subplot(111)\n\nplt.xticks(np.arange(min(X)+0.4, max(X)+1+0.4, 1.0))\n\n# We need to draw the canvas, otherwise the labels won't be positioned and \n# won't have values yet.\nfig.canvas.draw()\n \nlabels = [item.get_text() for item in ax.get_xticklabels()]\nlabels = priority\nax.set_xticklabels(labels)\nplt.bar(X,Y) \nplt.ylabel('Percent Probablity') \nplt.show()","sub_path":"plot histrogram of poker frequencies.py","file_name":"plot histrogram of poker frequencies.py","file_ext":"py","file_size_in_byte":1312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"635165527","text":"####################\n# ES-DOC CIM Questionnaire\n# Copyright (c) 2015 ES-DOC. All rights reserved.\n#\n# University of Colorado, Boulder\n# http://cires.colorado.edu/\n#\n# This project is distributed according to the terms of the MIT license [http://www.opensource.org/licenses/MIT].\n####################\n\n__author__ = 'allyn.treshansky'\n\n\nfrom Q.questionnaire.tests.test_base import TestQBase, create_ontology, remove_ontology, incomplete_test\nfrom Q.questionnaire.q_utils import serialize_model_to_dict\nfrom Q.questionnaire.models.models_ontologies import *\n\n\nclass TestQOntolgoy(TestQBase):\n\n def setUp(self):\n\n super(TestQOntolgoy, self).setUp()\n\n # create a test ontology\n self.test_ontology = create_ontology(\n name=\"test_ontology\",\n version=\"1.0\",\n )\n\n def tearDown(self):\n\n super(TestQOntolgoy, self).tearDown()\n\n # delete the test ontology\n remove_ontology(ontology=self.test_ontology)\n\n def test_ontology_get_key(self):\n\n test_key = \"test_ontology_1.0\"\n self.assertEqual(self.test_ontology.get_key(), test_key)\n self.assertEqual(QOntology.objects.get(key=test_key), self.test_ontology)\n\n self.test_ontology.version = \"123\"\n self.test_ontology.save()\n\n test_key = \"test_ontology_123\"\n self.assertEqual(self.test_ontology.get_key(), test_key)\n self.assertEqual(QOntology.objects.get(key=test_key), self.test_ontology)\n\n def test_ontology_register(self):\n\n self.assertFalse(self.test_ontology.is_registered)\n self.test_ontology.register()\n self.assertTrue(self.test_ontology.is_registered)\n\n test_model_proxies = self.test_ontology.model_proxies.all()\n test_property_proxies = QStandardPropertyProxy.objects.filter(model_proxy__ontology=self.test_ontology)\n\n actual_model_proxies_data = [\n serialize_model_to_dict(model_proxy, exclude=[\"id\", \"guid\", \"created\", \"modified\"])\n for model_proxy in test_model_proxies\n ]\n\n test_model_proxies_data = [\n {'name': u'modelComponent', 'stereotype': u'document', 'package': None, 'documentation': u'A ModelCompnent is nice.', 'namespace': None, 'ontology': self.test_ontology.pk, 'order': 0},\n {'name': u'responsibleParty', 'stereotype': None, 'package': None, 'documentation': u'a stripped-down responsible party to use for testing purposes.', 'namespace': None, 'ontology': self.test_ontology.pk, 'order': 1},\n {'name': u'contactType', 'stereotype': None, 'package': None, 'documentation': u'a stripped-down contactType just for testing purposes.', 'namespace': None, 'ontology': self.test_ontology.pk, 'order': 2},\n ]\n\n for actual_model_proxy_data, test_model_proxy_data in zip(actual_model_proxies_data, test_model_proxies_data):\n self.assertDictEqual(actual_model_proxy_data, test_model_proxy_data)\n\n actual_property_proxies_data = [\n serialize_model_to_dict(property_proxy, exclude=[\"id\", \"guid\", \"created\", \"modified\"])\n for property_proxy in test_property_proxies\n ]\n\n test_property_proxies_data = [\n {'field_type': u'ATOMIC', 'atomic_default': None, 'enumeration_nullable': False, 'name': u'string', 'stereotype': None, 'relationship_target_model': None, 'relationship_target_name': None, 'enumeration_choices': u'', 'documentation': u'I am a string', 'namespace': None, 'atomic_type': u'DEFAULT', 'order': 0, 'is_label': True, 'enumeration_open': False, 'cardinality': u'0|1', 'model_proxy': test_model_proxies[0].pk, 'enumeration_multi': False},\n {'field_type': u'ATOMIC', 'atomic_default': None, 'enumeration_nullable': False, 'name': u'boolean', 'stereotype': None, 'relationship_target_model': None, 'relationship_target_name': None, 'enumeration_choices': u'', 'documentation': u'I am a boolean', 'namespace': None, 'atomic_type': u'BOOLEAN', 'order': 1, 'is_label': False, 'enumeration_open': False, 'cardinality': u'0|1', 'model_proxy': test_model_proxies[0].pk, 'enumeration_multi': False},\n {'field_type': u'ATOMIC', 'atomic_default': None, 'enumeration_nullable': False, 'name': u'date', 'stereotype': None, 'relationship_target_model': None, 'relationship_target_name': None, 'enumeration_choices': u'', 'documentation': u'I am a date', 'namespace': None, 'atomic_type': u'DATE', 'order': 2, 'is_label': False, 'enumeration_open': False, 'cardinality': u'0|1', 'model_proxy': test_model_proxies[0].pk, 'enumeration_multi': False},\n {'field_type': u'ATOMIC', 'atomic_default': None, 'enumeration_nullable': False, 'name': u'uncategorized', 'stereotype': None, 'relationship_target_model': None, 'relationship_target_name': None, 'enumeration_choices': u'', 'documentation': u'I am an uncategorized string', 'namespace': None, 'atomic_type': u'DEFAULT', 'order': 3, 'is_label': False, 'enumeration_open': False, 'cardinality': u'0|1', 'model_proxy': test_model_proxies[0].pk, 'enumeration_multi': False},\n {'field_type': u'ENUMERATION', 'atomic_default': None, 'enumeration_nullable': False, 'name': u'enumeration', 'stereotype': None, 'relationship_target_model': None, 'relationship_target_name': None, 'enumeration_choices': u'one|two|three', 'documentation': u'I am an enumreation', 'namespace': None, 'atomic_type': None, 'order': 4, 'is_label': False, 'enumeration_open': False, 'cardinality': u'0|1', 'model_proxy': test_model_proxies[0].pk, 'enumeration_multi': False},\n {'field_type': u'RELATIONSHIP', 'atomic_default': None, 'enumeration_nullable': False, 'name': u'author', 'stereotype': None, 'relationship_target_model': 2, 'relationship_target_name': u'responsibleParty', 'enumeration_choices': u'', 'documentation': u'I am a relationship', 'namespace': None, 'atomic_type': None, 'order': 5, 'is_label': False, 'enumeration_open': False, 'cardinality': u'0|1', 'model_proxy': test_model_proxies[0].pk, 'enumeration_multi': False},\n {'field_type': u'RELATIONSHIP', 'atomic_default': None, 'enumeration_nullable': False, 'name': u'contact', 'stereotype': None, 'relationship_target_model': 2, 'relationship_target_name': u'responsibleParty', 'enumeration_choices': u'', 'documentation': u'I am a relationship', 'namespace': None, 'atomic_type': None, 'order': 6, 'is_label': False, 'enumeration_open': False, 'cardinality': u'0|*', 'model_proxy': test_model_proxies[0].pk, 'enumeration_multi': False},\n {'field_type': u'ATOMIC', 'atomic_default': None, 'enumeration_nullable': False, 'name': u'individualName', 'stereotype': None, 'relationship_target_model': None, 'relationship_target_name': None, 'enumeration_choices': u'', 'documentation': u'', 'namespace': None, 'atomic_type': u'DEFAULT', 'order': 0, 'is_label': True, 'enumeration_open': False, 'cardinality': u'0|1', 'model_proxy': test_model_proxies[1].pk, 'enumeration_multi': False},\n {'field_type': u'RELATIONSHIP', 'atomic_default': None, 'enumeration_nullable': False, 'name': u'contactInfo', 'stereotype': None, 'relationship_target_model': 3, 'relationship_target_name': u'contactType', 'enumeration_choices': u'', 'documentation': u'', 'namespace': None, 'atomic_type': None, 'order': 1, 'is_label': False, 'enumeration_open': False, 'cardinality': u'1|1', 'model_proxy': test_model_proxies[1].pk, 'enumeration_multi': False},\n {'field_type': u'ATOMIC', 'atomic_default': None, 'enumeration_nullable': False, 'name': u'phone', 'stereotype': None, 'relationship_target_model': None, 'relationship_target_name': None, 'enumeration_choices': u'', 'documentation': u'', 'namespace': None, 'atomic_type': u'DEFAULT', 'order': 0, 'is_label': False, 'enumeration_open': False, 'cardinality': u'0|1', 'model_proxy': test_model_proxies[2].pk, 'enumeration_multi': False},\n {'field_type': u'ATOMIC', 'atomic_default': None, 'enumeration_nullable': False, 'name': u'address', 'stereotype': None, 'relationship_target_model': None, 'relationship_target_name': None, 'enumeration_choices': u'', 'documentation': u'', 'namespace': None, 'atomic_type': u'TEXT', 'order': 1, 'is_label': False, 'enumeration_open': False, 'cardinality': u'0|1', 'model_proxy': test_model_proxies[2].pk, 'enumeration_multi': False},\n ]\n\n for actual_property_proxy_data, test_property_proxy_data in zip(actual_property_proxies_data, test_property_proxies_data):\n self.assertDictEqual(actual_property_proxy_data, test_property_proxy_data)\n\n @incomplete_test\n def test_ontology_reregister(self):\n pass\n","sub_path":"Q/questionnaire/tests/tests_unit/tests_models/test_ontologies.py","file_name":"test_ontologies.py","file_ext":"py","file_size_in_byte":8592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"380799371","text":"import tensorflow as tf \nimport time\nimport numpy as np \nimport scipy as sp \nfrom pointNet_model import *\nimport argparse\n\nHEIGHT = 1000\nWIDTH = 4\nCHANNEL = 1\nif __name__ == '__main__':\n # Read arguments\n parser = argparse.ArgumentParser()\n parser.add_argument('train', help='tf record filename')\n parser.add_argument('-b', '--batch-size', default=10, type=int, help='batch size')\n parser.add_argument('-e', '--epochs', default=4000, type=int, help='num of epochs')\n parser.add_argument('-o', '--output', default='model', help='model output')\n parser.add_argument('-l', '--log', default='logs', help='log directory')\n args = parser.parse_args()\n\n filename_queue = tf.train.string_input_producer(args.train)\n image, label = read_and_decode(filename_queue)\n batch = tf.train.shuffle_batch([image, label], batch_size=args.batch_size, capacity=800, num_threads=2, min_after_dequeue=200)\n\n points = tf.placeholder(tf.float32, [None, HEIGHT,WIDTH, CHANNEL], name='points')\n \n","sub_path":"misc/pointNet_train.py","file_name":"pointNet_train.py","file_ext":"py","file_size_in_byte":1008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"272615583","text":"# Copyright 2015 Mirantis, Inc\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# 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, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport json\nimport requests\n\nfrom cloudv_ostf_adapter.common import exception\n\n\nclass Plugins(object):\n\n route = \"http://%(host)s:%(port)d/%(api_version)s/plugins\"\n\n def __init__(self, **kwargs):\n self.url = self.route % kwargs\n\n def list(self, load_tests=True):\n params = {'load_tests': load_tests}\n response = requests.get(self.url, params=params)\n if not response.ok:\n raise exception.exception_mapping.get(response.status_code)()\n resp = json.loads(response.content)\n return resp['plugins']\n","sub_path":"cloudv_client/plugins.py","file_name":"plugins.py","file_ext":"py","file_size_in_byte":1166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"644040483","text":"import numpy as np\nimport functools\n\ninputfile = \"input16\"\nexample = '''Valve AA has flow rate=0; tunnels lead to valves DD, II, BB\nValve BB has flow rate=13; tunnels lead to valves CC, AA\nValve CC has flow rate=2; tunnels lead to valves DD, BB\nValve DD has flow rate=20; tunnels lead to valves CC, AA, EE\nValve EE has flow rate=3; tunnels lead to valves FF, DD\nValve FF has flow rate=0; tunnels lead to valves EE, GG\nValve GG has flow rate=0; tunnels lead to valves FF, HH\nValve HH has flow rate=22; tunnel leads to valve GG\nValve II has flow rate=0; tunnels lead to valves AA, JJ\nValve JJ has flow rate=21; tunnel leads to valve II'''\n\nalphabet = \"abcdefghijklmnopqrstuvwxyz\"\nALPHABET = alphabet.capitalize()\n\nneighbours = [(1, 0), (0, 1), (-1, 0), (0, -1)]\n\ndef textgrid_to_numbers(lines):\n return np.array([[int(x) for x in line] for line in lines], dtype=int)\n\ndef traverse(root):\n sum = 0\n for entry in root.keys():\n if entry == '..':\n continue\n if isinstance(root[entry], dict):\n sum += traverse(root[entry])\n else:\n sum += root[entry]\n global totsum\n totsum.append(sum)\n return sum\n\ndef append_if_exists(dictionary: dict, key, val):\n if key not in dictionary.keys():\n dictionary[key] = []\n\n dictionary[key].append(val)\n\ndef calc_distances_from(name: str, valves: dict):\n distances = {}\n visited = set([name])\n search_next = [name]\n distance = 0\n distances[name] = 0\n while len(visited) != len(valves.keys()):\n distance += 1\n search_next_round = []\n for valve in search_next:\n for neighbour in valves[valve]['connections']:\n if neighbour not in visited:\n visited.add(neighbour)\n distances[neighbour] = distance\n search_next_round.append(neighbour)\n search_next = search_next_round\n \n return distances\n\ncounter = 0\ndef main():\n import sys\n lines = []\n if len(sys.argv) > 1 and sys.argv[1] == '--example':\n lines = example.splitlines()\n else: \n file_contents = ''\n with open(inputfile) as infile:\n file_contents = infile.read()\n \n lines = file_contents.splitlines() \n\n print(f\"Read {len(lines)} lines\")\n\n valves = {}\n for line in lines:\n parts = line.split(' ')\n valve_name = parts[1]\n rate = int(parts[4].split('=')[1][:-1])\n connections = []\n for conn in parts[9:]:\n connections.append(conn.rstrip(','))\n \n valves[valve_name] = {'rate': rate, 'connections': connections}\n \n distances = {}\n for name in valves.keys():\n distances[name] = calc_distances_from(name, valves)\n valves[name]['distances'] = distances[name]\n \n not_visited_strip_zero = frozenset(valve_name for valve_name in valves.keys() if valves[valve_name]['rate'] > 0)\n # not_visited_ones = frozenset(valve_name for valve_name in valves.keys())\n @functools.cache\n def strip_not_reachable(at_valve, minutes_left, not_visited):\n return frozenset(valve_name for valve_name in not_visited if distances[at_valve][valve_name] + 1 <= minutes_left)\n\n def calc_score_at(at_valve, minutes):\n return valves[at_valve]['rate'] * minutes\n\n @functools.cache\n def best_score_from_here(at_valve, minutes_left, not_visited):\n global counter\n counter += 1\n if counter % 10000 == 0:\n print(f'done {counter} counts')\n best_score = 0\n\n for other_valve in not_visited:\n cost = distances[at_valve][other_valve] + 1\n minutes_left_after = minutes_left - cost\n not_visited_and_reachable = strip_not_reachable(other_valve, minutes_left_after, not_visited - frozenset([other_valve]))\n score_from_valve = calc_score_at(other_valve, minutes_left_after)\n # print(f'at: {at_valve}, fo: {other_valve}, mins left: {minutes_left_after}, not_visited_and_reachable: {not_visited_and_reachable}')\n # print(f'get {score_from_valve} from valve')\n score_after_valve = best_score_from_here(other_valve, minutes_left_after, not_visited_and_reachable)\n tot_score = score_from_valve + score_after_valve\n \n best_score = max(tot_score, best_score)\n return best_score\n\n def sort_inputs(minutes_pair, places_pair):\n if (minutes_pair[0] < minutes_pair[1] or\n (minutes_pair[0] == minutes_pair[1] and places_pair[0] < places_pair[1])):\n return tuple(reversed(minutes_pair)), tuple(reversed(places_pair))\n return minutes_pair, places_pair\n\n @functools.cache\n def best_pair_score_from_here(minutes_pair, places_pair, not_visited):\n global counter\n counter += 1\n if counter % 10000 == 0:\n print(f'done {counter} counts')\n best_score = max(best_score_from_here(places_pair[0], minutes_pair[0], not_visited), \n best_score_from_here(places_pair[1], minutes_pair[1], not_visited))\n\n for other_valve in not_visited:\n cost = distances[places_pair[0]][other_valve] + 1\n minutes_left_after = minutes_pair[0] - cost\n not_visited_and_reachable_first = strip_not_reachable(other_valve, minutes_left_after, not_visited - frozenset([other_valve]))\n not_visited_and_reachable_second = strip_not_reachable(places_pair[1], minutes_pair[1], not_visited - frozenset([other_valve]))\n score_from_valve = calc_score_at(other_valve, minutes_left_after)\n # print(f'at: {at_valve}, fo: {other_valve}, mins left: {minutes_left_after}, not_visited_and_reachable: {not_visited_and_reachable}')\n # print(f'get {score_from_valve} from valve')\n new_minutes_pair, new_places_pair = sort_inputs((minutes_left_after, minutes_pair[1]), (other_valve, places_pair[1]))\n \n score_after_valve = best_pair_score_from_here(new_minutes_pair, new_places_pair, not_visited_and_reachable_first | not_visited_and_reachable_second)\n tot_score = score_from_valve + score_after_valve\n \n best_score = max(tot_score, best_score)\n return best_score\n\n\n best_score = best_score_from_here('AA', 30, not_visited_strip_zero)\n best_score = best_pair_score_from_here((26, 26), ('AA', 'AA'), not_visited_strip_zero)\n print(f'best score: {best_score}')\n \n\n\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"day16.py","file_name":"day16.py","file_ext":"py","file_size_in_byte":6505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"622428611","text":"import logging\nimport os\nimport re\nimport shlex\nimport time\nfrom unittest import mock\n\nimport globus_sdk\nimport pytest\nimport responses\nfrom click.testing import CliRunner\nfrom globus_sdk._testing import register_response_set\nfrom globus_sdk.tokenstorage import SQLiteAdapter\nfrom globus_sdk.transport import RequestsTransport\nfrom ruamel.yaml import YAML\n\nimport globus_cli\n\nyaml = YAML()\nlog = logging.getLogger(__name__)\n\n\n@pytest.fixture(autouse=True)\ndef mocksleep():\n with mock.patch(\"time.sleep\") as m:\n yield m\n\n\n@pytest.fixture(autouse=True)\ndef set_login_manager_testmode():\n globus_cli.login_manager.LoginManager._TEST_MODE = True\n\n\n@pytest.fixture(scope=\"session\")\ndef go_ep1_id():\n return \"ddb59aef-6d04-11e5-ba46-22000b92c6ec\"\n\n\n@pytest.fixture(scope=\"session\")\ndef go_ep2_id():\n return \"ddb59af0-6d04-11e5-ba46-22000b92c6ec\"\n\n\ndef _mock_token_response_data(rs_name, scope, token_blob=None):\n if token_blob is None:\n token_blob = rs_name.split(\".\")[0]\n return {\n \"scope\": scope,\n \"refresh_token\": f\"{token_blob}RT\",\n \"access_token\": f\"{token_blob}AT\",\n \"token_type\": \"bearer\",\n \"expires_at_seconds\": int(time.time()) + 120,\n \"resource_server\": rs_name,\n }\n\n\n@pytest.fixture\ndef mock_login_token_response():\n mock_token_res = mock.Mock()\n mock_token_res.by_resource_server = {\n \"auth.globus.org\": _mock_token_response_data(\n \"auth.globus.org\",\n \"openid profile email \"\n \"urn:globus:auth:scope:auth.globus.org:view_identity_set\",\n ),\n \"transfer.api.globus.org\": _mock_token_response_data(\n \"transfer.api.globus.org\",\n \"urn:globus:auth:scope:transfer.api.globus.org:all\",\n ),\n \"groups.api.globus.org\": _mock_token_response_data(\n \"groups.api.globus.org\", \"urn:globus:auth:scope:groups.api.globus.org:all\"\n ),\n \"search.api.globus.org\": _mock_token_response_data(\n \"search.api.globus.org\", \"urn:globus:auth:scope:search.api.globus.org:all\"\n ),\n }\n return mock_token_res\n\n\n@pytest.fixture\ndef client_login(monkeypatch):\n monkeypatch.setenv(\"GLOBUS_CLI_CLIENT_ID\", \"fake_client_id\")\n monkeypatch.setenv(\"GLOBUS_CLI_CLIENT_SECRET\", \"fake_client_secret\")\n\n\n@pytest.fixture()\ndef client_login_no_secret(monkeypatch):\n monkeypatch.setenv(\"GLOBUS_CLI_CLIENT_ID\", \"fake_client_id\")\n\n\n@pytest.fixture()\ndef user_profile(monkeypatch):\n monkeypatch.setenv(\"GLOBUS_PROFILE\", \"test_user_profile\")\n\n\n@pytest.fixture\ndef test_token_storage(mock_login_token_response):\n \"\"\"Put memory-backed sqlite token storage in place for the testsuite to use.\"\"\"\n mockstore = SQLiteAdapter(\":memory:\")\n mockstore.store_config(\n \"auth_client_data\",\n {\"client_id\": \"fakeClientIDString\", \"client_secret\": \"fakeClientSecret\"},\n )\n mockstore.store(mock_login_token_response)\n return mockstore\n\n\n@pytest.fixture(autouse=True)\ndef patch_tokenstorage(monkeypatch, test_token_storage):\n monkeypatch.setattr(\n globus_cli.login_manager.token_storage_adapter,\n \"_instance\",\n test_token_storage,\n raising=False,\n )\n\n\n@pytest.fixture\ndef add_gcs_login(test_token_storage):\n def func(gcs_id):\n mock_token_res = mock.Mock()\n mock_token_res.by_resource_server = {\n gcs_id: _mock_token_response_data(\n gcs_id, f\"urn:globus:auth:scopes:{gcs_id}:manage_collections\"\n )\n }\n test_token_storage.store(mock_token_res)\n\n return func\n\n\n@pytest.fixture(scope=\"session\")\ndef test_file_dir():\n return os.path.normpath(os.path.join(os.path.dirname(__file__), \"files\"))\n\n\n@pytest.fixture\ndef cli_runner():\n return CliRunner(mix_stderr=False)\n\n\nclass OutputMatcher:\n r\"\"\"\n A helper for running regex matches and optionally doing literal checking of match\n groups against expected strings. This can be attached to run_line by passing\n \"matcher=True\".\n\n Runs regex matches in multiline mode, operating on the first match.\n If no match is found, it will raise an error.\n\n Usage:\n\n >>> res, matcher = run_line(..., matcher=True)\n >>> matcher.check(r\"^Foo:\\s+(\\w+)$\", groups=[\"FooValue\"])\n \"\"\"\n\n def __init__(self, result):\n self._result = result\n\n def check(self, regex, groups=None, err=False) -> None:\n pattern = re.compile(regex, flags=re.MULTILINE)\n groups = groups or []\n data = self._result.stderr if err else self._result.output\n\n m = pattern.search(data)\n if not m:\n raise ValueError(f\"Did not find a match for '{regex}' in {data}\")\n for i, x in enumerate(groups, 1):\n assert m.group(i) == x\n\n\n@pytest.fixture\ndef run_line(cli_runner, request, patch_tokenstorage):\n \"\"\"\n Uses the CliRunner to run the given command line.\n\n Asserts that the exit_code is equal to the given assert_exit_code,\n and if that exit_code is 0 prevents click from catching exceptions\n for easier debugging.\n \"\"\"\n\n def func(line, assert_exit_code=0, stdin=None, matcher=False):\n from globus_cli import main\n\n # split line into args and confirm line starts with \"globus\"\n args = shlex.split(line) if isinstance(line, str) else line\n assert args[0] == \"globus\"\n\n # run the line. globus_cli.main is the \"globus\" part of the line\n # if we are expecting success (0), don't catch any exceptions.\n result = cli_runner.invoke(\n main, args[1:], input=stdin, catch_exceptions=bool(assert_exit_code)\n )\n if result.exit_code != assert_exit_code:\n raise (\n Exception(\n (\n \"CliTest run_line exit_code assertion failed!\\n\"\n \"Line:\\n{}\\nexited with {} when expecting {}\\n\"\n \"stdout:\\n{}\\nstderr:\\n{}\\nnetwork calls recorded:\"\n \"\\n {}\"\n ).format(\n line,\n result.exit_code,\n assert_exit_code,\n result.stdout,\n result.stderr,\n (\n \"\\n \".join(\n f\"{r.request.method} {r.request.url}\"\n for r in responses.calls\n )\n or \" \"\n ),\n )\n )\n )\n if matcher:\n return result, OutputMatcher(result)\n return result\n\n return func\n\n\n@pytest.fixture(autouse=True)\ndef mocked_responses(monkeypatch):\n \"\"\"\n All tests enable `responses` patching of the `requests` package, replacing\n all HTTP calls.\n \"\"\"\n responses.start()\n\n # while request mocking is running, ensure GLOBUS_SDK_ENVIRONMENT is set to\n # production\n monkeypatch.setitem(os.environ, \"GLOBUS_SDK_ENVIRONMENT\", \"production\")\n\n yield\n\n responses.stop()\n responses.reset()\n\n\ndef _iter_fixture_routes(routes):\n # walk a fixture file either as a list of routes\n for x in routes:\n # copy and remove elements\n params = dict(x)\n path = params.pop(\"path\")\n method = params.pop(\"method\", \"get\")\n yield path, method, params\n\n\n@pytest.fixture(autouse=True, scope=\"session\")\ndef _register_all_response_sets(test_file_dir):\n fixture_dir = os.path.join(test_file_dir, \"api_fixtures\")\n\n def do_register(filename):\n with open(os.path.join(fixture_dir, filename)) as fp:\n data = yaml.load(fp.read())\n\n response_set = {}\n response_set_metadata = {}\n for service, routes in data.items():\n if service == \"metadata\":\n response_set_metadata = routes\n continue\n\n for idx, (path, method, params) in enumerate(_iter_fixture_routes(routes)):\n if \"query_params\" in params:\n # TODO: remove this int/float conversion after we upgrade to\n # `responses>=0.19.0` when this issue is expected to be fixed\n # https://github.com/getsentry/responses/pull/485\n query_params = {\n k: str(v) if isinstance(v, (int, float)) else v\n for k, v in params.pop(\"query_params\").items()\n }\n params[\"match\"] = [\n responses.matchers.query_param_matcher(query_params)\n ]\n response_set[f\"{method}_{service}_{path}_{idx}\"] = {\n \"service\": service,\n \"path\": path,\n \"method\": method.upper(),\n **params,\n }\n\n scenario_name = filename.rsplit(\".\", 1)[0]\n register_response_set(\n f\"cli.{scenario_name}\", response_set, metadata=response_set_metadata\n )\n\n for filename in os.listdir(fixture_dir):\n if not filename.endswith(\".yaml\"):\n continue\n do_register(filename)\n\n\n@pytest.fixture(autouse=True)\ndef disable_client_retries(monkeypatch):\n class NoRetryTransport(RequestsTransport):\n DEFAULT_MAX_RETRIES = 0\n\n monkeypatch.setattr(globus_sdk.TransferClient, \"transport_class\", NoRetryTransport)\n monkeypatch.setattr(globus_sdk.AuthClient, \"transport_class\", NoRetryTransport)\n monkeypatch.setattr(\n globus_sdk.NativeAppAuthClient, \"transport_class\", NoRetryTransport\n )\n monkeypatch.setattr(\n globus_sdk.ConfidentialAppAuthClient, \"transport_class\", NoRetryTransport\n )\n","sub_path":"tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":9671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"550687744","text":"import logging\nfrom copy import deepcopy\nfrom dataclasses import dataclass\nfrom typing import Dict, Any, Callable, List, Optional, Union\n\nfrom .Singleton import Singleton\nfrom .util import get_pub_attr_of_class\n\nLOGGER: logging.Logger = logging.getLogger(__name__)\n\n\n@dataclass\nclass Subscriber:\n id: str\n callback: Callable[[Any], None]\n\n def notify(self, state: Any):\n self.callback(state)\n\n\nclass _State:\n name: str\n _value: Any\n _history: List[Any]\n _history_len: int\n _subscribers: Dict[str, Subscriber]\n _type: type\n\n def __init__(self, name: str, value: Any = None, type=None, history_len=10):\n \"\"\"\n\n :param name: the name of the state\n :param value: the initial value\n :param type: the type the value can be. If none is provided, it accepts any type as new state\n :param history_len: how many rollback states are saved.\n If it is 0 no history will be available, if it is set to a negative value, the history saves all values\n \"\"\"\n self.name = name\n self._value = value\n self._history_len = history_len\n self._history = []\n self._subscribers = {}\n self._type = type\n\n def subscribe(self, subscriber: Subscriber) -> bool:\n if subscriber.id in self._subscribers:\n return False\n self._subscribers[subscriber.id] = subscriber\n return True\n\n def unsubscribe(self, subscriber_id: str) -> bool:\n if subscriber_id in self._subscribers:\n self._subscribers.pop(subscriber_id)\n return True\n else:\n LOGGER.debug(f\"Could not unsubscribe {subscriber_id} from {self.name}: Not subscribed\")\n return False\n\n def notify(self):\n for subscriber in self._subscribers.values():\n subscriber.notify(self.get_value())\n\n def get_value(self) -> Any:\n return deepcopy(self._value)\n\n def set_value(self, value: Any) -> bool:\n if self._type is not None:\n if not isinstance(value, self._type):\n return False\n\n self._update_history()\n self._value = deepcopy(value)\n self.notify()\n return True\n\n def roll_back(self, index: int = 1) -> Optional[Any]:\n if index > self._history_len:\n return None\n return self._history[-index]\n \n def get_subscriber_ids(self) -> List[str]:\n return list(self._subscribers.keys())\n\n def _update_history(self):\n if self._history_len == 0:\n return\n self._history.append(self._value)\n if self._history_len < 0:\n return\n if self._history_len < len(self._history):\n self._history.pop(0)\n\n\nclass StateManager:\n \"\"\"\n A [StateManager] is an instance to hold any states and notify [Subscribers] on change.\n\n usage:\n\n ```\n class PortListener:\n ip: IPAddress\n _identifier: str = \"my PortListener\"\n\n def __init__(self):\n StateManager().subscribe(\"ip\", self._identifier, self.on_ip_change) # Subscribe to channel\n\n def __del__(self):\n StateManager().unsubscribe_all(self._identifier)\n\n def on_ip_change(self, ip: IPAddress): # callback for changes\n self.ip = ip\n print(f\"New IP: {self.ip}\")\n\n\n def main():\n port_listener = PortListener()\n\n state_manager = StateManager()\n state_manager.set_state(\"ip\", getIpAddress())\n ```\n\n \"\"\"\n _states: Dict[str, _State] = {}\n\n def set_state(self, state_name: str, state: Any, type: type = None) -> bool:\n \"\"\"\n Updates a state or creates it if the [state_name] is new\n :param state_name: the state identifier\n :param state: the new state\n :param type: if specified and [state_name] is new, the state will be type secure.\n Meaning it will only set to the specified [type]\n :return: bool of success. It could fail due [state] is not of the type-secure type\n \"\"\"\n if state_name in self._states:\n return self._states[state_name].set_value(state)\n else:\n self._states[state_name] = _State(name=state_name, value=state, type=type)\n return True\n\n def get_state(self, state_name: str) -> Optional[Any]:\n \"\"\"\n Returns the current state of a given [state_name]\n :param state_name: the state identifier\n :return: the states value or None if [state_name] unknown\n \"\"\"\n if state_name in self._states:\n return self._states[state_name].get_value()\n else:\n LOGGER.debug(f\"Could get_state {state_name}: No such state name\")\n\n def subscribe(self, state_name: str, subscriber: Subscriber) -> bool:\n \"\"\"\n Subscribes to a state\n :param subscriber: the subscriber to be notified on changes\n :param state_name: The state_identifier\n :return: bool of success. It could fail due subscribing with an already subscribed [subscriber_id]\n or to an unknown [state_name]\n \"\"\"\n if state_name in self._states:\n return self._states[state_name].subscribe(subscriber)\n else:\n LOGGER.debug(f\"Could not subscribe {subscriber.id} to {state_name}: No such state name\")\n return False\n\n def unsubscribe(self, state_name: str, subscriber_id: str) -> bool:\n \"\"\"\n Unsubscribe a [subscriber_id] from a state with [state_name] identifier\n :param state_name: the identifier of the state you want to unsub from\n :param subscriber_id: the identifier of the subscriber\n :return: bool of success. It could fail due to an unknown [state_name] \n or because [subscriber_id] is not a subscriber of [state_name]\n \"\"\"\n if state_name in self._states:\n return self._states[state_name].unsubscribe(subscriber_id)\n else:\n LOGGER.debug(f\"Could not unsubscribe {subscriber_id} from {state_name}: No such state name\")\n return False\n\n def unsubscribe_all(self, subscriber_id: str) -> bool:\n \"\"\"\n Unsubscribe a given [subscriber_id] from all subscribed states.\n This is especially helpful on destructors.\n :param subscriber_id: the identifier of the subscriber\n :return: bool of success. It could fail due to no subscriptions of [caller_id]\n \"\"\"\n success: bool = False\n for state in self._states.values():\n if subscriber_id in state.get_subscriber_ids():\n state.unsubscribe(subscriber_id)\n success = True\n return success\n\n def get_state_names(self) -> List[str]:\n \"\"\"\n :return: A list of all state identifiers\n \"\"\"\n return list(self._states.keys())\n\n\nclass StateManagerSingleton(StateManager, Singleton):\n \"\"\"\n A [StateManager] that is conveniently a Singleton and therefore can be just initialized where it is needed,\n to get a reference on it.\n \"\"\"\n pass\n\n\nclass State:\n \"\"\"\n A class to inherit from.\n All public setters will notify\n \"\"\"\n _subscriber: Dict[str, List[Subscriber]] = {}\n\n def __setattr__(self, key: str, value):\n object.__setattr__(self, key, deepcopy(value))\n if key[0] != \"_\" and key in self._subscriber:\n for subscriber in self._subscriber[key]:\n subscriber.notify(deepcopy(value))\n\n def subscribe(self, subscriber: Subscriber, attributes: Union[str, List[str]] = None) -> bool:\n \"\"\"\n Subscribe to a given list of [attributes]\n :param subscriber: the subscriber to notify\n :param attributes: the attributes to listen on\n :return: bool of success. It could fail due invalid [attributes] or already subscription of [subscriber].\n A fail only means 'something went wrong' not all.\n \"\"\"\n success: bool = True\n if attributes is None:\n attributes = get_pub_attr_of_class(self.__class__)\n if isinstance(attributes, str):\n attributes = [attributes]\n\n for attribute in attributes:\n if attribute not in get_pub_attr_of_class(self):\n LOGGER.debug(f\"{attribute} is not an subscribable attribute of {self.__class__.__name__}: \"\n f\"not subscribed\")\n success = False\n continue\n if attribute in self._subscriber and subscriber in self._subscriber[attribute]:\n LOGGER.debug(f\"{subscriber.id} has already subscribed to {self.__class__.__name__}.{attribute}\")\n success = False\n continue\n if attribute not in self._subscriber:\n self._subscriber[attribute] = []\n self._subscriber[attribute].append(subscriber)\n return success\n\n def unsubscribe(self, subscriber_id: str, attributes: Union[str, List[str]] = None) -> bool:\n \"\"\"\n Unsubscribes a subsciber from certain attributes.\n :param subscriber_id: the subscriber identifier\n :param attributes: the attributes to unsub from\n :return: bool of success. It could fail due to unknown attribute or no valid subscription of the subscriber.\n A fail only means 'something went wrong' not all.\n \"\"\"\n if attributes is None:\n return self.unsubscribe_all(subscriber_id)\n if isinstance(attributes, str):\n attributes = [attributes]\n\n subscriber = self._get_subscriber(subscriber_id)\n success: bool = True\n for attribute in attributes:\n if attribute not in self._subscriber:\n LOGGER.debug(f\"{attribute} is not an subscribable attribute of {self.__class__.__name__}: \"\n f\"not unsubscribed\")\n success = False\n continue\n if attribute in self._subscriber and subscriber not in self._subscriber[attribute]:\n LOGGER.debug(f\"{subscriber.id} has not subscribed to {self.__class__.__name__}.{attribute}\")\n success = False\n continue\n self._subscriber[attribute].remove(subscriber)\n return success\n\n def unsubscribe_all(self, subscriber_id: str) -> bool:\n \"\"\"\n Unsubscribes the notification from all attributes the subscriber with the provided [subscriber_id] listens on\n :param subscriber_id: the identifier of the subscriber\n :return: bool of success. Could be False due no valid subscriptions.\n \"\"\"\n success: bool = False\n subscriber = self._get_subscriber(subscriber_id)\n for attribute in self._subscriber.keys():\n if subscriber in self._subscriber[attribute]:\n self._subscriber[attribute].remove(subscriber)\n success = True\n return success\n\n def _get_subscriber(self, subscriber_id: str) -> Optional[Subscriber]:\n all_subscribers = set()\n for subscriber_list in self._subscriber.values():\n all_subscribers.update(subscriber_list)\n\n for subscriber in all_subscribers:\n if subscriber.id == subscriber_id:\n return subscriber\n","sub_path":"utils/StateManager.py","file_name":"StateManager.py","file_ext":"py","file_size_in_byte":11300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"237894705","text":"def maxProduct(arr,n):\n if n < 2:\n print(\"No pairs exist...\")\n return\n if n == 2:\n print(\"str(arr[0]),str(arr[1])\")\n\t#initialize minimum and maximum values\n max_a = max_b = min_a = min_b = 0\n\t#update max and min values\n for i in range(n):\n if arr[i] > max_a:\n max_b = max_a\n max_a = arr[i]\n elif arr[i] > max_b:\n max_b = arr[i]\n\n if arr[i]<0 and abs(arr[i]) > abs(min_a):\n min_b = min_a\n min_a = arr[i]\n elif arr[i]<0 and abs(arr[i]>abs(min_b)):\n min_b=arr[i]\n\n\t# check maximum product\n if min_a*min_b > max_a*max_b:\n print(\"Max product is {\" + str(min_a*min_b) + \"} and pair is {\" + str(min_a) + \", \" + str(min_b) + \"}\")\n else:\n print(\"Max product is {\" + str(max_a*max_b) + \"} and pair is {\" + str(max_a) + \", \" + str(max_b) + \"}\")\n\n\narr = [9, -7, 3, 6, -2, 0, 4, -8]\nn = len(arr)\nmaxProduct(arr, n)\n","sub_path":"code/python/day-8/Max Product Pair.py","file_name":"Max Product Pair.py","file_ext":"py","file_size_in_byte":949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"322548257","text":"import pydeck as pdk\n\nH3_VERSION = \"~3.7.*\"\nPYDECK_VERSION = \"~8.8.*\"\n\nLIBRARIES_TO_INCLUDE = [\n f\"npm/h3-js@{H3_VERSION}/dist/h3-js.umd.js\",\n f\"npm/@deck.gl/extensions@{PYDECK_VERSION}/dist.min.js\",\n f\"npm/@deck.gl/carto@{PYDECK_VERSION}/dist.min.js\",\n]\nSELECTED_LIBRARIES = \",\".join(LIBRARIES_TO_INCLUDE)\nCARTO_LAYER_BUNDLE_URL = f\"https://cdn.jsdelivr.net/combine/{SELECTED_LIBRARIES}\"\n\n\nclass MapType:\n QUERY = pdk.types.String(\"query\")\n TABLE = pdk.types.String(\"table\")\n TILESET = pdk.types.String(\"tileset\")\n\n\nclass CartoConnection:\n CARTO_DW = pdk.types.String(\"carto_dw\")\n\n\nclass GeoColumnType:\n H3 = pdk.types.String(\"h3\")\n QUADBIN = pdk.types.String(\"quadbin\")\n\n\ndef register_carto_layer():\n \"\"\"Add CartoLayer JS bundle to pydeck\"s custom libraries.\"\"\"\n library_name = \"CartoLayerLibrary\"\n custom_library = {\n \"libraryName\": library_name,\n \"resourceUri\": CARTO_LAYER_BUNDLE_URL,\n }\n\n if pdk.settings.custom_libraries is None:\n pdk.settings.custom_libraries = [custom_library]\n return\n\n exists = any(\n [x.get(\"libraryName\") == library_name for x in pdk.settings.custom_libraries]\n )\n\n if not exists:\n pdk.settings.custom_libraries.append(custom_library)\n","sub_path":"bindings/pydeck-carto/pydeck_carto/layer.py","file_name":"layer.py","file_ext":"py","file_size_in_byte":1257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"179193249","text":"#!/usr/bin/env python3\n\nfrom pybytom.exceptions import NetworkError, BalanceError, APIError, \\\n AddressError, InvalidURLError, ClientError, NotFoundError\n\nimport pytest\n\n\ndef exceptions(error=\"\"):\n if error == \"network\":\n raise NetworkError(\"Invalid network type.\")\n elif error == \"network_detail\":\n raise NetworkError(\"Invalid network type.\", \"testnet\")\n elif error == \"balance\":\n raise BalanceError(\"0\")\n elif error == \"balance_detail\":\n raise BalanceError(\"0\", \"you don't enough coin\")\n elif error == \"api\":\n raise APIError(\"Server error.\")\n elif error == \"api_detail\":\n raise APIError(\"Server error.\", \"connection loss..\")\n elif error == \"address\":\n raise AddressError(\"Invalid bitcoin mainnet address.\")\n elif error == \"address_detail\":\n raise AddressError(\"Invalid bitcoin mainnet address.\", \"2N3NKQpymf1KunR4W8BpZjs8za5La5pV5hF\")\n elif error == \"url\":\n raise InvalidURLError(\"Invalid URL address.\")\n elif error == \"client\":\n raise ClientError(\"Invalid transaction raw.\")\n elif error == \"client_detail\":\n raise ClientError(\"Invalid transaction raw.\", \"--raw enasdsarue5kj5435345...\")\n elif error == \"not_found\":\n raise NotFoundError(\"Not Found.\")\n\n\ndef test_exceptions():\n with pytest.raises(NetworkError, match=r\".* network .*\"):\n exceptions(\"network\")\n with pytest.raises(NetworkError, match=r\".* network .*, testnet\"):\n exceptions(\"network_detail\")\n with pytest.raises(BalanceError, match=\"0\"):\n exceptions(\"balance\")\n with pytest.raises(BalanceError, match=\"0, you don't enough coin\"):\n exceptions(\"balance_detail\")\n with pytest.raises(APIError, match=r\".*.\"):\n exceptions(\"api\")\n with pytest.raises(APIError, match=r\".*.\"):\n exceptions(\"api_detail\")\n with pytest.raises(AddressError, match=\"Invalid bitcoin mainnet address.\"):\n exceptions(\"address\")\n with pytest.raises(AddressError, match=\"Invalid bitcoin mainnet address., 2N3NKQpymf1KunR4W8BpZjs8za5La5pV5hF\"):\n exceptions(\"address_detail\")\n with pytest.raises(InvalidURLError, match=\".* URL .*\"):\n exceptions(\"url\")\n with pytest.raises(ClientError, match=\"Invalid transaction raw.\"):\n exceptions(\"client\")\n with pytest.raises(ClientError, match=\"--raw enasdsarue5kj5435345...\"):\n exceptions(\"client_detail\", )\n with pytest.raises(NotFoundError, match=\"Not Found.\"):\n exceptions(\"not_found\")\n","sub_path":"tests/pybytom/test_exceptions.py","file_name":"test_exceptions.py","file_ext":"py","file_size_in_byte":2499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"431881839","text":"import math\n\ns, p = map(int, input().split())\nfound = False\nfor i in range(int(math.sqrt(p))):\n if p % (i + 1) == 0:\n if p // (i + 1) + i + 1 == s:\n found = True\n break\n\nif found:\n print(\"Yes\")\nelse:\n print(\"No\")\n","sub_path":"ARC_from101to200/ARC108/a.py","file_name":"a.py","file_ext":"py","file_size_in_byte":251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"36041944","text":"import glob\nimport re\nimport shlex\nimport struct\n\nfrom geoip2.database import Reader as GeoIPReader\nfrom geoip2.errors import AddressNotFoundError\n\n\n# assumes to find a GeoLite2 database in the current working directory\ngeoip_reader = GeoIPReader(glob.glob(\"GeoLite2-*.mmdb\")[0])\n\n\nclass Cube2BytesStream:\n\n # copied from src/shared/cube2font.c\n CUBE2UNICHARS = [\n 0, 192, 193, 194, 195, 196, 197, 198, 199, 9, 10, 11, 12, 13, 200,\n 201, 202, 203, 204, 205, 206, 207, 209, 210, 211, 212, 213, 214, 216,\n 217, 218, 219, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45,\n 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62,\n 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,\n 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96,\n 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110,\n 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124,\n 125, 126, 220, 221, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232,\n 234, 235, 236, 237, 238, 239, 241, 242, 243, 244, 245, 246, 233, 248,\n 249, 250, 251, 252, 253, 255, 0x104, 0x105, 0x106, 0x107, 0x10C,\n 0x10D, 0x10E, 0x10F, 0x118, 0x119, 0x11A, 0x11B, 0x11E, 0x11F, 0x130,\n 0x131, 0x141, 0x142, 0x143, 0x144, 0x147, 0x148, 0x150, 0x151, 0x152,\n 0x153, 0x158, 0x159, 0x15A, 0x15B, 0x15E, 0x15F, 0x160, 0x161, 0x164,\n 0x165, 0x16E, 0x16F, 0x170, 0x171, 0x178, 0x179, 0x17A, 0x17B, 0x17C,\n 0x17D, 0x17E, 0x404, 0x411, 0x413, 0x414, 0x416, 0x417, 0x418, 0x419,\n 0x41B, 0x41F, 0x423, 0x424, 0x426, 0x427, 0x428, 0x429, 0x42A, 0x42B,\n 0x42C, 0x42D, 0x42E, 0x42F, 0x431, 0x432, 0x433, 0x434, 0x436, 0x437,\n 0x438, 0x439, 0x43A, 0x43B, 0x43C, 0x43D, 0x43F, 0x442, 0x444, 0x446,\n 0x447, 0x448, 0x449, 0x44A, 0x44B, 0x44C, 0x44D, 0x44E, 0x44F, 0x454,\n 0x490, 0x491\n ]\n\n def __init__(self, data, offset):\n self.data = data\n self.offset = offset\n\n # see getint in src/shared/tools.cpp\n def next_int(self):\n next_int = struct.unpack(b\" 0:\n rv.append(chr(self.CUBE2UNICHARS[char]))\n self.offset += 1\n char = getchar()\n\n self.offset += 1\n\n return \"\".join(rv)\n\n\nclass Server:\n # see src/game/gamemode.h\n MUTATORS = {\n \"multi\": 1 << 0,\n \"ffa\": 1 << 1,\n \"coop\": 1 << 2,\n \"insta\": 1 << 3,\n \"medieval\": 1 << 4,\n \"kaboom\": 1 << 5,\n \"duel\": 1 << 6,\n \"survivor\": 1 << 7,\n \"classic\": 1 << 8,\n \"onslaught\": 1 << 9,\n \"freestyle\": 1 << 10,\n \"vampire\": 1 << 11,\n \"resize\": 1 << 12,\n \"hard\": 1 << 13,\n \"basic\": 1 << 14,\n # game specific mutators\n \"gsp1\": 1 << 15,\n \"gsp2\": 1 << 16,\n \"gsp3\": 1 << 17,\n }\n\n # more descriptive than \"gsp1\", \"gsp2\" or \"gsp3\"\n GSP_MUTATORS = {\n \"deathmatch\": [\"gladiator\", \"oldschool\"],\n \"capture-the-flag\": [\"quick\", \"defend\", \"protect\"],\n \"defend-and-control\": [\"quick\", \"king\"],\n \"bomber-ball\": [\"hold\", \"basket\", \"attack\"],\n \"race\": [\"timed\", \"endurance\", \"gauntlet\"],\n }\n\n # see src/game/game.h\n MASTERMODES = [\n \"open\",\n \"veto\",\n \"locked\",\n \"private\",\n \"password\",\n ]\n\n # see src/game/gamemode.h\n GAMEMODES = [\n \"demo\",\n \"edit\",\n \"deathmatch\",\n \"capture-the-flag\",\n \"defend-and-control\",\n \"bomber-ball\",\n \"race\",\n ]\n\n def __init__(self, ip_address, port, priority, flags):\n self.hostname = ip_address\n self.port = port\n self.priority = priority\n self.flags = flags\n\n try:\n self.country = geoip_reader.country(ip_address).country.iso_code\n except (AttributeError, AddressNotFoundError):\n self.country = None\n\n # Will be added later as soon as the data is fetched from the server\n # itself\n # see queryreply in src/game/server.cpp\n\n # integers inside queryreply data\n self.players_count = None\n self.fifteen = None\n self.protocol = None\n self.game_mode = None\n self.mutators = None\n self.time_remaining = None\n self.max_slots = None\n self.mastermode = None\n self.number_of_game_vars = None\n self.modification_percentage = None\n self.version = (None, None, None)\n self.version_platform = None\n self.version_arch = None\n self.game_state = None\n self.time_left = None\n\n # strings inside queryreply data\n self.map_name = None\n self.description = None\n\n # players are appended to the queryresponse and thus the last part\n self.players = None\n\n def parse_query_reply(self, query_reply):\n # Skip first 5 bytes as they are equal to the bytes sent as request\n stream = Cube2BytesStream(query_reply, 5)\n\n self.players_count = stream.next_int()\n\n # some constant, whyever they put it there o_O\n self.fifteen = stream.next_int()\n\n self.protocol = stream.next_int()\n self.game_mode = self.GAMEMODES[stream.next_int()]\n\n mutators = stream.next_int()\n self.mutators = [k for k, v in self.MUTATORS.items() if v & mutators]\n for i, gsp in enumerate([\"gsp1\", \"gsp2\", \"gsp3\"]):\n if gsp in self.mutators:\n gsp_description = self.GSP_MUTATORS[self.game_mode][i]\n self.mutators[self.mutators.index(gsp)] = gsp_description\n\n self.time_remaining = stream.next_int()\n self.max_slots = stream.next_int()\n self.mastermode = self.MASTERMODES[stream.next_int()]\n self.modification_percentage = stream.next_int()\n self.number_of_game_vars = stream.next_int()\n self.version = (stream.next_int(),\n stream.next_int(),\n stream.next_int())\n self.version_platform = stream.next_int()\n self.version_arch = stream.next_int()\n self.game_state = stream.next_int()\n self.time_left = stream.next_int()\n\n self.map_name = stream.next_string()\n self.description = stream.next_string()\n\n # quick fix to make redflare-python work with 1.5.5 release\n if self.version[:2] == (1, 5) and self.version[2] > 3:\n # throw away some irrelevant string that has been added after\n # the description in 1.5.5 release\n stream.next_string()\n\n self.players = []\n\n for i in range(self.players_count):\n player = stream.next_string()\n parts = player.split(\"\\f\")\n team_color, name = re.match(\"\\[([0-9]+)\\](.*)\", parts[4]).groups()\n\n self.players.append({\n \"color\": \"#\" + hex(int(parts[2].strip(\"[]\")))[2:].zfill(6),\n \"privilege\": parts[3].strip(\"($)\")[4:-3],\n \"team_color\": \"#\" + hex(int(team_color))[2:].zfill(6),\n \"name\": name,\n })\n\n for player in self.players:\n account = stream.next_string().strip()\n\n if len(account) == 0:\n account = None\n\n player[\"account\"] = account\n\n self.players.sort(key=lambda p: p[\"name\"].lower())\n\n # fallback if the server sends an empty description\n if not self.description.strip():\n self.description = \"{}:[{}]\".format(self.hostname, self.port)\n\n @staticmethod\n def from_addserver_line(data):\n parts = shlex.split(data)\n\n hostname = parts[1]\n port = int(parts[2])\n priority = int(parts[3])\n flags = list(parts[-2])\n\n return Server(hostname, port, priority, flags)\n\n def to_dict(self):\n return {\n \"hostname\": self.hostname,\n \"port\": self.port,\n \"priority\": self.priority,\n \"flags\": self.flags,\n \"country\": self.country,\n \"players_count\": self.players_count,\n \"fifteen\": self.fifteen,\n \"protocol\": self.protocol,\n \"game_mode\": self.game_mode,\n \"mutators\": self.mutators,\n \"time_remaining\": self.time_remaining,\n \"max_slots\": self.max_slots,\n \"mastermode\": self.mastermode,\n \"modification_percentage\": self.modification_percentage,\n \"number_of_game_vars\": self.number_of_game_vars,\n \"version\": \".\".join((str(v) for v in self.version)),\n \"version_platform\": self.version_platform,\n \"version_arch\": self.version_arch,\n \"game_state\": self.game_state,\n \"time_left\": self.time_left,\n \"map_name\": self.map_name,\n \"description\": self.description,\n \"players\": self.players,\n }\n\n def __repr__(self):\n return \"\".format(self.hostname, self.port)\n","sub_path":"redflare/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":9600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"14028","text":"#!/usr/bin/env python3\n\nimport os\nimport copy\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.python.client import device_lib\nfrom tqdm import tqdm\n\nfrom . import dataset\nfrom . import network\n\n\ndef _distribute_megabatch(classes, input_ops, output_ops, batches):\n\n # We are building up a feed_dict to pass in and an op to execute\n feed_dict = {}\n op = {}\n\n # Loop through the classes\n for i, c in enumerate(classes):\n\n # Work out which GPU we want to run this class on\n gpu_no = i % len(input_ops)\n\n # Set up our inputs and outputs for this class on this gpu\n feed_dict[input_ops[gpu_no][c[0]]['X']] = np.concatenate([m[c[0]]['X'] for m in batches], axis=0)\n feed_dict[input_ops[gpu_no][c[0]]['c']] = np.concatenate([m[c[0]]['c'] for m in batches], axis=0)\n op[c[0]] = {'X': output_ops[gpu_no][c[0]]['X'], 'c': output_ops[gpu_no][c[0]]['c']}\n\n return op, feed_dict\n\n\ndef _reduce_histogram_batch(X, c, num_bins):\n\n # Sort by confidence\n idx = tf.argsort(X)\n X = tf.gather(X, idx)\n c = tf.gather(c, idx)\n\n # Calculate precision and recall for all confidence thresholds\n thresholded = tf.cumsum(c, reverse=True, axis=0)\n p = tf.reduce_sum(c[:, 0], axis=0)\n precision = tf.divide(thresholded[:, 0], tf.add(thresholded[:, 0], thresholded[:, 1]))\n recall = tf.divide(thresholded[:, 0], p)\n\n # Calculate the distance along the PR curve for each point so we can sample evenly along the PR curve\n curve = tf.sqrt(\n tf.add(tf.squared_difference(precision[:-1], precision[1:]), tf.squared_difference(recall[:-1], recall[1:]))\n )\n curve = tf.pad(tf.cumsum(curve), [[1, 0]]) # First point is 0 length along the curve\n\n # Use cumsum and scatter to try to distribute points as evenly along the PR curve as we can\n idx = tf.cast(tf.expand_dims(tf.multiply(curve, tf.divide(num_bins, curve[-1])), axis=-1), dtype=tf.int32)\n idx = tf.clip_by_value(idx, 0, num_bins - 1)\n values = tf.reduce_sum(c, axis=-1)\n h_X = tf.scatter_nd(idx, tf.multiply(X, values), [num_bins]) # Scale by values in bin\n h_c = tf.scatter_nd(idx, c, [num_bins, 2])\n h_X = tf.divide(h_X, tf.reduce_sum(h_c, axis=-1)) # Renormalise by values in bin\n\n # Remove any points from the histogram that didn't end up getting values\n idx = tf.squeeze(tf.where(tf.logical_not(tf.is_nan(h_X))), axis=-1)\n h_X = tf.gather(h_X, idx)\n h_c = tf.gather(h_c, idx)\n\n # If we don't have enough values to make up the bins, just return the values themselves\n X = tf.cond(tf.size(X) < num_bins, lambda: X, lambda: h_X)\n c = tf.cond(tf.size(c) < num_bins, lambda: c, lambda: h_c)\n\n return X, c\n\n\ndef _build_device_testing_graph(data, network_structure, config, device_no):\n\n # Create the network graph ops for this device\n with tf.variable_scope(\"Network\"):\n X = network.build_network(data[\"X\"], data[\"G\"], network_structure, config.network.activation_fn)\n\n # Truth labels for the network\n Y = data[\"Y\"]\n\n # Use the alpha channel to strip points without labels\n W = data[\"W\"]\n S = tf.where(tf.greater(W, 0))\n X = tf.gather_nd(X, S)\n Y = tf.gather_nd(Y, S)\n\n # Softmax to get actual output\n X = tf.nn.softmax(X, axis=1)\n\n # True and false positives (assuming 1 and 0 for true/false)\n tp = Y\n fp = 1.0 - Y\n\n # Calculate the precision recall for each class individually\n ops = {}\n for i, c in enumerate(config.network.classes):\n\n # Get the values for this specific class and the true and false positives\n X_c = X[:, i]\n tpfp = tf.stack([tp[:, i], fp[:, i]], axis=-1)\n\n # Store our input tensors for later so we can override them as placeholders when we reduce a series of batches together\n inputs = {'X': X_c, 'c': tpfp}\n\n # Reduce these points down\n X_c, tpfp = _reduce_histogram_batch(X_c, tpfp, config.testing.num_bins)\n\n # Store our outputs\n outputs = {'X': X_c, 'c': tpfp}\n\n # For the ops for this particular class\n ops[c[0]] = {'inputs': inputs, 'outputs': outputs}\n\n return ops\n\n\ndef _build_testing_graph(gpus, config):\n\n with tf.device(\"/device:CPU:0\"):\n iterator = (\n dataset.VisualMeshDataset(\n input_files=config.dataset.testing,\n classes=config.network.classes,\n geometry=config.geometry,\n batch_size=max(1, config.testing.batch_size),\n prefetch=tf.data.experimental.AUTOTUNE,\n variants={},\n ).build().make_one_shot_iterator()\n )\n\n # Calculate the structure for the network and the tutor\n network_structure = copy.deepcopy(config.network.structure)\n network_structure[-1].append(len(config.network.classes))\n\n # For each GPU build a classification network, a tutor network and a gradients calculator\n device_ops = []\n for i, gpu in enumerate(gpus):\n with tf.device(gpu), tf.name_scope(\"Tower_{}\".format(i)):\n device_ops.append(_build_device_testing_graph(iterator.get_next(), network_structure, config, i))\n\n return device_ops\n\n\n# Train the network\ndef test(config, output_path):\n\n # Find the GPUs we have available and if we don't have any, fallback to CPU\n gpus = [x.name for x in device_lib.list_local_devices() if x.device_type == \"GPU\"]\n gpus = [\"/device:CPU:0\"] if len(gpus) == 0 else gpus\n\n # Build the training graph operations we need\n ops = _build_testing_graph(gpus, config)\n\n # Split our ops into input and output ops for each device\n input_ops = [{k: v['inputs'] for k, v in d.items()} for d in ops]\n output_ops = [{k: v['outputs'] for k, v in d.items()} for d in ops]\n\n # Tensorflow configuration\n tf_config = tf.ConfigProto()\n tf_config.allow_soft_placement = False\n tf_config.gpu_options.allow_growth = True\n\n with tf.Session(config=tf_config) as sess:\n # Initialise global variables\n sess.run(tf.global_variables_initializer())\n\n save_vars = {v.name: v for v in tf.trainable_variables()}\n saver = tf.train.Saver(save_vars)\n\n # Get our model directory and load it\n checkpoint_file = tf.train.latest_checkpoint(output_path)\n print(\"Loading model {}\".format(checkpoint_file))\n saver.restore(sess, checkpoint_file)\n\n # Count how many files are in the test dataset so we can show a progress bar\n # This is slow, but the progress bar is comforting\n print(\"Counting records in test dataset\")\n num_records = sum(1 for _ in tf.python_io.tf_record_iterator(config.dataset.testing))\n num_batches = num_records // max(1, config.testing.batch_size)\n print(\"Loading {} records in {} batches\".format(num_records, num_batches))\n\n # Process the results in batches, reducing the number of points down for tp and fp\n batches = []\n with tqdm(total=num_records // max(1, config.testing.batch_size), dynamic_ncols=True, unit='batch') as progress:\n try:\n while num_batches - len(batches) > 0:\n # Accumulate our individual batches\n batch = sess.run(output_ops[0:min(num_batches - len(batches), len(output_ops))])\n batches.extend(batch)\n progress.update(len(batch))\n\n except tf.errors.OutOfRangeError:\n print('Loaded into {} batches'.format(len(batches)))\n\n # Feed the megabatches and batches together into a merger\n op, feed_dict = _distribute_megabatch(config.network.classes, input_ops, output_ops, batches)\n hist = sess.run(op, feed_dict=feed_dict)\n\n # Process each class into a PR curve and save\n print('Processing PR curves')\n os.makedirs(os.path.join(output_path, 'test'), exist_ok=True)\n aps = []\n for k, data in tqdm(hist.items(), dynamic_ncols=True, unit='class'):\n\n # Concatenate the histogram thresholds into a set\n X = data['X']\n tpfp = data['c']\n p = np.sum(tpfp[:, 0])\n\n # Sort by threshold\n idx = np.argsort(X)\n X = X[idx]\n tpfp = tpfp[idx]\n\n # This is the precision when all points are selected (used for recall = 1 endpoint)\n all_points_precision = tpfp[:, 0].sum() / (tpfp[:, 0].sum() + tpfp[:, 1].sum())\n\n # Cumulative sum to calculate tp and fp for each threshold\n tp = np.cumsum(tpfp[::-1, 0], dtype=np.int64)[::-1]\n fp = np.cumsum(tpfp[::-1, 1], dtype=np.int64)[::-1]\n\n # Calculate precision and recall\n precision = np.true_divide(tp, (tp + fp))\n recall = np.true_divide(tp, p)\n\n # Add on the ends of the plot to make it cleaner and make the AP more accurate\n X = np.concatenate((X, [1.0]))\n precision = np.concatenate((precision, [1.0]))\n recall = np.concatenate((recall, [0.0]))\n if recall.max() < 1.0:\n X = np.concatenate((X, [0.0]))\n precision = np.concatenate((precision, [all_points_precision]))\n recall = np.concatenate((recall, [1.0]))\n\n # Sort by recall\n idx = np.argsort(recall)\n X = X[idx]\n precision = precision[idx]\n recall = recall[idx]\n\n # Calculate the average precision using this curve\n ap = np.trapz(precision, recall)\n\n # Add this average precision to the summary\n aps.append((k.title(), ap))\n\n # Save the PR curve\n np.savetxt(\n os.path.join(output_path, 'test', '{}_pr.csv'.format(k)),\n np.stack([X, recall, precision], axis=-1),\n comments=\"\",\n header=\"Confidence,Recall,Precision\",\n delimiter=\",\",\n )\n\n # Write out the mAP and ap for each class\n with open(os.path.join(output_path, 'test', 'pr.txt'), 'w') as pr_f:\n # Mean average precision\n mAP = sum([a[1] for a in aps]) / len(aps)\n print('mAP: {}'.format(mAP))\n pr_f.write('mAP: {}\\n'.format(mAP))\n\n # Individual precisions\n for k, ap in aps:\n print('\\t{}: {}'.format(k, ap))\n pr_f.write('\\t{}: {}\\n'.format(k, ap))\n","sub_path":"training/testing.py","file_name":"testing.py","file_ext":"py","file_size_in_byte":9560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"647741292","text":"from regolith.tools import filter_publications\nfrom regolith.tools import fuzzy_retrieval\n\n\ndef test_author_publications():\n citations = [{'author': ['CJ', 'SJLB']}, {'editor': 'SJLB'}]\n filter_publications(citations, {'SJLB'})\n\n\ndef test_fuzzy_retrieval():\n person = {'_id': 'scopatz',\n 'aka': ['Scopatz',\n 'Scopatz, A',\n 'Scopatz, A.',\n 'Scopatz, A M',\n 'Anthony Michael Scopatz'],\n 'name': 'Anthony Scopatz'}\n assert fuzzy_retrieval([person], ['aka', 'name', '_id'],\n 'scopatz') == person\n","sub_path":"tests/test_tools.py","file_name":"test_tools.py","file_ext":"py","file_size_in_byte":640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"585950958","text":"from configs import config\n\n\nimport datetime\n\nkey = {\n 'question-ask-self_user' : {\n 'title': 'Somebody asked you a question',\n 'text': \" asked you ''\",\n 'url': config.WEB_URL + '/q/%s',\n 'label_one': 'Answer',\n 'label_two': 'Later',\n 'day_limit': 2\n\n },\n 'post-add-self_user': {\n 'title': 'Your question got answered!',\n 'text': \" answered your question \",\n 'url': config.WEB_URL + '/p/%s',\n 'day_limit': 3,\n 'label_one': 'Play',\n 'label_two': ''\n },\n 'post-add-following_user': {\n 'title': 'New answer!',\n 'text': ''' answered the question ''',\n 'url': config.WEB_URL + '/p/%s',\n 'day_limit': 1,\n 'label_one': 'Play',\n 'label_two':''\n },\n 'comment-add-self_post':{\n 'title': 'New comment',\n 'text': '',\n 'url': config.WEB_URL + '/p/%s/comments',\n 'day-limit': 1,\n 'label_one':'',\n 'label_two': ''\n },\n 'new-celebrity-followed_category': {\n 'title':'New celebrity on Frankly',\n 'text': ''' has just joined Frankly. Ask him anything.''',\n 'url': config.WEB_URL + '/%s',\n 'day-limit': 1,\n 'label_one': 'Ask Now',\n 'label_two': 'Later'\n },\n 'popular-question-self_user': {\n 'title':'',\n 'text': '''Your question \"\" has received + upvotes. Share it to get more upvotes.''',\n 'url': config.WEB_URL + '/q/%s',\n 'day-limit': 1,\n 'label_one':'',\n 'label_two': ''\n },\n 'user-followers-milestone': {\n 'title':'You are getting noticed.',\n 'text': 'You just got your th follower. Get more by sharing your profile.',\n 'url': config.WEB_URL + '/%s',\n 'day-limit': 1,\n 'label_one':'',\n 'label_two': ''\n },\n 'post-likes-milestone': {\n 'title':'Your answer is becoming popular.',\n 'text': 'Your answer has crossed over likes. Share it to become popular.',\n 'url': config.WEB_URL + '/p/%s',\n 'day-limit': 1,\n 'label_one':'',\n 'label_two': ''\n\n },\n 'intro-video-request':{\n 'title': 'You are in demand!',\n 'text': ' just asked you for an intro video.',\n 'url': config.WEB_URL + '/u/%s',\n 'day-limit': 1,\n 'label_one':'',\n 'label_two': ''\n }\n}\n\n\ndef question_asked_text(question,question_author,question_to):\n text = key['question-ask-self_user']['text']\n if question.is_anonymous:\n text = text.replace('', 'Anonymous')\n else:\n text = text.replace('', question_author)\n text = text.replace('', question.body)\n text = text.replace('', question_to)\n\n return text\n\ndef post_add(answer_author, question_body):\n text = key['post-add-self_user']['text']\n text = text.replace('', answer_author)\n text = text.replace('', question_body)\n return text\n\ndef popular_question_text(question_body, upvote_count):\n text = key['popular-question-self_user']['text']\n return text.replace('', question_body).replace('', str(((upvote_count/10)*10)))\n\ndef following_answered_question(author_name, question_body):\n text = key['post-add-following_user']['text']\n return text.replace('', author_name).replace('', question_body)\n\ndef milestone_text(milestone_name, milestone_count):\n text = key[milestone_name]['text']\n return text.replace('',milestone_count)\n\ndef user_profile_request(requester_name):\n text = key['intro-video-request']['text']\n return text.replace('', requester_name)\n\nmilestones = {\n 'user-followers-milestone':[100, 200, 500, 1000, 5000, 10000, 20000, 50000, 1000000, 10000000],\n 'post-likes-milestone': [100, 200, 500, 1000, 5000, 10000, 20000, 50000, 1000000, 10000000],\n 'upvotes': [100, 200, 500, 1000, 5000, 10000, 20000, 50000, 1000000, 10000000],\n 'profile_views': [100, 200, 500, 1000, 5000, 10000, 20000, 50000, 1000000, 10000000],\n 'post_views':[100, 200, 500, 1000, 5000, 10000, 20000, 50000, 1000000, 10000000]\n\n}","sub_path":"franklyapi/notification/commons/helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":4475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"631947038","text":"import pickle\nimport os\nimport pymarc\nimport re\nfrom nltk.tokenize import word_tokenize\n# This document extract titles from norart, loads the titles from idunn from a pickle dump, and tries to create meta data for any correct matches that has been found. \n\ndef create_norart_titles():\n titles=[]\n regex = re.compile('[^a-zA-Z1234567890øæåØÆÅ ]')\n filename = \"norart20180108.xml\"\n print(\"Loading XML-records. Please wait\")\n p=pymarc.marcxml.parse_xml_to_array(filename, strict=False, normalize_form=None)\n print(\"Loading Complete\")\n count=0\n print(\"Starting scanning\")\n for record in p:\n if \"082\" in record and \"856\" in record:\n tittel = record[\"245\"]['a']\n undertittel = \"\"\n if \"b\" in record[\"245\"]:\n undertittel = record[\"245\"]['b']\n tidsskrift = \"\"\n year = \"\"\n if \"773\" in record:\n if \"t\" in record[\"773\"]:\n tidsskrift = record[\"773\"][\"t\"]\n if \"i\" in record[\"773\"]:\n year = record[\"773\"][\"i\"]\n dewey = record[\"082\"][\"a\"]\n kategori = str(dewey[:3])\n keyword=\"\"\n if \"650\" in record:\n keyword = record[\"650\"][\"a\"]\n tittel=tittel+\" \"+ undertittel\n tittel=tittel.lower()\n tittel = regex.sub(\"\", tittel)\n tokenized_tittel = word_tokenize(tittel, language=\"norwegian\")\n tittel = \" \".join(tokenized_tittel)\n titles.append(tittel)\n print(count)\n count+=1\n\n\n print(len(titles))\n with open('title_torstein.pickle', 'wb') as f:\n pickle.dump(titles,f)\n\n\ndef write_to_file_meta(tittel,undertittel,year,tidsskrift, dewey,keyword,filnavn, folder):\n print(\"Sucessfully writing to file\")\n with open(folder + \"/meta-\" + filnavn + \".txt\", \"w\") as d:\n\n d.write(\"tittel:::\" + str(tittel) + \"\\n\")\n d.write(\"undertittel:::\" + str(undertittel) + \"\\n\")\n d.write(\"dewey:::\" + str(dewey) + \"\\n\")\n d.write(\"keyword:::\" + str(keyword) + \"\\n\")\n d.write(\"tidsskrift:::\" + str(tidsskrift) + \"\\n\")\n d.write(\"year:::\" + str(year) + \"\\n\")\n d.write(\"idunn:::yes\"+\"\\n\")\n\ndef write_to_file_text(text,filnavn,folder):\n with open(folder + \"/\" + filnavn + \".txt\", \"w\") as d:\n d.write(text)\n\n# create_norart_titles()\n# exit(0)\nwith open(\"idunn_to_norart.pickle\",\"rb\") as f:\n idunn_to_norart=pickle.load(f)\nwith open(\"norart_to_idunn.pickle\",\"rb\") as f:\n norart_to_idunn=pickle.load(f)\nwith open(\"title_texts.pickle\",\"rb\") as f:\n title_texts=pickle.load(f)\n\nunmatched_norart={}\n\n\nfolder=\"documents\"\nregex = re.compile('[^a-zA-Z1234567890øæåØÆÅ ]')\nfilename = \"norart20180108.xml\"\nprint(\"Loading XML-records. Please wait\")\np=pymarc.marcxml.parse_xml_to_array(filename, strict=False, normalize_form=None)\nprint(\"Loading Complete\")\ncount=0\nprint(\"Starting scanning\")\ncount=0\nfor record in p:\n if \"082\" in record and \"856\" in record:\n tittel = record[\"245\"]['a']\n print(count)\n count += 1\n original_tittel=tittel\n undertittel = \"\"\n if \"b\" in record[\"245\"]:\n undertittel = record[\"245\"]['b']\n tidsskrift = \"\"\n year = \"\"\n if \"773\" in record:\n if \"t\" in record[\"773\"]:\n tidsskrift = record[\"773\"][\"t\"]\n if \"i\" in record[\"773\"]:\n year = record[\"773\"][\"i\"]\n dewey = record[\"082\"][\"a\"]\n kategori = str(dewey[:3])\n keyword=\"\"\n if \"650\" in record:\n keyword = record[\"650\"][\"a\"]\n tittel=tittel+\" \"+ undertittel\n tittel=tittel.lower()\n tittel = regex.sub(\"\", tittel)\n tokenized_tittel = word_tokenize(tittel, language=\"norwegian\")\n tittel = \" \".join(tokenized_tittel)\n text=\"\"\n if tittel in title_texts:\n text=title_texts[tittel]\n elif tittel in norart_to_idunn:\n text=title_texts[norart_to_idunn[tittel]]\n\n if text!=\"\":\n\n filnavn=\"\".join(tokenized_tittel)\n write_to_file_meta(original_tittel,undertittel,year,tidsskrift,dewey,keyword,filnavn,folder)\n write_to_file_text(text,filnavn,folder)\n pass\n if text==\"\":\n unmatched_norart[tittel]=original_tittel\nprint(len(unmatched_norart.keys()))\nwith open(\"unmatched_articles_norart.pickle\",\"wb\") as f:\n pickle.dump(unmatched_norart,f)\n","sub_path":"connect_idunn_data/connect_info.py","file_name":"connect_info.py","file_ext":"py","file_size_in_byte":4954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"413207498","text":"# -*- encoding: utf-8 -*-\n'''\n@File : test_login.py\n@Time : 2020/03/05 14:28:40\n@Author : peace_su\n@Version : 1.0\n@Contact : peace_su@163.com\n@WebSite : https://me.csdn.net/u010098760\n'''\n\n# here put the import lib\nimport sys\nimport os\ncurPath = os.path.abspath(os.path.dirname(__file__))\nrootPath = os.path.split(curPath)[0]\nsys.path.append(rootPath)\n\nimport pytest\nfrom util.LoggingUtil import LoggingUtil\nfrom pages.BasePage import BasePage\nfrom pages.WelcomePage import WelcomePage\nfrom pages.LoginPage import LoginPage\nfrom pages.MainPage import MainPage\nimport logging\nfrom appium import webdriver\nimport time\nimport allure\n\n\n@allure.feature('测试登录功能')\nclass Test_login(object):\n '''类注释\n 详细描述\n\n Attributes:\n 属性说明\n '''\n\n def setup_method(self, method):\n self.logging_util = LoggingUtil()\n self.logging_util.setup_logging()\n self.logger = logging.getLogger()\n desired_caps = {\n 'platformName': 'Android',\n # 'deviceName': '127.0.0.1:5554', # 手机设备名称,通过adb devices查看\n 'deviceName': '127.0.0.1:62001', # 手机设备名称,通过adb devices查看\n 'platformVersion': '5.1.1', # android系统的版本号\n 'appPackage': 'com.aiosign.dzonesign', # apk包名\n # apk的launcherActivity\n 'appActivity': 'com.aiosign.dzonesign.view.AppStartActivity',\n }\n self.logger.info('启动app')\n try:\n self.driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)\n time.sleep(3)\n self.base_page = BasePage(self.driver)\n self.welcome_page = WelcomePage(self.base_page)\n self.login_page = LoginPage(self.base_page)\n self.main_page = MainPage(self.base_page)\n except Exception:\n BasePage.get_screen('screen_shot/')\n\n def teardown_method(self, method):\n print(\"断开连接\")\n\n @allure.story('登录-用户不存在')\n def test_login_1(self):\n self.logger.info('开始测试test_login_1==================================')\n self.base_page.swipe_to_left()\n self.base_page.swipe_to_left()\n self.welcome_page.click_tiyan_button()\n self.welcome_page.click_login_button()\n self.login_page.input_username('15628811988')\n self.login_page.input_passwd('12345678')\n self.login_page.click_signin_button()\n res = self.base_page.is_toast_exist('用户不存在')\n assert res\n self.logger.info('测试结束=====================================')\n\n @allure.story('登录-账号或密码错误')\n def test_login_2(self):\n self.base_page.swipe_to_left()\n self.base_page.swipe_to_left()\n self.welcome_page.click_tiyan_button()\n self.welcome_page.click_login_button()\n self.login_page.input_username('123456')\n self.login_page.input_passwd('abc23')\n self.login_page.click_signin_button()\n res = self.base_page.is_toast_exist('账号或密码错误')\n assert res\n\n @allure.story('登录-正常')\n def test_right(self):\n self.logger.info('开始测试test_right=====================================')\n self.base_page.swipe_to_left()\n self.base_page.swipe_to_left()\n self.welcome_page.click_tiyan_button()\n self.welcome_page.click_login_button()\n self.login_page.input_username('123456')\n self.login_page.input_passwd('abcabc')\n self.login_page.click_signin_button()\n res = self.main_page.is_personal_center_button_exist()\n assert res\n # self.main_page.click_personal_center_button()\n # self.logger.info('测试完成')\n\n @allure.story('登录-未输入密码')\n def test_login_3(self):\n self.base_page.swipe_to_left()\n self.base_page.swipe_to_left()\n self.welcome_page.click_tiyan_button()\n self.welcome_page.click_login_button()\n self.login_page.input_username('123456')\n # self.login_page.input_passwd('')\n self.login_page.click_signin_button()\n res = self.base_page.is_toast_exist('请输入密码!')\n assert res\n\n @allure.story('登录-账号格式不正确')\n def test_login_4(self):\n self.base_page.swipe_to_left()\n self.base_page.swipe_to_left()\n self.welcome_page.click_tiyan_button()\n self.welcome_page.click_login_button()\n self.login_page.input_username('156288119')\n self.login_page.input_passwd('abcabc')\n self.login_page.click_signin_button()\n res = self.base_page.is_toast_exist('账号格式不正确(邮箱、信用代码、手机)')\n assert res\n\n @allure.story('登录-未输入账号')\n def test_login_5(self):\n self.base_page.swipe_to_left()\n self.base_page.swipe_to_left()\n self.welcome_page.click_tiyan_button()\n self.welcome_page.click_login_button()\n # self.login_page.input_username('')\n self.login_page.input_passwd('abcabc')\n self.login_page.click_signin_button()\n res = self.base_page.is_toast_exist('请输入账号!')\n assert res\n\n\nif __name__ == '__main__':\n pytest.main([\"--reruns\", \"3\", \"--reruns-delay\", \"2\", \"--alluredir\", \"result\"])","sub_path":"case/test_login.py","file_name":"test_login.py","file_ext":"py","file_size_in_byte":5327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"490247099","text":"import numba\nimport numpy as np\nfrom constants import *\n\n# sugar\n\n\n@numba.njit\ndef point(x, y, z):\n return np.array([x, y, z], dtype=np.float64)\n\n\n@numba.njit\ndef vec(x, y, z):\n return np.array([x, y, z], dtype=np.float64)\n\n\n@numba.njit\ndef unit(v):\n return v / np.linalg.norm(v)\n\n# fast primitives\n\n\nray_type = numba.deferred_type()\nnode_type = numba.deferred_type()\nbox_type = numba.deferred_type()\n\n\n@numba.experimental.jitclass([\n ('origin', numba.float64[3::1]),\n ('direction', numba.float64[3::1]),\n ('inv_direction', numba.float64[3::1]),\n ('sign', numba.uint8[3::1]),\n ('color', numba.float64[3::1]),\n ('local_color', numba.float64[3::1]),\n ('i', numba.int32),\n ('j', numba.int32),\n ('bounces', numba.int32),\n ('p', numba.float64),\n ('local_p', numba.float64),\n ('G', numba.float64),\n ('prev', numba.optional(ray_type)),\n ('normal', numba.float64[3::1]),\n ('material', numba.int64),\n ('hit_light', numba.boolean),\n])\nclass Ray:\n def __init__(self, origin, direction):\n # todo: I don't think any of these copies are necessary and i'd like to try removing them when otherwise stable\n self.origin = origin.copy()\n self.direction = direction.copy()\n self.inv_direction = 1 / self.direction\n self.sign = (self.inv_direction < 0).astype(np.uint8)\n self.color = WHITE.copy()\n self.local_color = WHITE.copy()\n self.i = 0\n self.j = 0\n self.bounces = 0\n self.p = 1\n self.local_p = 1\n self.G = 1\n self.prev = None\n self.normal = self.direction\n self.material = Material.SPECULAR.value\n self.hit_light = False\n\n\n@numba.experimental.jitclass([\n ('v0', numba.float64[3::1]),\n ('v1', numba.float64[3::1]),\n ('v2', numba.float64[3::1]),\n ('e1', numba.float64[3::1]),\n ('e2', numba.float64[3::1]),\n ('normal', numba.float64[3::1]),\n ('mins', numba.float64[3::1]),\n ('maxes', numba.float64[3::1]),\n ('color', numba.float64[3::1]),\n ('emitter', numba.boolean),\n ('material', numba.int64),\n ('surface_area', numba.float64)\n])\nclass Triangle:\n def __init__(self, v0, v1, v2, color=WHITE, emitter=False, material=Material.DIFFUSE.value):\n self.v0 = v0\n self.v1 = v1\n self.v2 = v2\n self.e1 = v1 - v0\n self.e2 = v2 - v0\n self.normal = unit(np.cross(self.e1, self.e2))\n self.mins = np.minimum(np.minimum(v0, v1), v2)\n self.maxes = np.maximum(np.maximum(v0, v1), v2)\n self.color = color.copy()\n self.emitter = emitter\n self.material = material\n e1_mag = np.linalg.norm(self.e1)\n e2_mag = np.linalg.norm(self.e2)\n cos_theta = np.dot(self.e1 / e1_mag, self.e2 / e2_mag)\n sin_theta = np.sqrt(1 - cos_theta * cos_theta)\n self.surface_area = np.abs(.5 * np.dot(self.e1, self.e2) * sin_theta)\n\n def sample_surface(self):\n r1 = np.random.random()\n r2 = np.random.random()\n u = 1 - np.sqrt(r1)\n v = np.sqrt(r1) * (1 - r2)\n w = r2 * np.sqrt(r1)\n return self.v0 * u + self.v1 * v + self.v2 * w\n\n\n@numba.experimental.jitclass([\n ('min', numba.float64[3::1]),\n ('max', numba.float64[3::1]),\n ('bounds', numba.float64[:, ::1]),\n ('span', numba.float64[3::1]),\n ('left', numba.optional(box_type)),\n ('right', numba.optional(box_type)),\n ('triangles', numba.optional(numba.types.ListType(Triangle.class_type.instance_type))),\n ('lights', numba.optional(numba.types.ListType(Triangle.class_type.instance_type))),\n ('light_SA', numba.float64),\n])\nclass Box:\n def __init__(self, least_corner, most_corner, color=WHITE):\n self.min = least_corner\n self.max = most_corner\n self.bounds = np.stack((least_corner, most_corner))\n self.span = self.max - self.min\n self.left = None\n self.right = None\n self.triangles = None\n self.lights = None\n self.light_SA = 0\n\n def contains(self, point: numba.float64[3]):\n return (point >= self.min).all() and (point <= self.max).all()\n\n def extend(self, triangle: Triangle):\n self.min = np.minimum(triangle.mins, self.min)\n self.max = np.maximum(triangle.maxes, self.max)\n self.span = self.max - self.min\n self.bounds = np.stack((self.min, self.max))\n\n def surface_area(self):\n return 2 * (self.span[0] * self.span[1] + self.span[1] * self.span[2] + self.span[0] * self.span[2])\n\n\n@numba.experimental.jitclass([\n ('next', numba.optional(node_type)),\n ('data', box_type),\n])\nclass BoxStackNode:\n def __init__(self, data):\n self.data = data\n self.next = None\n\n\n@numba.experimental.jitclass([\n ('head', numba.optional(node_type)),\n ('size', numba.uint32)\n])\nclass BoxStack:\n def __init__(self):\n self.head = None\n self.size = 0\n\n def push(self, data):\n node = BoxStackNode(data)\n node.next = self.head\n self.head = node\n self.size += 1\n\n def pop(self):\n old = self.head\n if old is None:\n return None\n self.head = old.next\n self.size -= 1\n return old.data\n\n\n@numba.experimental.jitclass([\n ('ray', numba.optional(Ray.class_type.instance_type)),\n ('hit_light', numba.boolean),\n ('direction', numba.int64),\n])\nclass Path:\n # path is a stack of rays. methods on paths are currently in routines.py\n def __init__(self, ray, direction=Direction.FROM_CAMERA.value):\n self.ray = ray\n self.hit_light = False\n self.direction = direction\n\n\nnode_type.define(BoxStackNode.class_type.instance_type)\nbox_type.define(Box.class_type.instance_type)\nray_type.define(Ray.class_type.instance_type)\n","sub_path":"src/primitives.py","file_name":"primitives.py","file_ext":"py","file_size_in_byte":5748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"53707536","text":"from math import atan\nimport numpy as np\n\nclass YawController(object):\n def __init__(self, wheel_base, steer_ratio, min_speed, max_lat_accel, max_steer_angle, kp):\n self.wheel_base = wheel_base\n self.steer_ratio = steer_ratio\n self.min_speed = min_speed\n self.max_lat_accel = max_lat_accel\n\n self.min_angle = -max_steer_angle\n self.max_angle = max_steer_angle\n\n self.kp = kp\n\n\n def get_angle(self, radius):\n angle = atan(self.wheel_base / radius) * self.steer_ratio\n return max(self.min_angle, min(self.max_angle, angle))\n\n def get_steering(self, linear_velocity, angular_velocity, current_velocity):\n angular_velocity = current_velocity * angular_velocity / linear_velocity if abs(linear_velocity) > 0. else 0.\n\n if abs(current_velocity) > 0.1:\n max_yaw_rate = abs(self.max_lat_accel / current_velocity);\n angular_velocity = max(-max_yaw_rate, min(max_yaw_rate, angular_velocity))\n\n return self.get_angle(max(current_velocity, self.min_speed) / angular_velocity) if abs(angular_velocity) > 0. else 0.0;\n\n def get_steering_P(self, pose, p1, p2):\n # this use closest pt and second closest pt to form a line and calculate\n # offset of the current position and time kp\n # https://en.wikipedia.org/wiki/Distance_from_a_point_to_a_line\n d = np.cross(p2-p1, p1-pose) / np.linalg.norm(p2-p1)\n angle = self.kp * d\n return max(self.min_angle, min(self.max_angle, angle))\n","sub_path":"ros/src/twist_controller/yaw_controller.py","file_name":"yaw_controller.py","file_ext":"py","file_size_in_byte":1523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"619400944","text":"#!/usr/bin/python3\n\"\"\"Module to handle place restful API actions\"\"\"\n\nimport models\nfrom flask import Flask, jsonify, request, abort, make_response\nfrom api.v1.views import app_views\n\n\n@app_views.route('/cities//places',\n strict_slashes=False,\n methods=['GET'])\ndef place_all(city_id):\n \"\"\"Retrives a list of all place objects\"\"\"\n cities = models.storage.all('City')\n city_key = 'City.' + city_id\n place_list = []\n if city_key in cities.keys():\n city = cities.get(city_key)\n else:\n abort(404)\n for place in city.places:\n place_list.append(place.to_dict())\n return(jsonify(place_list))\n\n\n@app_views.route('/places/', methods=['GET'])\ndef place_grab(place_id):\n \"\"\"grab one place based on ID\"\"\"\n places = models.storage.all('Place')\n for key in places.keys():\n c, p, id = key.partition('.')\n if id == place_id:\n return (jsonify(places.get(key).to_dict()))\n abort(404)\n\n\n@app_views.route('/places/', methods=['DELETE'])\ndef place_del(place_id):\n \"\"\"delete a place object\"\"\"\n places = models.storage.all('Place')\n for key in places.keys():\n s, p, id = key.partition('.')\n if id == place_id:\n models.storage.delete(places.get(key))\n models.storage.save()\n return (jsonify({}))\n abort(404)\n\n\n@app_views.route('/cities//places',\n strict_slashes=False,\n methods=['POST'])\ndef place_create(city_id):\n \"\"\"Creates a place Object\"\"\"\n if not request.get_json():\n abort(400, \"Not a JSON\")\n if 'user_id' not in request.get_json():\n abort(400, \"Missing user_id\")\n if 'name' not in request.get_json():\n abort(400, \"Missing name\")\n cities = models.storage.all('City')\n city_key = 'City.' + city_id\n place_list = []\n if city_key not in cities.keys():\n abort(404)\n name = request.get_json()\n place = models.place.Place(city_id=city_id, **name)\n users = models.storage.all('User')\n for user in users.values():\n if place.user_id == user.id:\n models.storage.new(place)\n models.storage.save()\n return make_response(jsonify(place.to_dict()), 201)\n abort(404)\n\n\n@app_views.route('/places/', methods=['PUT'])\ndef place_change(place_id):\n \"\"\"update a place object\"\"\"\n if not request.get_json():\n abort(400, \"Not a JSON\")\n places = models.storage.all('Place')\n for key in places.keys():\n s, p, id = key.partition('.')\n if id == place_id:\n for k, v in request.get_json().items():\n if k not in (\n 'id', 'user_id',\n 'city_id', 'created_at',\n 'updated_at'\n ):\n setattr(places[key], k, v)\n models.storage.save()\n return (jsonify(places[key].to_dict()))\n abort(404)\n","sub_path":"api/v1/views/places.py","file_name":"places.py","file_ext":"py","file_size_in_byte":2977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"359511523","text":"import numpy as np\r\nimport random\r\nimport matplotlib.pyplot as plt\r\nfrom sklearn.metrics import mean_squared_error\r\nx_train = np.random.uniform(-1,1,(10000,2))\r\nvector = (2, -1)\r\ny_train = []\r\nfor x,y in x_train:\r\n y_train.append(vector[0]*x + vector[1]*y + np.random.normal(0,1))\r\n\r\ndef cal_error(w):\r\n pre_on_train = [x * w[0] + y * w[1] for x, y in x_train]\r\n return mean_squared_error(pre_on_train, y_train)\r\n\r\nT = 1000\r\nw = [0, 0]\r\ncnt = 0\r\nplot_arr = [cal_error(w)]\r\n\r\ndef cal_matrix(x,y):\r\n s = 0\r\n for i in range(len(x)):\r\n s += x[i] * y[i]\r\n\r\n return s\r\n\r\nfor i in range(1, T):\r\n step_size = 1/i\r\n if cnt == 10:\r\n plot_arr.append(cal_error(w))\r\n cnt = 0\r\n n = random.randint(0,9999)\r\n temp = [(y_train[n] - cal_matrix(w,x_train[n]))*x_train[n][0], (y_train[n] - cal_matrix(w,x_train[n]))*x_train[n][1]]\r\n w = [w[0] + step_size*temp[0], w[1] + step_size*temp[1]]\r\n cnt += 1\r\n\r\nplt.plot(plot_arr)\r\nplt.xlabel(\"# of 10 updates\")\r\nplt.ylabel(\"MSE\")\r\nplt.show()","sub_path":"Addition1.py","file_name":"Addition1.py","file_ext":"py","file_size_in_byte":1022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"585191283","text":"import random\nfrom Card import Card \n\nclass CardDeck:\n\t\n\tdef __init__(self):\n\t\tself.suits = ['Hearts', 'Diamonds', 'Clubs', 'Spades']\n\t\tself.values = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]\n\n\t\tself.deck = []\n\t\tself.discPile = []\n\t\t\n\t\tfor s in self.suits:\n\t\t\tfor v in self.values:\n\t\t\t\tself.deck.append(Card(v, s))\n\t\t\t\t\n\t\tself.shuffle()\n\n\tdef shuffle(self):\n\t\trandom.shuffle(self.deck)\n\n\tdef deal(self):\n\t\tif len(self.deck) > 0:\n\t\t\tself.card = random.choice(self.deck)\n\t\t\tself.deck.remove(self.card)\n\t\t\treturn self.card\n\t\telse:\n\t\t\treturn \"Deck is empty.\"\n\t\n\tdef discard(self, c):\n\t\tself.discPile.append(c)\n\t\t\n\tdef reshuffle(self):\n\t\tif len(self.deck) > 0:\n\t\t\tself.deck.append(self.discPile)\n\t\t\tself.shuffle()\n\t\t\tself.discPile = []\n\t\telse:\n\t\t\tself.deck = self.discPile\n\t\t\tself.shuffle()\n\t\t\tself.discPile = []\n\t\t\n","sub_path":"src/CardDeck.py","file_name":"CardDeck.py","file_ext":"py","file_size_in_byte":813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"595271340","text":"#CTI 110\r\n#Jessica Thompson\r\n#March 19, 2018\r\n#P4HW3 - Factorial\r\n\r\nnum = int(input(\"Enter a nonnegative integer? \"))\r\n\r\nfac = 1\r\n\r\nfor i in range(1, num + 1):\r\n fac = fac * i\r\n\r\nprint(\"The factorial of \", num, \" is \", fac)\r\n","sub_path":"P4HW3_Factorial_ThompsonJessica.py","file_name":"P4HW3_Factorial_ThompsonJessica.py","file_ext":"py","file_size_in_byte":228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"340153696","text":"'''\nAuthor: Puffrora\nDate: 2022-04-18 18:17:26\nLastModifiedBy: Puffrora\nLastEditTime: 2022-04-18 18:17:36\n'''\n\n\nfrom typing import List\n\nclass Solution:\n def largestValsFromLabels(self, values: List[int], labels: List[int], numWanted: int, useLimit: int) -> int:\n from collections import defaultdict\n \n sorted_item = [(values[i], labels[i]) for i in range(len(values))]\n sorted_item.sort(key=lambda x:-x[0])\n\n seen = defaultdict(int)\n res = 0\n for val, label in sorted_item:\n if numWanted == 0:\n break\n\n if label in seen:\n if seen[label] < useLimit:\n seen[label] += 1\n numWanted -= 1\n res += val\n else:\n numWanted -= 1\n res += val\n seen[label] += 1\n \n return res\n ","sub_path":"Leetcode/leetcode1090 受标签影响的最大值.py","file_name":"leetcode1090 受标签影响的最大值.py","file_ext":"py","file_size_in_byte":906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"511653364","text":"import os\r\nfrom tkinter import *\r\nimport pickle\r\nfrom google_auth_oauthlib.flow import InstalledAppFlow\r\nfrom google.auth.transport.requests import Request\r\n\r\nimport httplib2\r\nimport requests\r\nfrom googleapiclient import errors\r\nfrom googleapiclient.discovery import build\r\nfrom oauth2client.file import Storage\r\nfrom pydrive.auth import GoogleAuth\r\nfrom pydrive.drive import GoogleDrive\r\n\r\n\"\"\"\r\nCreated by: Jaemyong Chang\r\nOn: 3/31/2021\r\n\r\nThe purpose of this is to set up the initial folders and files for a collaborative notetaking study\r\nunder the guidance of Professor Mik Fanguy of KAIST university of Daejeon, South Korea.\r\n\r\nExample of files and folder creation.\r\nhttps://drive.google.com/drive/folders/15-9eieDl5aicGLEclj1qShdOWvP6pwvv?usp=sharing\r\n\r\nExample of the templates.\r\nhttps://drive.google.com/drive/folders/1z92dOmC0M_jkMv6651mtRQoGS3ABHy2Y?usp=sharing\r\n\r\nYou'll need to download the 'credentials.json' from your Google account.\r\n\r\n\"\"\"\r\n\r\n\r\n# If modifying these scopes, delete the file token.pickle.\r\nSCOPES = ['https://www.googleapis.com/auth/documents']\r\n\r\n\r\n# Get permission via web browser.\r\ngauth = GoogleAuth()\r\ngauth.LoadCredentialsFile('google_credentials.txt')\r\n\r\nif gauth.credentials is None:\r\n gauth.LocalWebserverAuth()\r\nelif gauth.access_token_expired:\r\n gauth.Refresh()\r\nelse:\r\n gauth.Authorize()\r\ngauth.SaveCredentialsFile('google_credentials.txt')\r\n\r\ndrive = GoogleDrive(gauth)\r\n\r\n\r\n# Get authorization.\r\nstorage = Storage('google_credentials.txt')\r\ncredentials = storage.get()\r\nhttp = httplib2.Http()\r\nhttp = credentials.authorize(http)\r\n\r\ndrive_service_v2 = build('drive', 'v2', http=http)\r\ndrive_service_v3 = build('drive', 'v3', http=http)\r\n\r\ncreds = None\r\n# The file token.pickle stores the user's access and refresh tokens, and is\r\n# created automatically when the authorization flow completes for the first\r\n# time.\r\nif os.path.exists('token.pickle'):\r\n with open('token.pickle', 'rb') as token:\r\n creds = pickle.load(token)\r\n# If there are no (valid) credentials available, let the user log in.\r\nif not creds or not creds.valid:\r\n if creds and creds.expired and creds.refresh_token:\r\n creds.refresh(Request())\r\n else:\r\n flow = InstalledAppFlow.from_client_secrets_file(\r\n 'client_secrets.json', SCOPES)\r\n creds = flow.run_local_server(port=0)\r\n # Save the credentials for the next run\r\n with open('token.pickle', 'wb') as token:\r\n pickle.dump(creds, token)\r\n\r\nservice = build('docs', 'v1', credentials=credentials)\r\ndoc_service = build('docs', 'v1', credentials=creds)\r\n\r\ntemplate_folder_id = None\r\nparent_id = None\r\n\r\ndoc_ids = []\r\n\r\n\r\ndef search_for_folder():\r\n \"\"\"\r\n Initial search of folders.\r\n \"\"\"\r\n global template_folder_id\r\n global doc_ids\r\n template_name = template_folder_name_entry.get()\r\n\r\n page_token = None\r\n while True:\r\n response = drive_service_v2.files().list(q=\"mimeType='application/vnd.google-apps.folder'\",\r\n spaces='drive',\r\n fields='nextPageToken, items(id, title)',\r\n pageToken=page_token).execute()\r\n for file in response.get('items', []):\r\n # Process change\r\n if file.get('title') == template_name:\r\n template_folder_id = file.get('id')\r\n print('Found file: %s (%s)' % (file.get('title'), file.get('id')))\r\n break\r\n page_token = response.get('nextPageToken', None)\r\n\r\n if page_token is None or template_folder_id is not None:\r\n break\r\n\r\n if template_folder_id is None:\r\n folder_id_label = Label(root, text='File Not Found')\r\n folder_id_label.grid(row=1, column=1)\r\n else:\r\n template_folder = drive.ListFile({'q': \"'%s' in parents and trashed=false\" % template_folder_id}).GetList()\r\n for doc in template_folder:\r\n print(doc['title'], doc['id'])\r\n doc_ids.append({'title': doc['title'], 'id': doc['id']})\r\n template_id_label = Label(root, text=str(len(doc_ids)) + ' doc(s) found.')\r\n template_id_label.grid(row=1, column=1)\r\n\r\n\r\ndef create_drive_folder():\r\n global parent_id\r\n folder_name = root_folder_name_entry.get()\r\n file_metadata = {\r\n 'name': folder_name,\r\n 'mimeType': 'application/vnd.google-apps.folder'\r\n }\r\n\r\n file = drive_service_v3.files().create(body=file_metadata, fields='id').execute()\r\n parent_id = file.get('id')\r\n folder_id_label = Label(root, text=parent_id)\r\n folder_id_label.grid(row=3, column=1)\r\n\r\n\r\ndef create_drive_folder_in_parent(root_id, folder_name):\r\n\r\n # for names in sub_folder_names:\r\n file_metadata = {\r\n 'name': folder_name,\r\n 'mimeType': 'application/vnd.google-apps.folder',\r\n 'parents': [root_id]\r\n }\r\n\r\n file = drive_service_v3.files().create(body=file_metadata, fields='id').execute()\r\n\r\n return file.get('id')\r\n\r\n\r\ndef create_folders():\r\n global parent_id\r\n global doc_ids\r\n\r\n section_names = section_name_entry.get().split()\r\n class_names = class_folder_name_entry.get().split()\r\n group_names = group_folder_name_entry.get().split()\r\n\r\n for section_name in section_names:\r\n section_id = create_drive_folder_in_parent(parent_id, section_name)\r\n\r\n for class_name in class_names:\r\n class_id = create_drive_folder_in_parent(section_id, class_name)\r\n\r\n for group_name in group_names:\r\n group_id = create_drive_folder_in_parent(class_id, group_name)\r\n\r\n for document in doc_ids:\r\n title = document['title']\r\n id = document['id']\r\n\r\n body = {\r\n 'name': title,\r\n 'parents': [group_id, ]\r\n }\r\n\r\n try:\r\n drive_service_v3.files().copy(fileId=id, body=body).execute()\r\n except:\r\n pass\r\n\r\n Label(root, text='Folders and Files Created').grid(row=7, column=1)\r\n\r\n\r\n# UI\r\nroot = Tk()\r\n\r\nroot.title('Create Files and Folders')\r\n\r\n# Search for the templates folder with the Google Docs templates.\r\nLabel(root, text='Template Folder').grid(row=0, column=0)\r\ntemplate_folder_name_entry = Entry(root, width=60, borderwidth=5)\r\ntemplate_folder_name_entry.grid(row=0, column=1)\r\n\r\nsearch_template_btn = Button(root, text='Search', command=search_for_folder)\r\nsearch_template_btn.grid(row=1, column=0)\r\n\r\n# Create parent (root) folder.\r\nLabel(root, text='Root Folder').grid(row=2, column=0)\r\nroot_folder_name_entry = Entry(root, width=60, borderwidth=5)\r\nroot_folder_name_entry.grid(row=2, column=1)\r\n\r\ncreate_parent_btn = Button(root, text='Create Folder', command=create_drive_folder)\r\ncreate_parent_btn.grid(row=3, column=0)\r\n\r\n# Create section folders\r\nLabel(root, text='Section Name(s)').grid(row=4, column=0)\r\nsection_name_entry = Entry(root, width=60, borderwidth=5)\r\nsection_name_entry.grid(row=4, column=1)\r\n\r\n# Create class folders\r\nLabel(root, text='Class Name(s)').grid(row=5, column=0)\r\nclass_folder_name_entry = Entry(root, width=60, borderwidth=5)\r\nclass_folder_name_entry.grid(row=5, column=1)\r\n\r\n# Create group folders.\r\nLabel(root, text='Group Name(s)').grid(row=6, column=0)\r\ngroup_folder_name_entry = Entry(root, width=60, borderwidth=5)\r\ngroup_folder_name_entry.grid(row=6, column=1)\r\n\r\n# Create files and folders.\r\ncreate_folders_btn = Button(root, text='Create Folder(s)', command=create_folders)\r\ncreate_folders_btn.grid(row=7, column=0)\r\n\r\ntemplate_folder_name_entry.insert(END, 'Templates Spring 2021')\r\nroot_folder_name_entry.insert(END, 'ABC_Spring2021')\r\nsection_name_entry.insert(END, 'Section1 Section2 Section3 Section4')\r\nclass_folder_name_entry.insert(END, 'Class1 Class2 Class3 Class4 Class5')\r\ngroup_folder_name_entry.insert(END, 'Group1 Group2 Group3 Group4 Group5')\r\n\r\nroot.mainloop()\r\n\r\n\r\n","sub_path":"FileCreator/create_files_and_folders.py","file_name":"create_files_and_folders.py","file_ext":"py","file_size_in_byte":7994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"5370029","text":"import random\r\nimport time\r\n\r\nclass Pet:\r\n def __init__(self, name):\r\n self.name = name\r\n self.health = random.randrange(70, 100)\r\n self.mood = random.randrange(50, 100)\r\n self.hunger = random.randrange(60)\r\n self.cleanliness = random.randrange(0,100)\r\n # changing value\r\n self.healthChange = 0\r\n self.moodChange = 0\r\n self.hungerChange = 0\r\n self.cleanlinessChange = 0\r\n self.is_alive = True\r\n\r\n def resetChangingValues(self):\r\n self.healthChange = 0\r\n self.moodChange = 0\r\n self.hungerChange = 0\r\n self.cleanlinessChange = 0\r\n\r\n def __repr__(self):\r\n return r\"\"\"\r\n .---------------------------------.\r\n | .-----------------------------. |\r\n \r\n Round {} \r\n ^__^\r\n (oo)\\_______\r\n (__)\\ )\\/\\\r\n ||----w |\r\n || ||\r\n \r\n {} \r\n Health: {}/100 \r\n Mood: {}/100 \r\n Hunger: {}/100\r\n Cleanliness: {}/100 \r\n\r\n | |_____________________________| |\r\n |_________________________________| \r\n \"\"\".format(n_rounds, self.name, self.health, self.mood, self.hunger, self.cleanliness)\r\n \r\n def leave_alone(self):\r\n\r\n actions = [\"takeARest\",\"catchARat\", \"eatPoison\", \"fightWACat\"]\r\n result = random.choice(actions)\r\n\r\n if result == \"takeARest\":\r\n time.sleep(1.0)\r\n print(\"Shhhhh {} is taking a rest. ZZZ\".format(self.name))\r\n #Health+\r\n self.healthChange = random.randrange(5,10)\r\n self.health += self.healthChange \r\n #Mood+\r\n self.moodChange = random.randrange(5,20) \r\n self.mood += self.moodChange\r\n #print status\r\n time.sleep(1.5)\r\n print(\"Health: +{}\".format(self.healthChange))\r\n time.sleep(0.5)\r\n print(\"Mood: +{}\".format(self.moodChange))\r\n\r\n if result == \"catchARat\":\r\n time.sleep(1.0)\r\n print(\"{} caught a rat. LOL\".format(self.name))\r\n self.moodChange = random.randrange(30,50)\r\n self.mood += self.moodChange\r\n self.cleanlinessChange = random.randrange(10,20)\r\n self.cleanliness -= self.cleanlinessChange\r\n time.sleep(0.5)\r\n print(\"Mood: +{}\".format(self.moodChange))\r\n print(\"Cleanliness: -{}\".format(self.cleanlinessChange))\r\n\r\n if result == \"eatPoison\":\r\n time.sleep(1.0)\r\n print(\"{} just ate some poisonous food! Poor {}!\".format(self.name, self.name))\r\n self.healthChange = random.randrange(30,50)\r\n self.health -= self.healthChange\r\n time.sleep(0.5)\r\n print(\"Health: -{}\".format(self.healthChange))\r\n\r\n if result == \"fightWACat\":\r\n print(\"{} came across a cat. A fight can't be avoided...\".format(self.name))\r\n time.sleep(1.0)\r\n print(\"And the winner goes to (drum rolling)\")\r\n time.sleep(1.0)\r\n resultOfFight = random.choice([0, 1])\r\n if resultOfFight == 0:\r\n print(\"{}!\".format(self.name))\r\n self.moodChange = random.randrange(10,20)\r\n self.mood += self.moodChange\r\n time.sleep(0.5)\r\n print(\"Mood: +{}\".format(self.moodChange))\r\n elif resultOfFight == 1:\r\n print(\"The Cat!\")\r\n self.moodChange = random.randrange(10,20)\r\n self.mood -= self.moodChange\r\n time.sleep(0.5)\r\n print(\"Mood: -{}\".format(self.moodChange))\r\n self.healthChange = random.randrange(10,20)\r\n self.health -= self.healthChange\r\n self.cleanlinessChange = random.randrange(20,40)\r\n self.cleanliness -= self.cleanlinessChange\r\n \r\n #print status\r\n time.sleep(0.5)\r\n print(\"Health: -{}\".format(self.healthChange))\r\n print(\"Cleanliness: -{}\".format(self.cleanlinessChange))\r\n\r\n \r\n def feed(self):\r\n if self.hunger < 0: # overeats\r\n print(\"{} seems to have had too much!\".format(self.name))\r\n self.healthChange = random.randrange(5, 15)\r\n self.health -= self.healthChange\r\n self.moodChange = random.randrange(5, 10)\r\n self.mood -= self.moodChange\r\n self.hungerChange = 0\r\n self.hunger -= self.hungerChange\r\n time.sleep(1.0)\r\n print(r\"\"\"\r\n Health: -{}\r\n Mood: -{}\r\n Hunger: \\+{}\r\n \"\"\".format(self.healthChange, self.moodChange, self.hungerChange))\r\n else:\r\n print(\"{} has had a good meal!\".format(self.name))\r\n self.hungerChange = random.randrange(20,35)\r\n self.hunger -= self.hungerChange\r\n self.moodChange = random.randrange(5, 10)\r\n self.mood += self.moodChange\r\n\r\n time.sleep(1.0)\r\n print(r\"\"\"\r\n Mood: +{}\r\n Hunger: -{}\r\n \"\"\".format(self.moodChange, self.hungerChange))\r\n \r\n def play(self):\r\n if self.hunger > 40:\r\n print(\"{} is too hungry to play. Why not feed {} some food?\".format(self.name, self.name))\r\n return\r\n elif self.mood < 40:\r\n print(\"Seems {} is in a bad mood. Why not leave {} alone for a while?\".format(self.name, self.name))\r\n return\r\n else:\r\n print(r\"\"\"\r\n _______________\r\n < Yay! >\r\n ---------------\r\n \\ ^__^\r\n \\ (oo)\\_______\r\n (__)\\ )\\/\\\r\n ||----w |\r\n || ||\r\n \"\"\")\r\n self.moodChange = random.randrange(10, 30)\r\n self.mood += self.moodChange\r\n self.cleanlinessChange = random.randrange(10,40)\r\n self.cleanliness -= self.cleanlinessChange\r\n time.sleep(1.0)\r\n print(\"Mood: +{}\".format(self.moodChange))\r\n print(\"Cleanliness: -{}\".format(self.cleanlinessChange))\r\n\r\n\r\n def take_to_vet(self):\r\n self.moodChange = random.randrange(10,20)\r\n self.mood -= self.moodChange\r\n print(r\"\"\"\r\n_________________\r\n< I hate the vet >\r\n ----------------\r\n \\ ^__^\r\n \\ (oo)\\_______\r\n (__)\\ )\\/\\\r\n ||----w |\r\n || ||\r\n \r\n \"\"\")\r\n time.sleep(0.5)\r\n print(\"Mood: -{}\".format(self.moodChange))\r\n\r\n if self.health > 50:\r\n print(\"{} took some medicine.\".format(self.name))\r\n self.healthChange = random.randrange(40,50)\r\n self.health += self.healthChange\r\n time.sleep(0.5)\r\n print(\"Health: +{}\".format(self.healthChange))\r\n print(\"{} feels good now!\".format(self.name))\r\n else:\r\n print(\"{} is seriously ill. A surgery is needed!\".format(self.name))\r\n surgeryResult = random.choice([0,1]) #0 is better, 1 is worse.\r\n if surgeryResult == 0:\r\n self.healthChange = random.randrange(50,99)\r\n self.health += self.healthChange\r\n time.sleep(1.0)\r\n print(\"Health: +{}\".format(self.healthChange))\r\n print(\"{} feels good now!\".format(self.name))\r\n elif surgeryResult == 1:\r\n self.health = 0\r\n time.sleep(1.0)\r\n print(\"Sorry, we did everything we could.\")\r\n return\r\n\r\n def takeABath(self):\r\n self.moodChange = random.randrange(10,30)\r\n self.mood -= self.moodChange\r\n print(r\"\"\"\r\n_________________\r\n< I hate bath >\r\n ----------------\r\n \\ ^__^\r\n \\ (oo)\\_______\r\n (__)\\ )\\/\\\r\n ||----w |\r\n || ||\r\n \r\n \"\"\")\r\n time.sleep(0.5)\r\n print(\"Mood: -{}\".format(self.moodChange))\r\n\r\n self.cleanlinessChange = random.randrange(30,60)\r\n self.cleanliness += self.cleanlinessChange\r\n print(\"Cleanliness: +{}\".format(self.cleanlinessChange))\r\n \r\n\r\n def update(self):\r\n if self.healthChange == 0:\r\n self.health -= random.randrange(0,10)\r\n if self.cleanlinessChange == 0:\r\n self.cleanliness -= random.randrange(5,20) \r\n if self.hungerChange == 0:\r\n self.hunger += random.randrange(10,20)\r\n\r\n if self.hunger > 100: # cannot exceed the max value of 100\r\n self.is_alive = False\r\n print(\"{) died of starvation. Poor {}\".format(self.name, self.name))\r\n elif self.hunger > 80:\r\n self.health -= random.randrange(10, 30)\r\n elif self.hunger < 0:\r\n self.hunger = 0\r\n\r\n if self.mood > 100:\r\n self.mood = 100\r\n\r\n if self.cleanliness < 0:\r\n self.cleanliness = 0\r\n elif self.cleanliness > 100:\r\n self.cleanliness = 100\r\n\r\n if self.health > 100:\r\n self.health = 100\r\n if self.health <= 0:\r\n self.is_alive = False\r\n \r\n \r\n\r\n# Game Start\r\nprint(r\"\"\"\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\ntime.sleep(0.5)\r\nprint(\"Your goal in this game is to keep your pet alive for as many rounds as possible!\")\r\ntime.sleep(0.5)\r\nname = input(\"Please give your pet a name: \")\r\npet = Pet(name)\r\nn_rounds = 0\r\ntime.sleep(1.0)\r\nprint(r\"\"\"\r\nSay hi to {}!\r\n\"\"\".format(name))\r\nprint(r\"\"\"\r\n _______________\r\n< Hello world! >\r\n ---------------\r\n \\ ^__^\r\n \\ (oo)\\_______\r\n (__)\\ )\\/\\\r\n ||----w |\r\n || ||\r\n\r\n\"\"\")\r\n# print(image)\r\n\r\nmenu = \"\"\"\r\nWhat would you like to do with {}: \r\n (1) leave it alone\r\n (2) feed\r\n (3) play\r\n (4) take to the vet\r\n (5) take a bath\r\nPlease choose an action: \"\"\".format(pet.name)\r\nwhile True:\r\n n_rounds += 1\r\n time.sleep(1.0)\r\n print(\"-\" * 100)\r\n print(pet)\r\n action = input(menu)\r\n if action == \"1\":\r\n pet.leave_alone()\r\n elif action == \"2\":\r\n pet.feed()\r\n elif action == \"3\":\r\n pet.play()\r\n elif action == \"4\":\r\n pet.take_to_vet()\r\n elif action == \"5\":\r\n pet.takeABath()\r\n else:\r\n print(\"Invalid action, will leave the pet alone\")\r\n pet.leave_alone()\r\n pet.update()\r\n pet.resetChangingValues()\r\n if not pet.is_alive:\r\n print(\"{0} is dead! Poor {0}!\".format(pet.name))\r\n break\r\n \r\nprint(\"Game over. {} lived for {} rounds\".format(pet.name, n_rounds))","sub_path":"assignment/8/fake_tamagotchi.py","file_name":"fake_tamagotchi.py","file_ext":"py","file_size_in_byte":11971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"175505770","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport os\nimport re\nimport sys\nimport json\nimport time\nimport traceback\n\nimport boot\nimport constantValues as CONSTANT\nimport nativeHelper\nimport pexpect\nfrom caseUtils import CaseUtils\nfrom logStat import LogAnalysisTools\nfrom netBasicCase import NetUtils\nfrom powerManager import TvPowerControl\nfrom systemAction import BasicSystemAction\nfrom testcase import TestCase\nfrom utils import Log\n\n\nclass TestMultimedia(TestCase):\n def __init__(self, doc, level, owner):\n super(TestMultimedia, self).__init__(doc, level, owner)\n self.package_name = \"\"\n self.test_content = \"\"\n # run_case_type 0 normal\n # run_case_type 1 STR\n # run_case_type 2 fake STR\n # run_case_type 3 DC off and on\n # run_case_type 4 AC off and on\n self.run_case_type = 0\n self.run_timeout = 17 * 60\n self.dc_action_tag = True\n self.caseUtils = CaseUtils()\n self.str_timeout = 30\n self.jar_run_state = ''\n self.netutils = None\n self.CONNECT_WIFI = False\n self.BT_TAG = False\n self.USB_TAG = False\n self.UPLOAD_TAG = False\n self.loop_counts = 0\n self.exception_list = []\n self.expect_list = []\n\n def set_procrank_env(self):\n self.su_by_proc()\n self.sendline('ls /system/xbin/procrank')\n self.expect(['shell@', 'root@', pexpect.TIMEOUT])\n if 'No such file' in self.connection.before:\n Log().warning('no procrank in current device, try to download one')\n self.sendline('mount -o remount,rw /system')\n self.expect(['shell@', 'root@', pexpect.TIMEOUT])\n #\n self.sendline('cd /system/lib64')\n self.expect(['shell@', 'root@', pexpect.TIMEOUT])\n self.sendline(\n 'busybox wget -O libpagemap.so http://172.16.117.1:8000/resource/media/procrank/libpagemap.so_system_lib64')\n\n self.sendline('cd /system/lib')\n self.expect(['shell@', 'root@', pexpect.TIMEOUT])\n self.sendline(\n 'busybox wget -O libpagemap.so http://172.16.117.1:8000/resource/media/procrank/libpagemap.so_system_lib')\n\n self.sendline('cd /system/xbin')\n self.expect(['shell@', 'root@', pexpect.TIMEOUT])\n self.sendline('busybox wget http://172.16.117.1:8000/resource/media/procrank/procrank')\n self.expect(['shell@', 'root@', pexpect.TIMEOUT])\n self.sendline('chmod 755 procrank')\n self.empty_buffer()\n\n def call_script_on_DUT(self, call_cmd):\n self.sendline(call_cmd + ' &')\n self.sendline('echo $! > /tmp/script.pid')\n index = self.expect(['shell@', 'root@', pexpect.TIMEOUT])\n if index == 2:\n Log().error('Fail to run mem script')\n\n def stop_script_on_DUT(self):\n self.sendcontrol('c')\n self.sendline('su')\n self.sendline('cd /data/local/tmp')\n Log().info('stop script process')\n self.sendline('if [ -f /tmp/script.pid ]; then kill `cat /tmp/script.pid`; fi')\n self.empty_buffer()\n\n def get_current_time(self):\n return time.strftime('%Y%m%d%H%M%S')\n\n def check_mm_exception_from_logcat(self):\n error_infos = ''\n e_mm_res_list = []\n for filename in self.adb_log_path:\n Log().info(\"\\n\\t\\t\\t\\t\\t [ \" + filename + \" ]\")\n\n for e in LogAnalysisTools().analyze_playstat(filename):\n if e not in e_mm_res_list:\n e_mm_res_list.append(e)\n Log().error('Error mm res list: ' + str(e_mm_res_list))\n for error in e_mm_res_list:\n if error and error[0] not in error_infos:\n error_infos += error[0] + \"_\" + error[1] + \"_\" + error[2] + \" |\\t\"\n if error_infos != '':\n self._msg += error_infos.encode('utf-8')\n return error_infos\n\n def check_mute(self):\n if self.platform.upper() in ['APOLLO', 'PHOEBUS', 'FORMULA']:\n self.sendcontrol('c')\n self.sendline('cat /proc/msp/sound0')\n index = self.expect(['I2S1.*Mute\\(off\\)', pexpect.TIMEOUT, pexpect.EOF])\n if index == 0:\n return True\n return False\n\n def check_bt(self):\n self.get_msg_from_jar(\n self.run_normal_case('cn.whaley.cases.Apollo.bt.btTestSets', 'checkBtState -e cc Y -e cl Y',\n 300))\n attempt_count = 1\n while self._status != 'PASS':\n self.kill_all_app()\n self.get_msg_from_jar(\n self.run_normal_case('cn.whaley.cases.Apollo.bt.btTestSets', 'checkBtState -e cc Y -e cl Y',\n 300))\n if attempt_count > 10:\n Log().error('Can not confirm the bt status')\n return False\n return True\n\n def check_USB(self):\n self.sendline('ls /mnt/usb/*')\n self.expect(['shell@', 'root@'])\n if 'No such file' in self.connection.before:\n Log().info('No USB Mounted')\n return False\n return True\n\n def check_network(self):\n self.sendline('ping -W5 -c1 www.baidu.com')\n index = self.expect(['1 received', '0 received', pexpect.TIMEOUT, pexpect.EOF])\n return index == 0\n\n def get_msg_from_jar(self, jar_log):\n result_infos = ''\n ERROR_TAG = '>>>>> [ ERROR ]'\n INFO_TAG = '>>>>> [ INFO ]'\n if jar_log:\n jar_log_line_list = jar_log.split('\\r\\n')\n for line in jar_log_line_list:\n if self.jar_run_state == 1 and INFO_TAG in line:\n self.jar_run_state = 0\n if ERROR_TAG in line:\n error_info = line.split(ERROR_TAG)[1]\n if error_info not in result_infos:\n result_infos += error_info + ' #'\n if re.match('E write.*Broken pipe', line):\n self.jar_run_state = -1\n # Log().error(\"ERROR\" + result_infos)\n self._msg += result_infos\n\n def run_normal_case(self, pkg_name='', content_info='', timeout=0):\n self.jar_run_state = 1\n if pkg_name != '' and content_info != '' and timeout != 0:\n return self.run_uiautomator(package_name=pkg_name, test_content=content_info,\n timeout=timeout)\n return self.run_uiautomator(package_name=self.package_name, test_content=self.test_content,\n timeout=self.run_timeout)\n\n def check_su_status(self):\n self.sendcontrol('c')\n self.empty_buffer()\n self.sendline('cd /')\n platform_value = self.platform.lower()\n if platform_value == 'sphinx' or platform_value == 'cronus':\n index = self.expect(\n ['shell@' + platform_value + ':/ $', 'root@' + platform_value + ':/ #', pexpect.TIMEOUT, pexpect.EOF])\n else:\n index = self.expect(\n ['shell@' + platform_value + ':/ $', 'shell@' + platform_value + ':/ #', pexpect.TIMEOUT, pexpect.EOF])\n if index == 3:\n self._msg += 'Trouble may appear in serial connection #'\n Log().error('Trouble may appear in serial connection')\n return index\n # Sphinx/Cronus\n # shell@sphinx:/ $\n # root@sphinx:/ #\n\n # Helios/Apollo/Athena/Formula/Phoebus\n # shell@apollo:/ $\n # shell@apollo:/ #\n\n def check_str_status(self):\n index = self.expect([CONSTANT.STR_OFF_PROMPT[self.platform.upper()], pexpect.EOF, pexpect.TIMEOUT])\n if index == 0:\n Log().info(\"In Str\")\n return True\n return False\n\n def su_by_proc(self):\n attmpt_count = 0\n while self.check_su_status() != 1:\n attmpt_count += 1\n if attmpt_count > 3:\n Log().error('Fail to su')\n return False\n Log().info('Try at ' + str(attmpt_count))\n self.empty_buffer()\n self.sendcontrol('c')\n self.sendline('su')\n self.empty_buffer()\n Log().info(\"Su Done\")\n return True\n\n def kill_all_app(self):\n package_name = 'cn.whaley.util.toolUtil.windowSets.LauncherWindow'\n test_content = 'killAllAppBack_ground'\n self.get_msg_from_jar(self.run_uiautomator(package_name=package_name, test_content=test_content,\n timeout=300))\n\n def prepare_str_or_dc_env(self):\n if self.plan.rctty == \"\":\n if boot.set_auto_wake_up():\n CaseUtils.boot_count += 1\n Log().info('set_str_dc_auto_wake_up_env done')\n if self.su_by_proc():\n return True\n self._msg += 'Fail to su after set auto wake up #'\n self._status = 'FAIL'\n return False\n else:\n self._msg += 'Fail to set str dc auto wake up env #'\n self._status = 'FAIL'\n return False\n else:\n if self.caseUtils.prepare_rc_env(self.connection, self.plan.rctty):\n Log().info('Match BT Done')\n return True\n else:\n self._msg += 'Fail to match BT #'\n self._status = 'FAIL'\n return False\n\n def clear_str_or_dc_env(self):\n if self.plan.rctty == \"\":\n if boot.clear_auto_wake_up():\n CaseUtils.boot_count += 1\n Log().info('clear str dc auto wake up env done')\n if self.su_by_proc():\n return True\n self._msg += 'Fail to su after clear auto wake up #'\n self._status = 'FAIL'\n return False\n else:\n self._msg += 'Fail to clear str dc auto wake up env #'\n self._status = 'FAIL'\n return False\n\n def do_STR(self):\n if self.plan.rctty == \"\":\n if BasicSystemAction.STR_and_resume():\n return True\n return False\n else:\n return self.caseUtils.str_off_on_by_bt(self.platform, self.connection, self.str_timeout)\n\n def run_STR_case(self):\n self.get_msg_from_jar(self.run_normal_case())\n if self._status == 'PASS':\n last_interface = self.caseUtils.check_current_interface(self.connection)\n mute_state = self.check_mute()\n if self.do_STR():\n Log().info('STR done ')\n time.sleep(5)\n if mute_state != self.check_mute():\n self._msg += 'Mute state changed after STR'\n self.package_name = 'cn.whaley.util.caseUtil.media.CaseBase'\n self.test_content = 'testMultimediaAfterSTR -e lastInterface ' + last_interface\n self.get_msg_from_jar(self.run_normal_case())\n else:\n Log().error('Fail to Do STR')\n self._status = 'FAIL'\n self._msg += 'Fail to Do STR #'\n else:\n Log().error('Fail Before STR')\n self._status = 'FAIL'\n self._msg += 'Fail Before STR #'\n\n def run_STR_case_Stress(self):\n loop_count = 0\n fail_str_count = 0\n self.get_msg_from_jar(self.run_normal_case())\n while self._status == 'PASS' and loop_count < self.loop_counts:\n last_interface = self.caseUtils.check_current_interface(self.connection)\n if self.do_STR():\n Log().info('STR done ')\n loop_count += 1\n time.sleep(1)\n self.get_msg_from_jar(self.run_normal_case('cn.whaley.util.caseUtil.media.CaseBase', \\\n 'testMultimediaAfterSTR -e lastInterface ' + last_interface, \\\n 600))\n if self._status == 'FAIL':\n self._msg += 'Bug may appear'\n sys.exit(-1)\n else:\n fail_str_count += 1\n Log().error('Fail to Do STR ' + str(fail_str_count) + ' at ' + str(loop_count))\n # self._status = 'FAIL'\n self._msg += 'Fail to Do STR #' + str(fail_str_count) + ' at ' + str(loop_count)\n if fail_str_count > self.loop_counts / 5:\n self._status = 'FAIL'\n self._msg += 'Fail to STR ' + str(fail_str_count)\n break\n Log().debug('Boot count: ' + str(CaseUtils.boot_count))\n\n if self.caseUtils.check_boot(self.serial_log_path, self.platform):\n self._status = 'FAIL'\n self._msg += 'Boot during run case #'\n sys.exit(-1)\n if self.BT_TAG:\n if not self.check_bt():\n self._status = 'FAIL'\n self._msg = 'No BT STATUS at the case'\n sys.exit(-1)\n if self.USB_TAG:\n if not self.check_USB():\n self._status = 'FAIL'\n self._msg = 'No USB Mounted at the case'\n sys.exit(-1)\n self.get_msg_from_jar(self.run_normal_case())\n\n if not self._status == 'PASS':\n self._msg += 'Fail to Play at loop ' + str(loop_count) + ' Before STR #'\n Log().error('Fail to Play at loop ' + str(loop_count) + ' Before STR')\n\n def do_DC_off_and_on(self):\n if self.plan.rctty == \"\":\n if BasicSystemAction.shutdown_and_start():\n CaseUtils.boot_count += 1\n return True\n return False\n else:\n return self.caseUtils.dc_off_on_by_bt(self.connection, self.platform, dc_action_tag=self.dc_action_tag)\n\n def run_DC_off_and_on_case(self):\n self.get_msg_from_jar(self.run_normal_case())\n if self._status == 'PASS':\n if self.do_DC_off_and_on():\n Log().info('DC done ')\n time.sleep(5)\n if not self.su_by_proc():\n self._msg += 'Fail to su after DC #'\n self._status = 'FAIL'\n return\n self.package_name = \"cn.whaley.cases.Helios.media.video.vod.MusicTestCase\"\n self.test_content = \"playSpecMusicFromSearch\"\n self.get_msg_from_jar(self.run_normal_case())\n else:\n self._status = 'FAIL'\n self._msg += 'Fail to Do DC #'\n else:\n Log().error('Fail Before DC')\n self._status = 'FAIL'\n self._msg += 'Fail Before DC #'\n\n def run_AC_off_and_on_case(self):\n self.get_msg_from_jar(self.run_normal_case())\n if self._status == 'PASS':\n if TvPowerControl.AC_OFF() and TvPowerControl.AC_ON():\n CaseUtils.boot_count += 1\n Log().info('AC Done ')\n if (self.platform.upper() == 'MONE' or self.platform.upper() == 'FORMULA') \\\n and not self.check_str_status():\n self._msg = 'May no secondary standby '\n self._status = 'FAIL'\n return\n if BasicSystemAction.wait_boot_finish() and self.su_by_proc():\n time.sleep(5)\n self.package_name = \"cn.whaley.util.toolUtil.CommonApi\"\n self.test_content = 'hasInfoText -e text 今日推荐'\n self.get_msg_from_jar(self.run_normal_case())\n self.package_name = \"cn.whaley.cases.Helios.media.video.vod.TodayTopTestSets\"\n self.test_content = \"testOneOnBaseFunction\"\n self.get_msg_from_jar(self.run_normal_case())\n else:\n self._status = 'FAIL'\n Log().error('Fail to restore env after AC ')\n else:\n self._status = 'FAIL'\n Log().error('Fail to Do AC ')\n else:\n Log().error('Fail Before AC')\n self._status = 'FAIL'\n self._msg += 'Fail Before AC #'\n\n def main_case(self):\n\n if self.run_case_type == 0:\n # kill all background app first ,to clear the env\n self.get_msg_from_jar(\n self.run_normal_case(pkg_name='cn.whaley.util.toolUtil.windowSets.LauncherWindow',\n content_info='killAllAppBackground',\n timeout=15))\n if self._status != 'PASS':\n Log().error('Fail to kill app background')\n self.get_msg_from_jar(self.run_normal_case())\n elif self.run_case_type == 1:\n if self.prepare_str_or_dc_env():\n self.run_STR_case()\n self.clear_str_or_dc_env()\n\n # elif self.run_case_type == 2:\n # self.run_fake_STR_case()\n elif self.run_case_type == 3:\n if self.prepare_str_or_dc_env():\n self.run_DC_off_and_on_case()\n self.clear_str_or_dc_env()\n elif self.run_case_type == 4:\n if self.platform.upper() == 'FORMULA' or self.platform.upper() == 'MONE':\n if boot.set_auto_wake_up(2):\n CaseUtils.boot_count += 1\n Log().info('set_str_dc_auto_wake_up_env done')\n if not self.su_by_proc():\n self._msg += 'Fail su by proc #'\n self._status = 'FAIL'\n Log().error('Fail su by proc')\n return\n else:\n self._msg += 'Fail to set str dc auto wake up env #'\n self._status = 'FAIL'\n return\n self.run_AC_off_and_on_case()\n if self.platform.upper() == 'FORMULA' or self.platform.upper() == 'MONE':\n if boot.clear_auto_wake_up():\n CaseUtils.boot_count += 1\n Log().info('clear str dc auto wake up env done')\n if not self.su_by_proc():\n self._msg += 'Fail su by proc #'\n self._status = 'FAIL'\n Log().error('Fail su by proc')\n return\n else:\n self._msg += 'Fail to su after clear auto wake up #'\n self._status = 'FAIL'\n return\n elif self.run_case_type == 5:\n if self.prepare_str_or_dc_env():\n self.run_STR_case_Stress()\n self.clear_str_or_dc_env()\n\n def enable_stop_tag2plan(self):\n Log().debug(\"Starting ....\" + str(self.plan._plan_name))\n with open(self.plan._plan_name, 'r') as plan_json:\n contents = json.load(plan_json)\n case_number = len(contents['case'])\n for i in range(case_number):\n case = contents['case'][i]['name']\n if case == \"test_demo.py\":\n Log().info(\"Add stopTask for \" + self.plan._plan_name)\n contents['case'][i]['stopTask'] = True\n with open(self.plan._plan_name, 'w') as plan_json:\n json.dump(contents, plan_json)\n\n def get_log_and_anlyz(self):\n self.stop_log()\n if os.path.exists(self.serial_log_path) and self.caseUtils.check_boot(self.serial_log_path,\n self.platform):\n self._status = 'FAIL'\n self._msg += \"Boot during run case #\"\n self.connection.sendline('echo \"serial connection state\"')\n index = self.connection.expect(['shell@', 'root@', pexpect.EOF, pexpect.TIMEOUT])\n if index >= 2:\n if self._status == 'NA':\n self._msg += 'serail disconnect during run case #'\n Log().error('Serial disconnected')\n\n if self.adb_log_path:\n self.check_mm_exception_from_logcat()\n _, exception_tag, expect_tag = self.check_exception_from_logcat(exceptions=self.exception_list,\n expects=self.expect_list)\n if exception_tag or not expect_tag:\n self.enable_stop_tag2plan()\n if exception_tag:\n self._msg += 'Quit task for exception key words occur #'\n if not expect_tag:\n self._msg += 'Quit task for expect key words not occur #'\n elif os.path.exists(self.serial_log_path):\n self.check_exception_from_seriallog()\n Log().warning('No logcat to anlyz: ')\n self._msg += 'No logcat to anlyz #'\n\n def execute(self):\n Log().info(\"Timeout : \" + str(self.run_timeout))\n if self.connection:\n self.start_log()\n try:\n if self.CONNECT_WIFI:\n self.netutils = NetUtils(self)\n if not self.netutils:\n self._status = 'FAIL'\n self._msg = 'Fail to create netutils'\n sys.exit(-1)\n if not self.netutils.disable_lan():\n self._status = 'FAIL'\n self._msg = 'Fail to disconnect wlan'\n sys.exit(-1)\n result, ssidvalue = self.netutils.connect_a_wifi_in_lib()\n if not result:\n self._status = 'FAIL'\n self._msg = 'Fail to connect ssid ' + ssidvalue\n self.netutils.connect_lan()\n sys.exit(-1)\n if self.BT_TAG:\n if not self.check_bt():\n self._status = 'FAIL'\n self._msg = 'No BT STATUS at the begining of case'\n sys.exit(-1)\n if self.USB_TAG:\n if not self.check_USB():\n self._status = 'FAIL'\n self._msg = 'No USB Mounted'\n sys.exit(-1)\n if self.UPLOAD_TAG:\n target_folder = os.path.join(self.out, self.case_name_seq)\n serverinfo_abspath = '/data/local/tmp/TAP/serverInfo.log'\n self.sendline(\n 'echo \"SERVER_IP=' + self._ip + '\\nTARGET_FOLDER=' + target_folder + '\\n\" > ' + serverinfo_abspath)\n if not nativeHelper.is_path_exist(serverinfo_abspath, True):\n self._status = 'FAIL'\n self._msg = 'Fail to generate serverinfo file'\n Log().error('Fail to generate serverinfo file')\n sys.exit(-1)\n self.main_case()\n if (self.CONNECT_WIFI or self.BT_TAG) and self._status != 'PASS':\n self._msg += 'Not Pass,reserved scene'\n else:\n if self.CONNECT_WIFI:\n self.netutils.connect_lan()\n if self.BT_TAG:\n if not self.check_bt():\n self._status = 'FAIL'\n self._msg = 'No BT STATUS at the end case'\n sys.exit(-1)\n if self.USB_TAG:\n if not self.check_USB():\n self._status = 'FAIL'\n self._msg = 'No USB Mounted at the end case'\n sys.exit(-1)\n except Exception:\n Log().error('Exception in main case')\n Log().error(traceback.format_exc())\n finally:\n Log().debug('Boot count: ' + str(CaseUtils.boot_count))\n self.get_log_and_anlyz()\n # jar_run_state\n # 0 run normal 真正的timeout\n # -1 broken pip 串口断开\n # 1 not run 串口输入无反应\n if self._status == 'NA':\n self._status = 'FAIL''FAIL'\n if self.jar_run_state == 0:\n self._msg += 'case not finish before killed #'\n elif self.jar_run_state == 1:\n self._msg += 'case not run by serial #'\n elif self.jar_run_state == -1:\n self._msg += 'serail disconnect during run case #'\n\n else:\n self._msg += 'Fail to connect serial #'\n self._status = 'FAIL'\n","sub_path":"lib/multimedia_test_case.py","file_name":"multimedia_test_case.py","file_ext":"py","file_size_in_byte":24577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"537811963","text":"# encoding: utf-8\n\nfrom unittest import TestCase\nimport web.core\nfrom webob import Request\n\n\n__all__ = ['PlainController', 'WebTestCase']\n\n\n\nclass PlainController(web.core.Controller):\n def __before__(self, *parts, **data):\n web.core.response.content_type = \"text/plain\"\n return super(PlainController, self).__before__(*parts, **data)\n\n\nclass WebTestCase(TestCase):\n def assertResponse(self, path, status='200 OK', content_type='text/plain', _method='get', **kw):\n request = Request.blank(path, environ=dict(REMOTE_ADDR='127.0.0.1'))\n request.method = _method\n \n response = request.get_response(self.app)\n \n self.assertEqual((response.status, response.content_type), (status, content_type))\n \n for i, j in kw.iteritems():\n self.assertEqual(getattr(response, i), j)\n \n return response\n \n def assertPostResponse(self, path, data={}, status='200 OK', content_type='text/plain', **kw):\n request = Request.blank(path)\n \n request.method = \"POST\"\n request.POST.update(data)\n \n response = request.get_response(self.app)\n \n self.assertEqual((response.status, response.content_type), (status, content_type))\n \n for i, j in kw.iteritems():\n self.assertEqual(getattr(response, i), j)\n \n return response\n","sub_path":"tests/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":1393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"304324566","text":"import os\nimport math\n\nos.environ[\"PATH\"] += os.pathsep + 'C:/Program Files (x86)/Graphviz2.38/bin/'\n\nimport pandas as pd\nimport numpy as np\n\nfrom sklearn import tree\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import accuracy_score\n\nfrom sklearn.ensemble import RandomForestClassifier, RandomForestRegressor\n\nimport pydotplus\nfrom sklearn.tree import export_graphviz\n\nfrom sklearn.model_selection import GridSearchCV\n\n\ndf_train = pd.read_excel('C:/Users/jerem/Documents/Git/machine_learning/goal_tree/titanic_2/med/pima.xls',\n sheet_name = \"apprentissage\")\n\n\ndf_test = pd.read_excel('C:/Users/jerem/Documents/Git/machine_learning/goal_tree/titanic_2/med/pima.xls',\n sheet_name = \"a_classer\")\n\ndf_Y_test = pd.read_excel('C:/Users/jerem/Documents/Git/machine_learning/goal_tree/titanic_2/med/pima.xls',\n sheet_name = \"etiquette\")\n\n\nlb = LabelEncoder() # Copy and transform value (ex: Str to int)\n\n\nX_train = df_train[['pregnant', 'plasma', 'bodymass', 'pedigree', 'age']] # Get Features table\nX_test = df_test[['pregnant', 'plasma', 'bodymass', 'pedigree', 'age']] # Get Features table\n\n\ny_train = df_train[['diabete']]\ny_test_resp = df_Y_test[['diabete']]\n\n\ny_train = y_train.apply(lb.fit_transform)\ny_test_resp = y_test_resp.apply(lb.fit_transform)\n\n\n\ncustom_parameter = [\n## {'criterion':['entropy'],\n## 'max_depth':[i for i in range(0,150)],\n## 'max_features':[i for i in range(1, 5)],\n## 'random_state':[i for i in range(5, 10)]},\n\n {'criterion':['gini'],\n 'max_depth':[i for i in range(0,50)],\n 'max_features':[i for i in range(1, 5)],\n 'random_state':[i for i in range(5, 10)],\n 'n_estimators':[i for i in range(1, 100)]},\n]\n\n\ntree = GridSearchCV(RandomForestClassifier(bootstrap=True),\n param_grid = custom_parameter, n_jobs = -1)\n\n# Paramètre optimal\ntree.fit(X_train, y_train)\n\n\nprint(\"Meilleur score = %f, Meilleur paramètre = %s\" % (1. - tree.best_score_, tree.best_params_))\n\ny_pred = tree.best_estimator_.predict(X_test)\n\n\n\nprint (\"confusion: \" , confusion_matrix(y_test_resp, y_pred))\nprint( \"Accuracy : \", accuracy_score(y_test_resp, y_pred) * 100)\n\n\ndot_data = export_graphviz( # Create dot data\n tree.best_estimator_ , filled=True, rounded=True,\n feature_names= X_test.columns,\n out_file=None,\n)\n\ngraph = pydotplus.graph_from_dot_data(dot_data) # Create graph from dot data\ngraph.write_png('tree_diabete.png') # Write graph to PNG image\n","sub_path":"goal_tree/titanic_2/med/random_forest.py","file_name":"random_forest.py","file_ext":"py","file_size_in_byte":2743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"274108307","text":"#!/usr/bin/env python\nimport logging\nimport threading\nimport typing\n\nimport pymongo\nimport pymongo.collection\nimport pymongo.database\n\nfrom . import commons\n\nlogger = logging.getLogger(\"DB\")\n\n\nclass DBException(Exception):\n def __init__(self, *args):\n super().__init__(*args)\n\n\nclass DBManager:\n DB_NAME = \"mailpy-db\"\n CONDITIONS_COLLECTION = \"conditions\"\n GROUPS_COLLECTION = \"groups\"\n ENTRIES_COLLECTION = \"entries\"\n # @todo: Consider adding a USERS_COLLECTION = 'users' to reference users and emails\n\n def __init__(self, url: str = \"mongodb://localhost:27017/\"):\n self.url = url\n self.client: typing.Optional[pymongo.MongoClient] = None\n self.mailpy_db: typing.Optional[pymongo.database.Database] = None\n self.lock = threading.RLock()\n\n self.connect()\n\n def disconnect(self):\n \"\"\"Disconnect\"\"\"\n if self.client:\n self.client.close()\n\n def connect(self):\n \"\"\"Estabilish mongo connection\"\"\"\n self.client = pymongo.MongoClient(self.url)\n self.mailpy_db: pymongo.database.Database = self.client[DBManager.DB_NAME]\n\n def get_entries(self):\n \"\"\"Return all entries\"\"\"\n entries: pymongo.collection.Collection = self.mailpy_db[\n DBManager.ENTRIES_COLLECTION\n ]\n return [e for e in entries.find()]\n\n def create_entry(self, entry: commons.Entry):\n \"\"\"Create an entry\"\"\"\n if not self.mailpy_db:\n raise RuntimeError(\"Database not initialised\")\n\n if not entry.group:\n logger.warning(f\"Invalid group for entry {entry}\")\n return\n\n if not self.get_group(entry.group.name):\n self.create_group(entry.group)\n\n if not self.get_condition(entry.condition):\n logger.error(\n \"Failed to crate entry {entry}, condition not found at the database\"\n )\n\n entries: pymongo.collection.Collection = self.mailpy_db[\n DBManager.ENTRIES_COLLECTION\n ]\n\n logger.info(f\"insert {entry.as_dict()}\")\n result = entries.insert(entry.as_dict())\n logger.info(f\"Inserted entry {entry} id {result}\")\n\n def get_group(self, group_name: str) -> typing.Optional[str]:\n if not self.mailpy_db:\n raise RuntimeError(\"Database not initialised\")\n groups: pymongo.collection.Collection = self.mailpy_db[\n DBManager.GROUPS_COLLECTION\n ]\n return groups.find_one({\"_id\": group_name})\n\n def create_group(self, group: commons.Group):\n \"\"\"Create a group\"\"\"\n if not self.mailpy_db:\n raise RuntimeError(\"Database not initialised\")\n groups: pymongo.collection.Collection = self.mailpy_db[\n DBManager.GROUPS_COLLECTION\n ]\n\n if groups.find_one({\"name\": group.name}):\n logger.warning(f\"Group {group} already exists\")\n return\n\n result = groups.insert(group.as_dict())\n logger.info(f\"Inserted group {group} id {result}\")\n\n def get_condition(self, name: str):\n \"\"\"Get a condtion by name\"\"\"\n if not self.mailpy_db:\n raise RuntimeError(\"Database not initialised\")\n\n conditions: pymongo.collection.Collection = self.mailpy_db[\n DBManager.CONDITIONS_COLLECTION\n ]\n return conditions.find_one({\"name\": name})\n\n def initialize_conditions(self):\n \"\"\"Initialize the conditions collection using the supported ones from commons.Condition\"\"\"\n if not self.mailpy_db:\n raise RuntimeError(\"Database not initialised\")\n\n self.mailpy_db.drop_collection(DBManager.CONDITIONS_COLLECTION)\n\n conditions: pymongo.collection.Collection = self.mailpy_db[\n DBManager.CONDITIONS_COLLECTION\n ]\n result = conditions.insert_many(commons.Condition.get_conditions())\n\n logger.info(f\"Inserted {result.inserted_ids}\")\n","sub_path":"app/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":3917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"612562815","text":"import numpy as np\n\n\ndef euclidean_metrics(points, dim):\n \"\"\"\n Function calculates euclidean distance between points in n-dimensional space. Function created for\n datasets larger than 5000 rows. (It will be re-designed for parallel processing).\n :param points: numpy array with points' coordinates where each column indices new dimension and each row is\n a new coordinate set (point)\n :param dim: dimension of dataset (1 or more than 1)\n :return: distances_list - numpy array with euclidean distances between all pairs of points.\n \"\"\"\n distances_list = []\n if dim == 1:\n for val in points:\n distances_list.append(np.abs(points - val))\n else:\n for row in points:\n for col in range(0, len(row)):\n single_dist_col = (points[:, col] - row[col])**2\n if col == 0:\n multiple_distances_sum = single_dist_col\n else:\n multiple_distances_sum = multiple_distances_sum + single_dist_col\n distances_list.append(np.sqrt(multiple_distances_sum))\n return np.array(distances_list)\n\ndef calculate_distance(points_array):\n \"\"\"\n Function calculates euclidean distance between points in n-dimensional space.\n\n :param points_array: numpy array with points' coordinates where each column indices new dimension and each row is\n a new coordinate set (point)\n :return: distances - numpy array with euclidean distances between all pairs of points.\n \n IMPORTANT! If input array size has x rows (coordinates) then output array size is x(cols) by x(rows) \n and each row describes distances between coordinate from row(i) with all rows. \n The first column in row is a distance between coordinate(i) and coordinate(0), \n the second row is a distance between coordinate(i) and coordinate(1) and so on.\n \"\"\"\n\n try:\n number_of_cols = points_array.shape[1]\n except IndexError:\n number_of_cols = 1\n\n distances = euclidean_metrics(points_array, number_of_cols)\n\n return distances\n\ndef calculate_block_to_block_distance(area_block_1, area_block_2):\n \"\"\"\n Function calculates distance between two blocks based on how they are divided (into a population blocks)\n :param area_block_1: set of coordinates of each population block in the form:\n [\n [coordinate x 0, coordinate y 0, value 0],\n [...],\n [coordinate x n, coordinate y n, value n]\n ]\n :param area_block_2: the same set of coordinates as area_block_1\n :return distance: function return weighted block to block distance\n \n Equation: Dist(v_a, v_b) = 1 / (SUM_to(Pa), SUM_to(Pb) n(u_s) * n(u_si)) *\n * SUM_to(Pa), SUM_to(Pb) n(u_s) * n(u_si) ||u_s - u_si||\n where:\n Pa and Pb: number of points u_s and u_si used to discretize the two units v_a and v_b\n n(u_s) - population size in the cell u_s\n \"\"\"\n \n distances_list = []\n sum_pa_pb = 0\n distance = 0\n \n for a_row in area_block_1:\n for b_row in area_block_2:\n weight = a_row[-1] * b_row[-1]\n sum_pa_pb = sum_pa_pb + weight\n partial_distance = np.sqrt((a_row[0] - b_row[0])**2 + (a_row[1] - b_row[1])**2)\n distance = distance + weight * partial_distance\n distance = distance / sum_pa_pb\n return distance\n\ndef block_to_block_distances(areas, interpretation='dict'):\n \"\"\"\n Function returns distances between all blocks passed to it.\n Function has two parameters:\n :param areas: dictionary with areas (where each area has unique ID and key 'coordinates' with coordinates\n and values in the form [x, y, val]) or 3D list where each layer represents different area\n :param interpretation: 'dict' if areas are dictionary with multiple areas or list if list of coordinates\n is given as an input\n :return distances:\n \n if interporetation == 'dict':\n {\n 'unit 0 ID': {\n 'unit 0 ID': distance to unit 0,\n 'unit n ID': distance to unit n,\n }\n ,\n 'unit n ID': {\n 'unit 0 ID': distance to unit 0,\n 'unit n ID': distance to unit n,\n }\n ,\n 'unit z ID': {\n 'unit 0 ID': distance to unit 0,\n 'unit n ID': distance to unit n,\n }\n \n }\n \n if interpretation == 'list':\n [\n [d(coordinate 0 to coordinate 0), d(coordinate 0 to coordinate 1), d(coordinate 0 to coordinate n)],\n [d(coordinate 1 to coordinate 0), d(coordinate 1 to coordinate 1), d(coordinate 1 to coordinate n)],\n [d(coordinate n to coordinate 0), d(coordinate n to coordinate 1), d(coordinate n to coordinate n)],\n ]\n \n \"\"\"\n \n if interpretation == 'dict':\n print('Selected data: dict type') # Inform which type of data structure has been chosen\n distance_dicts = {}\n for key_a in areas.keys():\n distance_dicts[key_a] = {}\n for key_b in areas.keys():\n if key_a == key_b:\n distance_dicts[key_a][key_b] = 0\n else:\n block_1 = areas[key_a]['coordinates']\n block_2 = areas[key_b]['coordinates']\n distance = calculate_block_to_block_distance(block_1, block_2)\n distance_dicts[key_a][key_b] = distance\n return distance_dicts\n \n elif interpretation == 'list':\n print('Selected data: list of value lists type') # Inform which type of data structure has been chosen\n list_of_grouped_distances = []\n for i, layer_a in enumerate(areas):\n layer_x = []\n for j, layer_b in enumerate(areas):\n if i == j:\n distance = 0\n else:\n distance = calculate_block_to_block_distance(layer_a, layer_b)\n layer_x.append(distance)\n list_of_grouped_distances.append(layer_x)\n return list_of_grouped_distances\n \n else:\n print('Selected data type not available. You may choose dict or list type. Please look into a docstring.')\n\ndef centroid_blocks_distances(areas):\n \"\"\"\n Function returns distances between all blocks passed to it.\n Function has two parameters:\n :param areas: dictionary with areas (where each area has unique ID and key 'coordinates' with coordinates\n and values in the form [x, y, val]) or 3D list where each layer represents different area\n :param interpretation: 'dict' if areas are dictionary with multiple areas or list if list of coordinates\n is given as an input\n :return distances:\n {\n 'unit 0 ID': {\n 'unit 0 ID': distance to unit 0,\n 'unit n ID': distance to unit n,\n }\n ,\n 'unit n ID': {\n 'unit 0 ID': distance to unit 0,\n 'unit n ID': distance to unit n,\n }\n ,\n 'unit z ID': {\n 'unit 0 ID': distance to unit 0,\n 'unit n ID': distance to unit n,\n }\n \n }\n \n \"\"\"\n print('Centroid distances calculation: process starts')\n distance_dicts = {}\n for key_a in areas.keys():\n distance_dicts[key_a] = {}\n for key_b in areas.keys():\n if key_a == key_b:\n distance_dicts[key_a][key_b] = 0\n else:\n block_1_x = areas[key_a]['centroid_pos_x']\n block_2_x = areas[key_b]['centroid_pos_x']\n block_1_y = areas[key_a]['centroid_pos_y']\n block_2_y = areas[key_b]['centroid_pos_y']\n distance = (block_1_x - block_2_x)**2 + (block_1_y - block_2_y)**2\n distance = np.sqrt(distance)\n distance_dicts[key_a][key_b] = distance\n return distance_dicts\n","sub_path":"pyinterpolate/kriging/helper_functions/euclidean_distance.py","file_name":"euclidean_distance.py","file_ext":"py","file_size_in_byte":7794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"189345755","text":"from . import views\nfrom django.urls import path\n\nurlpatterns = [\n path('', views.index, name=\"main\"), # 主页\n path('epidemic_data/', views.epidemic_data, name='epidemic_data'),\n path('map/', views.map, name='map'),\n path('yi_baike/', views.yi_baike, name='yq_baike'),\n path('yq_ol/', views.yq_ol, name='yq_ol'),\n path('admin_new/', views.admin_new, name='admin_new'),\n path('register/', views.register, name='register'),\n path('sucessful/', views.sucessful, name='sucessful'),\n]\n","sub_path":"HMweb项目_基于Django框架/jhm_project/apps/疫情小报/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"531329952","text":"#!/usr/bin/env python3\n# system.py\nimport core\nimport proc\nfrom threading import Thread\nglobal proc\n\nbase_dir = \"root\"\nif base_dir == False:\n\tprint(\"STOP!\")\n\texit()\nsys = core.core(base_dir)\nproc = proc.proc()","sub_path":"system.py","file_name":"system.py","file_ext":"py","file_size_in_byte":209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"183234059","text":"from Bio.Blast import NCBIWWW\r\nimport os\r\nimport matplotlib.pyplot as plt\r\nfrom textwrap import wrap\r\nimport sys\r\nimport getopt\r\nimport matplotlib\r\nimport pandas as pd\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\ndef main(argv):\r\n input_path = ''\r\n # path of execution\r\n output_path = os.path.dirname(os.path.abspath(__file__))\r\n file = ''\r\n\r\n # Get all arguments given\r\n try:\r\n opts, args = getopt.getopt(argv, \"hi:o:\", [\"inputfile=\", \"outputfolder=\"])\r\n except getopt.GetoptError:\r\n print('rep_histogram.py -index -o ')\r\n sys.exit(2)\r\n\r\n for opt, arg in opts:\r\n if opt == '-h':\r\n print('rep_histogram.py -index -o ')\r\n sys.exit()\r\n elif opt in (\"-i\", \"--inputfile\"):\r\n if os.path.isabs(arg):\r\n file = os.path.basename(arg)\r\n input_path = os.path.dirname(arg)\r\n else:\r\n path = os.path.join(os.getcwd(), arg)\r\n file = os.path.basename(path)\r\n input_path = os.path.dirname(path)\r\n print('path: ' + path + ' file: ' + file + ' inputp: ' + input_path)\r\n elif opt in (\"-o\", \"--outputfolder\"):\r\n if os.path.isabs(arg):\r\n output_path = arg\r\n else:\r\n output_path = os.path.join(os.getcwd(), arg)\r\n # print('arg: ' + arg + ' outputp: ' + output_path)\r\n\r\n #print(f'Blast file: {file}')\r\n df = pd.read_csv(os.path.join(input_path, file),\r\n sep='\\t',\r\n names=['C1', 'C2', 'C3', 'C4', 'C5', 'C6', 'START', 'END', 'C7', 'C8', 'C9',\r\n 'C10'])\r\n\r\n max_length = 0\r\n for index, row in df.iterrows():\r\n #print(row['START'], row['END'])\r\n if row['END'] > max_length:\r\n max_length = row['END']\r\n print(max_length)\r\n canvas = np.zeros(max_length)\r\n\r\n for index, row in df.iterrows():\r\n for hit in range(row['START'], row['END']):\r\n canvas[hit] += 1\r\n print(canvas)\r\n\r\n plt.figure(figsize=(10, 10))\r\n plt.plot(np.arange(max_length), canvas)\r\n plt.title(\"\\n\".join(wrap('Blast significant profile of: ' + file, 60)))\r\n plt.xlabel('Repetitions length')\r\n plt.ylabel('Repetitions')\r\n #plt.show()\r\n plt.savefig(os.path.join(output_path, file + '_histogram.png'))\r\n\r\n '''\r\n Each plot in hist function is a subplot so we have to load them as a subplots() \r\n \r\n fig, ax = plt.subplots()\r\n df.hist(column='START', ax=ax, alpha=0.5)\r\n plt.show()\r\n fig.savefig(os.path.join(output_path, file + '_histogram.png'))\r\n #ax.plot()\r\n #ax.show()\r\n # print(df[[6]])\r\n '''\r\n\r\n\r\nmatplotlib.use('Agg')\r\n\r\nif __name__ == \"__main__\":\r\n print('RepHistogram v0.1')\r\n main(sys.argv[1:])\r\n","sub_path":"plot/rep_histogram.py","file_name":"rep_histogram.py","file_ext":"py","file_size_in_byte":2901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"574462182","text":"\n# only on schoolserver\n\n\n\nimport pickle\n\nfrom tkinter import *\nfrom tkinter import messagebox\nfrom tkinter import filedialog\n\nfrom threading import *\n\nfrom time import time\nfrom time import sleep\n\nfrom os.path import abspath\nfrom os import system\nfrom os import listdir\n\nfrom const.connection import managment\n\na = managment.ddd()\n#a = filedialog.askopenfile()\n#print(a)\n\na =str(time()).replace(\".\",\"\")\n\nprint (a)\nprint (int(a))\nprint(abspath(\".\"))\n\n\"/skole/tjener/home0/niko115/chat/data/chats/main.txt\"\n\"\"\"\nd = open(\"settings/settingssize.dmp\", \"wb\")\np = pickle.Pickler(d)\np.dump([1000,10000,10])\nd.close()\n\nd = open(\"settings/settingsuser.dmp\", \"wb\")\np = pickle.Pickler(d)\np.dump([\"User\",\"#000000\"])\nd.close()\n\"\"\"\n\n\n\"\"\"\nroot = Tk()\ns = StringVar()\nroot.title(\"Counting Seconds\")\nlabel = Label(root, fg=\"green\")\nlabel.grid()\na = Entry(root)\na.grid()\nlabel.config(background=\"#055\")\nroot.mainloop()\nprint(s.get())\n\"\"\"\n\nd = open(\"settings/settingsuser.dmp\", \"rb\")\np = pickle.Unpickler(d)\ns = p.load()\nprint(s)\nd.close()\n\nd = open(\"settings/settingssize.dmp\", \"rb\")\np = pickle.Unpickler(d)\ns = p.load()\nprint(s)\nd.close()\n\n\n\n\n\n\n\nclass image():\n\n def __init__(self,filenn):\n self.filen = filenn\n self.openpic = Tk(className=\" Bild\")\n\n if (len(self.filen)-5)<(self.filen.lower()).find(\".gif\"):\n canvasp = Canvas(master=self.openpic)\n canvasp.pack()\n\n pic = PhotoImage(master=self.openpic,file=self.filen)\n canvasp.create_image(30,30, anchor=NW, image=pic)\n\n\n self.openpic.mainloop()\n\n else:\n system(self.filen)\n\n\n\n\n\ndef func(filed):\n im = image(filed)\n return 0\n\n\n# class\n\nclass frame():\n\n def __init__(self):\n self.mainframe = Tk(className=\" Whatspy\")\n\n try:\n self.mainframe.wm_iconbitmap(\"Icon.ico\")\n except:\n pass\n\n self.color1 = \"\"\n self.name = \"\"\n\n self.size1 = 0\n self.size2 = 0\n self.size3 = 0\n\n self.time = ((listdir(\"settings/var\"))[0]).replace(\".txt\",\"\")\n\n self.owntime = str(self.time).replace(\".\",\"\")\n\n\n self.inits()\n self.initt()\n\n\n self.integer1 = IntVar()\n self.boolean1 = True\n\n self.string1 = StringVar()\n self.string2 = StringVar()\n\n self.string3 = StringVar()\n self.string4 = \"\"\n\n self.string2.set(\"Courier\")\n\n\n\n self.mainframe.M = Menu(self.mainframe)\n\n self.mainframe.M.m = Menu(self.mainframe.M, tearoff =0)\n\n self.mainframe.M.m.add_radiobutton(label = \"rot\", variable = self.string1, value = \"800\")\n self.mainframe.M.m.add_radiobutton(label = \"gruen\", variable = self.string1, value = \"080\")\n self.mainframe.M.m.add_radiobutton(label = \"blau\", variable = self.string1, value = \"008\")\n\n self.mainframe.M.m.m1 = Menu(self.mainframe.M.m,tearoff =0)\n\n self.mainframe.M.m.m1.add_radiobutton(label = \"weiß\", variable = self.integer1, value = 1)\n self.mainframe.M.m.m1.add_radiobutton(label = \"schwarz\", variable = self.integer1, value = 2)\n\n self.mainframe.M.m.add_cascade(menu = self.mainframe.M.m.m1, label = \"Helligkeit\")\n\n self.mainframe.M.add_cascade(menu = self.mainframe.M.m, label = \"Farbe\")\n\n\n self.mainframe.M.add_command(label= \"Aendern\", command = self.color)\n\n self.mainframe.M.add_separator()\n self.mainframe.M.add_command(label= \"Hochladen\", command = self.sendpic)\n self.mainframe.M.add_command(label= \"Oeffnen\", command = self.openpic)\n self.mainframe.M.add_separator()\n\n\n self.mainframe.M.add_command(label= \"Einstellungen\", command = self.settings)\n\n self.mainframe.M.add_command(label= \"Hilfe/Readme\", command = self.help)\n\n self.mainframe.config(menu = self.mainframe.M)\n\n\n\n\n\n self.mainframe.canvas1 = Canvas(master = self.mainframe ,width = \"10c\", height = \"10c\", background = \"#080\")\n self.mainframe.canvas1.pack(fill = BOTH, expand = 1)\n\n self.mainframe.canvas1.canvasinl = Label(master=self.mainframe.canvas1,background = \"#080\")\n self.mainframe.canvas1.canvasinl.grid(row=0 , column=0, padx=\"1m\")\n\n self.mainframe.canvas1.canvasinu = Label(master=self.mainframe.canvas1,background = \"#080\")\n self.mainframe.canvas1.canvasinu.grid(row=0 , column=1, pady=\"1m\")\n\n self.mainframe.canvas1.canvasinr = Label(master=self.mainframe.canvas1,background = \"#080\")\n self.mainframe.canvas1.canvasinr.grid(row=0 , column=3, padx=\"1m\")\n\n self.mainframe.canvas1.canvasinc = Label(master=self.mainframe.canvas1,background = \"#080\")\n self.mainframe.canvas1.canvasinc.grid(row=3 , column=2, pady=\"1m\")\n\n\n self.mainframe.canvas1.baryy = Scrollbar(master = self.mainframe.canvas1, orient=VERTICAL)\n self.mainframe.canvas1.baryy.grid(row=4 , column=2, sticky=\"NS\")\n\n self.mainframe.canvas1.barxx = Scrollbar(master = self.mainframe.canvas1, orient=HORIZONTAL)\n self.mainframe.canvas1.barxx.grid(row=5 , column=1, sticky=\"EW\")\n\n self.mainframe.canvas1.message = Text(master= self.mainframe.canvas1 ,yscrollcommand = self.mainframe.canvas1.baryy.set, xscrollcommand = self.mainframe.canvas1.barxx.set ,font=\"Courier\",relief = SUNKEN, height=3 ,width=70, wrap=NONE)\n\n self.mainframe.canvas1.baryy.config(command = self.mainframe.canvas1.message.yview)\n self.mainframe.canvas1.barxx.config(command = self.mainframe.canvas1.message.xview)\n self.mainframe.canvas1.message.grid(row=4 , column=1, sticky=\"E\")\n\n\n\n\n\n\n\n self.mainframe.canvas1.bary = Scrollbar(master = self.mainframe.canvas1, orient=VERTICAL)\n self.mainframe.canvas1.bary.grid(row=1 , column=2, sticky=\"NS\")\n\n self.mainframe.canvas1.barx = Scrollbar(master = self.mainframe.canvas1, orient=HORIZONTAL)\n self.mainframe.canvas1.barx.grid(row=2 , column=1, sticky=\"EW\")\n\n self.mainframe.canvas1.editor = Text(master= self.mainframe.canvas1 ,yscrollcommand = self.mainframe.canvas1.bary.set, xscrollcommand = self.mainframe.canvas1.barx.set ,font=\"Courier\",relief = SUNKEN, height=20 ,width=70, wrap=NONE)\n self.mainframe.canvas1.editor.config(state=DISABLED)\n\n self.mainframe.canvas1.bary.config(command = self.mainframe.canvas1.editor.yview)\n self.mainframe.canvas1.barx.config(command = self.mainframe.canvas1.editor.xview)\n self.mainframe.canvas1.editor.grid(row=1 , column=1, sticky=\"E\")\n\n\n\n self.mainframe.canvas1.Button1 = Button(master= self.mainframe.canvas1, text=\"Senden\", command= self.send)\n self.mainframe.canvas1.Button1.grid(row=6, column=1, pady=\"5m\")\n\n self.mainframe.canvas1.Checkbutton1 = Checkbutton(master= self.mainframe.canvas1, onvalue=\"Courier\" , offvalue=\"Arial\", command=self.stil ,indicatoron=False,variable=self.string2, textvariable=self.string2,width =6 )\n self.mainframe.canvas1.Checkbutton1.grid(row=6, column=1, pady=\"5m\", padx=\"5m\", sticky=W)\n\n\n\n self.askfile = {}\n self.askfile[\"initialdir\"] = abspath(\".\")+\"/data/picture\"\n self.askfile[\"title\"] = \" Bildwahl\"\n\n\n self.mainframe.protocol(\"WM_DELETE_WINDOW\", self.closewindow)\n\n self.mainframe.resizable(width=FALSE, height=FALSE)\n\n\n\n\n self.newthread = self.starttext(self.mainframe.canvas1.editor, self.size1)\n self.newthread.start()\n self.currentthread = self.currenttext(self.mainframe.canvas1.editor)\n self.currentthread.start()\n\n\n\n def closewindow(self):\n yesno = messagebox.askyesno(\" Beenden\",\"Wollen die den Chat wirklich beenden?\\nSind alle anderen Bildschirme geschlossen.\")\n if yesno:\n self.currentthread.setrun()\n self.currentthread = 0\n\n self.mainframe.destroy()\n #self.manager()\n return 0\n\n\n\n def inits(self):\n d = open(\"settings/settingssize.dmp\", \"rb\")\n p = pickle.Unpickler(d)\n s = p.load()\n d.close()\n\n self.size1 = s[0]\n self.size2 = s[1]\n self.size3 = s[2]\n return 0\n\n def initt(self):\n d = open(\"settings/settingsuser.dmp\", \"rb\")\n p = pickle.Unpickler(d)\n t = p.load()\n d.close()\n\n self.name = t[0]\n self.color1 = t[1]\n\n return 0\n\n def color(self):\n if self.string1.get() != \"\":\n self.s = \"#\" + str(self.string1.get())\n if self.integer1.get()==1 :\n self.s =self.s.replace(\"8\", \"C\")\n elif self.integer1.get()==2:\n self.s =self.s.replace(\"8\", \"4\")\n\n self.mainframe.canvas1.config(background = self.s)\n\n self.mainframe.canvas1.canvasinl.config(background = self.s)\n\n self.mainframe.canvas1.canvasinu.config(background = self.s)\n\n self.mainframe.canvas1.canvasinr.config(background = self.s)\n\n self.mainframe.canvas1.canvasinc.config(background = self.s)\n\n if self.integer1.get() != 0 and self.boolean1:\n self.mainframe.M.m.m1.add_radiobutton(label = \"neutral\", variable = self.integer1, value = 0)\n self.boolean1 = False\n elif self.integer1.get() == 0:\n self.mainframe.M.m.m1.delete(2)\n self.boolean1 = True\n\n\n\n\n\n def send(self):\n self.string4=self.mainframe.canvas1.message.get(1.0,END)\n managment.send(self.name,self.color1,self.string4)\n sleep(0.1)\n self.mainframe.canvas1.message.delete(1.0,END)\n return 0\n\n\n\n def sendpic(self):\n managment.send(self.name,self.color1,\"Sendet Bild\")\n\n filed = str(filedialog.askopenfilename(**(self.askfile)))\n if filed==\"\":\n return 0\n\n managment.sendpic(filed)\n\n return 0\n\n def openpic(self):\n filed = str(filedialog.askopenfilename(**(self.askfile)))#.replace(abspath(\".\").replace(\"\\\\\",\"/\"),\"\")\n #filed= filed[1:]\n\n if filed==\"\":\n return 0\n\n func(filed)\n\n return 0\n\n\n def settings(self):\n self.sett = Tk()\n self.sett.title(\" Einstellungen\")\n\n button1 = Button(self.sett, text=\"Speicher\", width=25, command=self.sizesettings)\n button1.pack()\n\n button2 = Button(self.sett, text=\"Benutzer\", width=25, command=self.usersettings)\n button2.pack()\n\n self.sett.mainloop()\n return 0\n\n def usersettings(self):\n\n self.sett.destroy()\n\n self.ustring1 = \"\"\n\n self.ustring2 = self.color1\n\n\n def userendbutton():\n\n d = open(\"settings/settingsuser.dmp\", \"wb\")\n p = pickle.Pickler(d)\n self.ustring1 = self.user.entry1.get()\n\n if self.ustring1 != self.name and self.ustring1 != \"\" and self.ustring1 != \" \":\n self.name = self.ustring1\n if self.ustring2 != self.color1 :\n if self.ustring2.find(\"#\")==-1:\n self.ustring2 = \"#000000\"\n self.color1 = self.ustring2\n p.dump([self.name,self.color1])\n d.close()\n\n self.user.destroy()\n\n\n self.user = Tk()\n self.user.title(\" Benutzereinstellungen\")\n label1 = Label(self.user, text=\"Name\", width=20)\n label2 = Label(self.user, text=\"Farbe\", width=20)\n label1.grid(row=0,column=0, pady=\"1m\")\n label2.grid(row=1,column=0, pady=\"1m\")\n self.user.entry1 = Entry(master=self.user, width=30)\n self.user.entry1.grid(row=0,column=1, pady=\"1m\")\n\n button1 = Button(self.user, text=\"Farbe erstellen\", width=30, command=self.colorbutton)\n button1.grid(row=1,column=1, pady=\"1m\")\n\n button1 = Button(self.user, text=\"Fertig\", width=30, command=userendbutton)\n button1.grid(row=2,column=1, pady=\"2m\")\n\n self.user.mainloop()\n return 0\n\n\n\n def sizesettings(self):\n\n self.sett.destroy()\n\n def sizeendbutton():\n try:\n d = open(\"settings/settingssize.dmp\", \"wb\")\n p = pickle.Pickler(d)\n if int(self.size.entry1.get())>100 and int(self.size.entry1.get())<1001:\n self.size1 = int(self.size.entry1.get())\n if int(self.size.entry2.get())>1000 and int(self.size.entry1.get())1:\n self.size3 = int(self.size.entry3.get())\n\n p.dump([self.size1,self.size2,self.size3])\n d.close()\n\n self.size.destroy()\n except:\n pass\n\n\n self.size = Tk()\n self.size.title(\" Speichereinstellungen\")\n\n label1 = Label(self.size, text=\"Anzahl der angezeigten Nachrichten\", width=40)\n label2 = Label(self.size, text=\"Anzahl der gespeicherten Nachrichten\", width=40)\n label3 = Label(self.size, text=\"Anzahl der gespeicherten Bilder\", width=40)\n label1.grid(row=0,column=0, pady=\"1m\")\n label2.grid(row=1,column=0, pady=\"1m\")\n label3.grid(row=2,column=0, pady=\"1m\")\n\n self.size.entry1 = Entry(master=self.size, width=30)\n self.size.entry1.grid(row=0,column=1, pady=\"1m\")\n self.size.entry2 = Entry(master=self.size, width=30)\n self.size.entry2.grid(row=1,column=1, pady=\"1m\")\n self.size.entry3 = Entry(master=self.size, width=30)\n self.size.entry3.grid(row=2,column=1, pady=\"1m\")\n\n self.size.entry1.insert(1,str(self.size1))\n self.size.entry2.insert(1,str(self.size2))\n self.size.entry3.insert(1,str(self.size3))\n\n button1 = Button(self.size, text=\"Fertig\", width=30, command=sizeendbutton)\n button1.grid(row=3,column=1, pady=\"2m\")\n\n self.size.mainloop()\n return 0\n\n\n\n\n\n def help(self):\n\n d = open(\"const/help.dmp\", \"rb\")\n p = pickle.Unpickler(d)\n s = p.load()\n d.close()\n helpme = Tk()\n helpme.title(\"Hilfe\")\n label1 = Label(master= helpme,text=s, font=(\"Arial\",11))\n label1.pack()\n helpme.mainloop()\n\n return 0\n\n\n\n def stil(self):\n\n if self.string2.get()==\"Courier\":\n\n self.mainframe.canvas1.editor.config(font=\"Courier\")\n self.mainframe.canvas1.message.config(font=\"Courier\")\n else:\n\n self.mainframe.canvas1.editor.config(font=\"Arial\")\n self.mainframe.canvas1.message.config(font=\"Arial\")\n\n\n def colorbutton(self):\n\n def end():\n self.ustring2 = self.var\n self.color1.destroy()\n\n\n\n self.var=\"#000000\"\n\n def change(event):\n try:\n show.config(background=\"#\"+str(hex(scale1.get())).lstrip(\"0x\").zfill(2)+str(hex(scale2.get())).lstrip(\"0x\").zfill(2)+str(hex(scale3.get())).lstrip(\"0x\").zfill(2))\n self.var=\"#\"+str(hex(scale1.get())).lstrip(\"0x\").zfill(2)+str(hex(scale2.get())).lstrip(\"0x\").zfill(2)+str(hex(scale3.get())).lstrip(\"0x\").zfill(2)\n except:\n pass\n\n self.color1 = Tk()\n self.color1.title(\" Farbenmixer\")\n scale1 = Scale(self.color1, orient=VERTICAL, label=\"rot\",from_=255, to =0, command=change)\n scale1.grid(row=0,column=0)\n\n scale2 = Scale(self.color1, orient=VERTICAL, label=\"gruen\",from_=255, to =0, command=change)\n scale2.grid(row=0,column=1)\n\n scale3 = Scale(self.color1, orient=VERTICAL, label=\"blau\",from_=255, to =0, command=change)\n scale3.grid(row=0,column=2)\n\n self.color1.bind_all(sequence=\"\", func=change)\n\n show = Canvas(self.color1, width=70,height=70, background=\"#000000\")\n show.grid(row=0,column=3)\n\n button1 = Button(self.color1, text=\"Fertig\", width=10, command=end)\n button1.grid(row=1, column=3)\n\n\n self.color1.mainloop()\n return 0\n\n class currenttext(Thread):\n\n def __init__(self, t):\n Thread.__init__(self)\n self.runvar = True\n self.configtext = t\n self.filenown = \"settings/var\"\n\n def run(self):\n\n owntime = str(time()).replace(\".\",\"\")\n sleep(2.5)\n\n var=0\n while self.runvar:\n\n sleep(0.5)\n try:\n othertime = ((listdir(self.filenown))[0]).replace(\".txt\",\"\")\n except:\n continue\n\n if len(othertime)<15:\n othertime = othertime + \"0\"\n\n if len(owntime)<15:\n owntime = owntime + \"0\"\n\n\n\n #if not(int(owntime)self.size:\n del list[self.size::]\n\n var=0\n self.configtext.config(state=NORMAL)\n for c in list:\n c.replace(\"\\n\",\"\")\n r = eval(c)\n argument1 = r[0]\n argument2 = r[2]\n color = r[1]\n\n\n connection = \"\\n\" + argument1 + \": \" + argument2\n\n self.configtext.insert(\"1.0\",connection)\n #end = str(int(float(self.configtext.index(\"end\")))-2) + \".\"\n\n length1 = \"2.\" + \"0\"\n length2 = \"2.\" + str(len(argument1))\n\n\n\n #self.configtext.configure(font=\"Arial\")\n self.configtext.tag_add(\"usercolor\" + str(var), length1,length2)\n self.configtext.tag_configure(\"usercolor\" + str(var), foreground=color)\n\n var +=1\n\n #self.configtext.mark_set(\"insert\", \"16.0\")\n\n self.configtext.config(state=DISABLED)\n\n\n return 0\n\n\n\n def gettime(self):\n return self.owntime\n\n def settime(self,timee):\n self.owntime = timee\n\n\n def mainlooop(self):\n\n self.mainframe.mainloop()\n\nclass background(Thread):\n\n def __init__(self):\n Thread.__init__(self)\n self.action = 1\n self.boo = True\n self.filen = \"/skole/tjener/home0/niko115/chat/data/var\"\n #self.filen = \"I:/002_Befehlslisten/chat/structur/chat/data/var\"\n self.filenown = \"settings/var/\"\n\n\n def run(self):\n\n sleep(1.5)\n if self.action ==1:\n while self.boo:\n #try:\n owntime = window.gettime()\n othertime = ((listdir(self.filen))[0]).replace(\".txt\",\"\")\n\n\n\n if len(othertime)<15:\n othertime = othertime + \"0\"\n\n if len(owntime)<15:\n owntime = owntime + \"0\"\n\n if int(owntime)\",\"exec\")\n#exec(code)\n\n\n'''\nif self.o in listdir():\n self.ask= messagebox.askyesno(\"Überschreibungswarnung\",\"Datei existiert bereits!!!\\nWollen sie sie überschreiben?\")\n if not self.ask:\n return 0\n\n'''\n","sub_path":"newframe_win.py","file_name":"newframe_win.py","file_ext":"py","file_size_in_byte":22507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"321408301","text":"#!/usr/bin/python\n################################################################################\n# CONTROLLER MANAGER\n#\n#\n# 07/15/2015 Original construction\n# 09/16/2015 Integrate user and group tables\n# 11/30/2015 Added key bindings to search entry widgets.\n# 01/11/2016 Rewrote to use new class structure and selection GUI.\n################################################################################\n\nimport traceback\n\nfrom time import time\nfrom Tkinter import *\n\nfrom .selection_gui import SelectionGUI\nfrom ..db.logger import add_message\nfrom .permission_gui import PermissionGUI\nfrom ..db.controller import (get_readable_uuids_names as get_readable_controller_uuids_names, \\\n add_controller, \\\n del_controller, \\\n get_controller, \\\n set_controller, \\\n copy_controller)\nfrom ..db.procedure import get_executable_uuids_names as get_executable_procedure_uuids_names\nfrom ..db.host import (get_executable_uuids_names as get_executable_host_uuids_names)\n\nclass ControllerManager:\n def __populate_controllers(self, event = None):\n try:\n self.__controller_lb.delete(0, last = END)\n self.__controller_lb_to_uuid = {}\n \n for controller_uuid, controller_name in get_readable_controller_uuids_names(self.__current_user_uuid):\n lb_name = \"{0} ({1})\".format(controller_name, controller_uuid[0:8])\n self.__controller_lb_to_uuid[lb_name] = controller_uuid\n self.__controller_lb.insert(END, lb_name)\n \n pairs = {}\n for host_uuid, host_name, host in get_executable_host_uuids_names(self.__current_user_uuid):\n pairs[host_uuid] = host_name\n self.__host_selection.set_available(pairs)\n \n pairs = {}\n for procedure_uuid, procedure_name in get_executable_procedure_uuids_names(self.__current_user_uuid):\n pairs[procedure_uuid] = procedure_name\n self.__procedure_selection.set_available(pairs)\n \n self.__permissions.populate()\n \n self.__configure_controls()\n except Exception:\n add_message(time(), traceback.format_exc())\n \n def __load_controller(self, event = None):\n try:\n if self.__current_controller_uuid:\n self.__save_controller()\n \n if len(self.__controller_lb.curselection()) == 1:\n self.__current_controller_uuid = self.__controller_lb_to_uuid[self.__controller_lb.get(self.__controller_lb.curselection())]\n \n if self.__current_controller_uuid:\n name, req_host_uuids, req_procedure_uuids, mode, owner = get_controller(self.__current_controller_uuid, self.__current_user_uuid)\n \n self.__controller_name_entry.delete(0, END)\n self.__controller_name_entry.insert(0, str(name))\n \n self.__host_selection.deselect_all()\n for host_uuid in req_host_uuids:\n self.__host_selection.select(host_uuid)\n \n self.__procedure_selection.deselect_all()\n for procedure_uuid in req_procedure_uuids:\n self.__procedure_selection.select(procedure_uuid)\n \n self.__permissions.set_mode(mode)\n self.__permissions.set_owner(owner)\n \n self.__configure_controls()\n except Exception:\n add_message(time(), traceback.format_exc())\n \n def __auto_refresh(self, event = None):\n self.__populate_controllers()\n self.__load_controller()\n \n def __save_controller(self):\n try:\n selected_host_uuids = []\n for host_uuid, host_name in self.__host_selection.get_selected().iteritems():\n selected_host_uuids.append(host_uuid)\n \n selected_procedure_uuids = []\n for procedure_uuid, procedure_name in self.__procedure_selection.get_selected().iteritems():\n selected_procedure_uuids.append(procedure_uuid)\n \n set_controller(self.__current_controller_uuid, \\\n self.__controller_name_entry.get(), \\\n selected_host_uuids, \\\n selected_procedure_uuids, \\\n self.__permissions.get_mode(), \\\n self.__permissions.get_owner(), \\\n user_uuid = None)\n except Exception:\n add_message(time(), traceback.format_exc())\n \n def __auto_save(self, event = None):\n if self.__current_controller_uuid:\n self.__save_controller()\n \n def __new_controller(self):\n try:\n add_controller(None, name = \"--NEW CONTROLLER\", user_uuid = self.__current_user_uuid)\n self.__populate_controllers()\n self.__configure_controls()\n except Exception:\n add_message(time(), traceback.format_exc())\n \n def __copy_controller(self):\n try:\n copy_controller(self.__current_controller_uuid, user_uuid = self.__current_user_uuid)\n self.__populate_controllers()\n self.__configure_controls()\n except Exception:\n add_message(time(), traceback.format_exc())\n \n def __delete_controller(self):\n try:\n del_controller(self.__current_controller_uuid, self.__current_user_uuid)\n self.__current_controller_uuid = None\n self.__populate_controllers()\n self.__configure_controls()\n except Exception:\n add_message(time(), traceback.format_exc())\n \n def __configure_controls(self, event = None):\n if self.__current_controller_uuid:\n self.__controller_delete_btn.configure(state = NORMAL)\n self.__controller_copy_btn.configure(state = NORMAL)\n self.__controller_save_btn.configure(state = NORMAL)\n else:\n self.__controller_delete_btn.configure(state = DISABLED)\n self.__controller_copy_btn.configure(state = DISABLED)\n self.__controller_save_btn.configure(state = DISABLED)\n \n def close(self):\n if self.__current_controller_uuid:\n self.__save_controller()\n self.__master.destroy()\n \n def __init__(self, master, user_uuid):\n self.__master = master\n self.__master.bind(\"\", self.__auto_save)\n self.__master.bind(\"\", self.__auto_refresh)\n Grid.rowconfigure(self.__master, 0, weight = 1)\n Grid.columnconfigure(self.__master, 0, weight = 1)\n Grid.columnconfigure(self.__master, 1, weight = 1)\n \n self.__current_controller_uuid = None\n self.__current_user_uuid = user_uuid\n \n #### CONTROLLER FRAME #################################\n controller_frame = LabelFrame(self.__master, text = \"Controller\", padx = 5, pady = 5)\n controller_frame.grid(column = 1, columnspan = 2, row = 0, rowspan = 1, sticky = N + S + E + W) \n Grid.rowconfigure(controller_frame, 1, weight = 1)\n Grid.rowconfigure(controller_frame, 2, weight = 1)\n Grid.columnconfigure(controller_frame, 0, weight = 1)\n \n self.__controller_name_entry = Entry(controller_frame)\n self.__controller_name_entry.grid(column = 0, columnspan = 1, row = 0, rowspan = 1, sticky = N + S + E + W)\n \n #### CONTROLLER\\PROCEDURES FRAME ######################\n procedures_frame = LabelFrame(controller_frame, text = \"Procedures\", padx = 5, pady = 5)\n procedures_frame.grid(column = 0, columnspan = 1, row = 1, rowspan = 1, sticky = N + S + E + W) \n self.__procedure_selection = SelectionGUI(procedures_frame)\n \n #### CONTROLLER\\HOSTS FRAME ###########################\n hosts_frame = LabelFrame(controller_frame, text = \"Hosts\", padx = 5, pady = 5)\n hosts_frame.grid(column = 0, columnspan = 1, row = 2, rowspan = 1, sticky = N + S + E + W) \n self.__host_selection = SelectionGUI(hosts_frame)\n \n #### CONTROLLERS\\PERMS FRAME ###########################\n perms_frame = LabelFrame(controller_frame, text = \"Permissions\", padx = 5, pady = 5)\n perms_frame.grid(column = 0, columnspan = 1, row = 3, rowspan = 1, sticky = N + S + E + W) \n self.__permissions = PermissionGUI(perms_frame)\n \n #### CONTROLLERS FRAME ################################\n controllers_frame = LabelFrame(self.__master, text = \"Controllers\", padx = 5, pady = 5)\n controllers_frame.grid(column = 0, columnspan = 1, row = 0, rowspan = 1, sticky = N + S + E + W) \n Grid.columnconfigure(controllers_frame, 0, weight = 1)\n Grid.rowconfigure(controllers_frame, 1, weight = 1)\n\n controller_scrollbar = Scrollbar(controllers_frame)\n controller_scrollbar.grid(column = 1, columnspan = 1, row = 1, rowspan = 1, sticky = N + S + E + W) \n \n self.__controller_lb = Listbox(controllers_frame, selectmode = SINGLE, yscrollcommand = controller_scrollbar.set, width = 32)\n self.__controller_lb.bind('<>', self.__load_controller)\n self.__controller_lb.grid(column = 0, columnspan = 1, row = 1, rowspan = 1, sticky = N + S + E + W) \n \n controller_scrollbar.config(command = self.__controller_lb.yview)\n \n #### CONTROLLERS FRAME\\BUTTON FRAME ###################\n controller_button_frame = Frame(controllers_frame)\n controller_button_frame.grid(column = 0, columnspan = 2, row = 0, rowspan = 1, sticky = N + S + E + W) \n Grid.columnconfigure(controller_button_frame, 0, weight = 1)\n Grid.columnconfigure(controller_button_frame, 1, weight = 1)\n Grid.columnconfigure(controller_button_frame, 2, weight = 1)\n Grid.columnconfigure(controller_button_frame, 3, weight = 1)\n Grid.columnconfigure(controller_button_frame, 4, weight = 1)\n \n self.__controller_new_btn = Button(controller_button_frame, text = \"NEW\", command = self.__new_controller)\n self.__controller_new_btn.grid(column = 0, columnspan = 1, row = 0, rowspan = 1, sticky = N + S + E + W)\n \n self.__controller_copy_btn = Button(controller_button_frame, text = \"COPY\", state = DISABLED, command = self.__copy_controller)\n self.__controller_copy_btn.grid(column = 1, columnspan = 1, row = 0, rowspan = 1, sticky = N + S + E + W)\n \n self.__controller_delete_btn = Button(controller_button_frame, text = \"DELETE\", state = DISABLED, command = self.__delete_controller)\n self.__controller_delete_btn.grid(column = 2, columnspan = 1, row = 0, rowspan = 1, sticky = N + S + E + W)\n \n self.__controller_save_btn = Button(controller_button_frame, text = \"SAVE\", state = DISABLED, command = self.__save_controller)\n self.__controller_save_btn.grid(column = 3, columnspan = 1, row = 0, rowspan = 1, sticky = N + S + E + W)\n \n self.__controller_refresh_btn = Button(controller_button_frame, text = \"REFRESH\", command = self.__populate_controllers)\n self.__controller_refresh_btn.grid(column = 4, columnspan = 1, row = 0, rowspan = 1, sticky = N + S + E + W)\n \n self.__populate_controllers()","sub_path":"valarie/gui/controller_manager.py","file_name":"controller_manager.py","file_ext":"py","file_size_in_byte":11473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"411656785","text":"import sqlite3\n\ndef insertTable(county, arg1, arg2, arg3, arg4, arg5, arg6):\n try:\n db = sqlite3.connect('NewYorkCovidDatabase.db')\n cursor = db.cursor()\n cursor.execute(\"INSERT INTO {} VALUES('\".format(self.county)\n + self.testDate +\n \"', '\" + self.id +\n \"', '\" + self.newPositives +\n \"', '\" + self.cummulativeNumberOfPositives +\n \"', '\" + self.totalNumberOfTestsPerformed +\n \"', '\" + self.cummulativeNumberOfTestsPerformed +\n \"', DATETIME('now', 'localtime'))\")\n except Exception as E:\n return E\n finally:\n cursor.close()","sub_path":"venv/insert.py","file_name":"insert.py","file_ext":"py","file_size_in_byte":784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"219403355","text":"from single import julia_single\nfrom parallel import julia_parallel\nimport time\n\nresolution = 50000\nc = (0.322+0.05j)\n# single\nstart = time.time()\n#jl_single = julia_single.calc_julia(resolution, c)\nend = time.time()\nsingle_time=end-start\nprint(\"single elapsed =\", single_time)\n# parallel\nstart = time.time()\njl_parallel = julia_parallel.calc_julia(resolution, c)\nend = time.time()\nparallel_time=end-start\nprint(\"parallel elapsed =\", parallel_time)\n\nprint(\"single/parallel =\",single_time/parallel_time)\n\nassert (jl_single == jl_parallel).all()\n\nfrom matplotlib import pyplot as plt \nimport numpy as np\nplt.imshow(np.log(jl_single))\nplt.show()","sub_path":"cythonTest/calcJulia/compare_res.py","file_name":"compare_res.py","file_ext":"py","file_size_in_byte":642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"7210414","text":"#!/usr/bin/env python3\n\n\"\"\"\nFractionAM converts atom fractions to mass fractions\nand mass fractions to atom fractions. Input is a \nsingle string with MCNP style fractions.\n\"\"\"\n\n__author__ = \"Paul Mendoza\"\n__copyright__ = \"Copyright 2016, Planet Earth\"\n__credits__ = [\"Sunil Chirayath\",\n \"Charles Folden\",\n \"Jeremy Conlin\"]\n__license__ = \"GPL\"\n__version__ = \"1.0.1\"\n__maintainer__ = \"Paul Mendoza\"\n__email__ = \"paul.m.mendoza@gmail.com\"\n__status__ = \"Production\"\n\n################################################################\n##################### Import packages ##########################\n################################################################\n\nimport numpy as np\nfrom scipy.stats import beta\nfrom scipy import interpolate\nfrom scipy import integrate\nfrom scipy.integrate import trapz\n\nimport matplotlib.pyplot as plt\nplt.rcParams[\"font.family\"] = \"monospace\"\nimport matplotlib\nmatplotlib.rc('text',usetex=True)\nmatplotlib.rcParams['text.latex.preamble']=[r\"\\usepackage{amsmath}\"]\n\n\n################################################################\n######################### Functions ############################\n################################################################\n\n\ndef BuildA(v,D,w,dt,dx,NX):\n #i-1\n a=(-v/dx-D/pow(dx,2))\n #i\n b=(1/dt)+(v/dx)+2*D/pow(dx,2)+w\n #i+1\n c=(-D/pow(dx,2))\n \n A = np.zeros([NX,NX])\n \n for i in range(0,NX):\n if (i == 0):\n A[i,i] = b\n A[i,1] = c\n elif(i==(NX-1)):\n A[i,i-1] = a\n A[i,i] = b\n else: \n A[i,i-1] = a\n A[i,i] = b\n A[i,i+1] = c\n\n #Boundary conditions\n A[0,NX-1] = A[0,0]\n A[NX-1,0] = A[NX-1,NX-1]\n return(A)\n\ndef FindIndex(list,item):\n idx = (np.abs(arr - v)).argmin()\n\n\ndef Integrate(u,xmin,xmax,x,t):\n\n x_low=np.abs(x-xmin).argmin()\n x_high=np.abs(x-xmax).argmin()\n\n \n r=u[x_low:x_high+1,:]\n\n IntegratedOverTime=np.zeros([x_high+1-x_low])\n\n \n for i in range(0,x_high+1-x_low):\n IntegratedOverTime[i]=np.trapz(r[i,:],t)\n\n IntTimeSpace=np.trapz(IntegratedOverTime,x[x_low:x_high+1])\n \n return(IntTimeSpace)\n\ndef SolveQoI(NX,Nt,x,t,A,dt,w):\n #Build Matrix with solutions\n u=np.zeros([NX,Nt])\n \n for i in range(0,NX):\n if x[i]<=2.5:\n u[i,0]=1\n \n #Solve the system\n for i in range(1,len(t)):\n u[:,i] = np.linalg.solve(A,u[:,i-1]*(1/dt))\n\n \n #Integrate the system\n Integral=Integrate(u,5,6,x,t)\n RXNRate=Integral*w\n return(RXNRate)\n\n \ndef Plot(x,y,Label,fig,ax,ColorStyle,Varied,Scaled):\n \n\n ax.plot(x,y,ColorStyle,linewidth=2.0,label=Label,\n markersize=8)\n\n if Scaled:\n yLabel=r'$\\text{Scaled Sensitivity Coeff}|_i=\\left.\\mu_i\\frac{\\delta\\text{QoI}}{\\delta\\theta_i}\\right|_{\\bar{\\theta}}$'\n else:\n yLabel=r'$\\text{Sensitivity Index}|_i=\\left.\\sigma_i\\frac{\\delta\\text{QoI}}{\\delta\\theta_i}\\right|_{\\bar{\\theta}}$'\n \n ax.set_xlabel(r'$\\Delta$'+Varied,fontsize=18)\n ax.set_ylabel(yLabel,fontsize=16)\n #ax.yaxis.labelpad=55\n \n ax.xaxis.set_tick_params(labelsize=14)\n ax.yaxis.set_tick_params(labelsize=14)\n \n ax.grid(alpha=0.8,color='black',linestyle='dotted')\n ax.grid(alpha=0.8,color='black',linestyle='dotted')\n \n return(fig,ax)\n","sub_path":"Assignments/Homework3/Problem3_long/Functions.py","file_name":"Functions.py","file_ext":"py","file_size_in_byte":3368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"73142058","text":"\"\"\"\nThis is a module as well as a python program (script) for getting nearest words in a pre-trained word2vec model.\n\nUsage as a script:\n Analogy task example:\n\n $ python use_word2vec.py --logdir=models/ko_twt --tagger=twt --k=10 -a '서울' '한국' '하노이'\n\n Run\n\n $ python use_word2vec.py -h\n\n on your terminal to display options and quit.\n\nUsage as a module:\n\n Import TrainedWord2Vec object to your python program.\n\n Example:\n\n from use_word2vec import TrainedWord2Vec\n\n model = TrainedWord2Vec('models/ko_twt', 'twt')\n\n print(model.get_nearby('그릇'))\n print(model.get_analogy('긍정', '부정', '좋은'))\n\"\"\"\n\nimport os\nimport argparse\nfrom collections import defaultdict\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom konlpy.tag import Mecab, Twitter\n\n\nparser = argparse.ArgumentParser()\n\nparser.add_argument('--logdir',\n help=\"Path to directory containing model checkpoint files\",\n default=\"models/ko_twt\")\n\nparser.add_argument('--tagger',\n help=\"Specify POS tagger with which the model in --logdir was trained.\",\n default=None)\n\nparser.add_argument('-f', '--four', action='count',\n help=\"Get top 4 nearest words instead of 1. Applies to both nearby and \")\n\nparser.add_argument('-k', '--k', type=int, default=20,\n help='k for k nearest words')\n\nnearby = parser.add_mutually_exclusive_group(required=True)\n\nnearby.add_argument('-w', '--words', nargs='+',\n help=\"List of words whose k nearest words you want. If not POS-tagged, --tagger will be used.\")\n\nnearby.add_argument('-a', '--analogy_words', nargs=3, metavar=('w0', 'w1', 'w2'),\n help=\"[w0 w1 w2] as in w0:w1 = w2:w3. If not POS-tagged, --tagger will be used.\")\n\n\nclass TrainedWord2Vec:\n\n def __init__(self, logdir, tagger='mcb'):\n # Load word2vec custom TensorFlow op\n word2vec = tf.load_op_library(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'word2vec_ops.so'))\n\n checkpoint_meta = \"\"\n embedding_metadata = \"\"\n\n # Get checkpoint's .meta and metadata.tsv paths\n for file in os.listdir(logdir):\n if file.endswith(\".meta\"):\n checkpoint_meta = os.path.join(os.path.dirname(os.path.realpath(__file__)), os.path.join(logdir, file))\n if file=='metadata.tsv':\n embedding_metadata = os.path.join(os.path.dirname(os.path.realpath(__file__)), os.path.join(logdir, file))\n\n\n # Load list of words and word:id dict\n id2word = []\n with open(embedding_metadata, mode='r', encoding='utf-8') as fp:\n for i, line in enumerate(fp):\n if i == 0:\n continue\n word, freq = line.strip().split(\"\\t\")\n id2word.append(word)\n\n word2id = {}\n for i in range(len(id2word)):\n word2id[id2word[i]] = i\n\n self._id2word = id2word\n self._word2id = word2id\n\n # Load pretrained word2vec model (embeddings)\n saver = tf.train.import_meta_graph(checkpoint_meta)\n\n # Load graph\n self._graph = tf.get_default_graph()\n\n # Load embeddings tensor\n self._w_in = self._graph.get_tensor_by_name('w_in:0')\n self._build_eval_graph()\n\n self._session = tf.Session()\n saver.restore(self._session, checkpoint_meta[:-5])\n\n self._tagger = Twitter() if tagger=='twt' else Mecab()\n\n def _pos_tag(self, words):\n for i, word in enumerate(words):\n if '/' not in word:\n words[i] = \"/\".join(self._tagger.pos(word)[0])\n return words\n\n def _build_eval_graph(self):\n normalized_emb = tf.nn.l2_normalize(self._w_in, 1) # compute l2-normalized embedding\n\n analogy_a = tf.placeholder(dtype=tf.int32) # [N]\n analogy_b = tf.placeholder(dtype=tf.int32) # [N]\n analogy_c = tf.placeholder(dtype=tf.int32) # [N]\n\n a_emb = tf.gather(normalized_emb, analogy_a) # a's embs\n b_emb = tf.gather(normalized_emb, analogy_b) # b's embs\n c_emb = tf.gather(normalized_emb, analogy_c) # c's embs\n\n target = c_emb + (b_emb - a_emb)\n\n # Compute cosine distance between each pair of target and vocab.\n # dist has shape [N, vocab_size].\n dist = tf.matmul(target, normalized_emb, transpose_b=True)\n\n # For each question (row in dist), find the top 4 words.\n _, pred_idx = tf.nn.top_k(dist, 4)\n\n # measure = tf.placeholder_with_default('cosine', dtype=tf.string)\n nearby_word = tf.placeholder(dtype=tf.int32) # word id (index) in self._word2id\n nearby_emb = tf.gather(normalized_emb, nearby_word) # retrieve embedding for word\n nearby_dist = tf.matmul(nearby_emb, normalized_emb, transpose_b=True) #if measure=='cosine' else tf.reduce_sum((nearby_emb-nemb)**2, axis=0)\n nearby_val, nearby_idx = tf.nn.top_k(nearby_dist, min(1000, len(self._id2word)))\n\n # Nodes in the construct graph which are used by training and\n # evaluation to run/feed/fetch.\n self._analogy_a = analogy_a\n self._analogy_b = analogy_b\n self._analogy_c = analogy_c\n self._analogy_pred_idx = pred_idx\n self._nearby_word = nearby_word\n self._nearby_val = nearby_val\n self._nearby_idx = nearby_idx\n\n def _predict(self, analogy):\n \"\"\"Predict the top 4 answers for analogy questions.\"\"\"\n idx, = self._session.run([self._analogy_pred_idx], {\n self._analogy_a: analogy[:, 0],\n self._analogy_b: analogy[:, 1],\n self._analogy_c: analogy[:, 2]\n })\n return idx\n\n\n def nearby(self, words, k=20):\n \"\"\"Prints out nearby words given a list of words.\"\"\"\n\n neighbors = self.get_nearby(words, k)\n\n for word in neighbors:\n print(\"\\n{}\\n=====================================\".format(word))\n for (neighbor, distance) in neighbors[word]:\n print(\"{:20}\\t{:6.4f}\".format(neighbor, distance))\n\n def get_nearby(self, words, k=20):\n \"\"\"Given a word, return nearby words and corresponding cosine similarity.\n Given a list of words, return a dict of such results.\n \"\"\"\n if type(words)==str:\n words = self._pos_tag([words])\n else:\n words = self._pos_tag(words)\n ids = np.array([self._word2id.get(x, 0) for x in words])\n\n vals, idx = self._session.run([self._nearby_val, self._nearby_idx], {self._nearby_word: ids})\n\n output = defaultdict(list)\n for i in range(len(words)):\n for (neighbor, distance) in zip(idx[i, :k], vals[i, :k]):\n output[words[i]].append((self._id2word[neighbor], distance))\n\n return output\n\n def analogy(self, w0, w1, w2, get_top_4=False):\n \"\"\"Predict word w3 as in w0:w1 vs w2:w3.\"\"\"\n print(self.get_analogy(w0, w1, w2, get_top_4))\n\n def get_analogy(self, w0, w1, w2, get_top_4=False):\n \"\"\"Return word w3 as in w0:w1 vs w2:w3. Return top 4 such candidates if get_top_4=True.\"\"\"\n w0, w1, w2 = self._pos_tag([w0, w1, w2])\n wid = np.array([[self._word2id.get(w, 0) for w in [w0, w1, w2]]])\n idx = self._predict(wid)\n\n top_4 = [self._id2word[i] for i in idx[0, :]]\n\n if get_top_4:\n return top_4\n\n for c in top_4:\n if c not in [w0, w1, w2]:\n return c\n\n return \"unknown\"\n\ndef main(opts):\n model = TrainedWord2Vec(opts.logdir, opts.tagger)\n if opts.words:\n model.nearby(opts.words, opts.k)\n elif opts.analogy_words:\n model.analogy(*opts.analogy_words, opts.four)\n\nif __name__=='__main__':\n main(parser.parse_args())\n","sub_path":"use_word2vec.py","file_name":"use_word2vec.py","file_ext":"py","file_size_in_byte":7810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"370768706","text":"import os\nimport cv2\nimport gym\nimport sys\nimport random\nimport itertools\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom gym.wrappers import Monitor\nfrom collections import namedtuple\n\nenv = gym.envs.make('Breakout-v0')\n\nVALID_ACTIONS = [0, 1, 2, 3]\n\nclass StateProcessor():\n def __init__(self):\n with tf.variable_scope('state_processor'):\n self.input_state = tf.placeholder(shape=[210, 160, 3], dtype=tf.uint8)\n self.output = tf.image.rgb_to_grayscale(self.input_state)\n self.output = tf.image.crop_to_bounding_box(self.output, 34, 0, 160, 160)\n self.output = tf.image.resize_images(\n self.output, [84, 84], method=tf.image.ResizeMethod.NEAREST_NEIGHBOR)\n self.output = tf.squeeze(self.output)\n\n\n def process(self, sess, state):\n return sess.run(self.output, {self.input_state: state})\n\nclass Estimator():\n def __init__(self, scope='estimator', summaries_dir=None):\n self.scope = scope\n self.summary_writer = None\n\n with tf.variable_scope(scope):\n self._build_model()\n\n if summaries_dir:\n summary_dir = os.path.join(summaries_dir, 'summaries_{}'.format(scope))\n if not os.path.exists(summary_dir):\n os.makedirs(summary_dir)\n self.summary_writer = tf.summary.FileWriter(summary_dir)\n\n def _build_model(self):\n self.X_pl = tf.placeholder(shape=[None, 84, 84, 4], dtype=tf.uint8, name='X')\n self.y_pl = tf.placeholder(shape=[None], dtype=tf.float32, name='y')\n self.actions_pl = tf.placeholder(shape=[None], dtype=tf.int32, name='actions')\n\n X = tf.to_float(self.X_pl) / 255.0\n batch_size = tf.shape(self.X_pl)[0]\n\n conv1 = tf.contrib.layers.conv2d(X, 32, 8, 4, activation_fn=tf.nn.relu)\n conv2 = tf.contrib.layers.conv2d(conv1, 64, 4, 2, activation_fn=tf.nn.relu)\n conv3 = tf.contrib.layers.conv2d(conv2, 64, 3, 1, activation_fn=tf.nn.relu)\n\n flattened = tf.contrib.layers.flatten(conv3)\n fc1 = tf.contrib.layers.fully_connected(flattened, 512)\n self.predictions = tf.contrib.layers.fully_connected(fc1, len(VALID_ACTIONS))\n\n gather_indices = tf.range(batch_size) * tf.shape(self.predictions)[1] + self.actions_pl\n self.action_predictions = tf.gather(tf.reshape(self.predictions, [-1]), gather_indices)\n\n self.losses = tf.squared_difference(self.y_pl, self.action_predictions)\n self.loss = tf.reduce_mean(self.losses)\n\n self.optimizer = tf.train.RMSPropOptimizer(.00025, .99, .0, 1e-6)\n self.train_op = self.optimizer.minimize(self.loss, global_step=tf.train.get_global_step())\n\n self.summaries = tf.summary.merge([\n tf.summary.scalar('loss', self.loss),\n tf.summary.histogram('loss_hist', self.losses),\n tf.summary.histogram('q_values_hist', self.predictions),\n tf.summary.scalar('max_q_value', tf.reduce_max(self.predictions))\n ])\n\n def predict(self, sess, s):\n return sess.run(self.predictions, {self.X_pl: s})\n\n def update(self, sess, s, a, y):\n feed_dict = {self.X_pl: s, self.y_pl: y, self.actions_pl: a}\n summaries, global_step, _, loss = sess.run(\n [self.summaries, tf.train.get_global_step(), self.train_op, self.loss],\n feed_dict)\n\n if self.summary_writer:\n self.summary_writer.add_summary(summaries, global_step)\n\n return loss\n\ndef copy_model_parameters(sess, estimator1, estimator2):\n e1_params = [t for t in tf.trainable_variables() if t.name.startswith(estimator1.scope)]\n e1_params = sorted(e1_params, key=lambda v: v.name)\n e2_params = [t for t in tf.trainable_variables() if t.name.startswith(estimator2.scope)]\n e2_params = sorted(e2_params, key=lambda v: v.name)\n\n update_ops = []\n for e1_v, e2_v in zip(e1_params, e2_params):\n op = e2_v.assign(e1_v)\n update_ops.append(op)\n\n sess.run(update_ops)\n\ndef make_epsilon_greedy_policy(estimator, nA):\n def policy_fn(sess, observation, epsilon):\n A = np.ones(nA, dtype=float) * epsilon / nA\n q_values = estimator.predict(sess, np.expand_dims(observation, 0))[0]\n best_action = np.argmax(q_values)\n A[best_action] += (1.0 - epsilon)\n return A\n return policy_fn\n\ndef deep_q_learning(sess,\n env,\n q_estimator,\n target_estimator,\n state_processor,\n num_episodes,\n experiment_dir,\n replay_memory_size=50000,\n replay_memory_init_size=5000,\n update_target_estimator_every=1000,\n discount_factor=.99,\n epsilon_start=1.0,\n epsilon_end=.1,\n epsilon_decay_steps=50000,\n batch_size=32,\n record_video_every=50):\n Transition = namedtuple('Transition', ['state', 'action', 'reward', 'next_state', 'done'])\n EpisodeStats = namedtuple('Stats', ['episode_lengths', 'episode_rewards'])\n\n replay_memory = []\n\n stats = EpisodeStats(\n episode_lengths=np.zeros(num_episodes),\n episode_rewards=np.zeros(num_episodes))\n\n checkpoint_dir = os.path.join(experiment_dir, 'checkpoints')\n checkpoint_path = os.path.join(checkpoint_dir, 'model')\n monitor_path = os.path.join(experiment_dir, 'monitor')\n\n if not os.path.exists(checkpoint_dir):\n os.makedirs(checkpoint_dir)\n if not os.path.exists(monitor_path):\n os.makedirs(monitor_path)\n\n saver = tf.train.Saver()\n latest_checkpoint = tf.train.latest_checkpoint(checkpoint_dir)\n if latest_checkpoint:\n saver.restore(sess, latest_checkpoint)\n\n total_t = sess.run(tf.train.get_global_step())\n epsilons = np.linspace(epsilon_start, epsilon_end, epsilon_decay_steps)\n policy = make_epsilon_greedy_policy(\n q_estimator,\n len(VALID_ACTIONS))\n\n state = env.reset()\n state = state_processor.process(sess, state)\n state = np.stack([state] * 4, axis=2)\n\n for i in range(replay_memory_init_size):\n action_probs = policy(sess, state, epsilons[min(total_t, epsilon_decay_steps - 1)])\n action = np.random.choice(np.arange(len(action_probs)), p=action_probs)\n next_state, reward, done, _ = env.step(VALID_ACTIONS[action])\n\n## cv2.imshow('', cv2.resize(next_state, (0, 0), fx=3, fy=3))\n## cv2.waitKey(1)\n \n next_state = state_processor.process(sess, next_state)\n next_state = np.append(state[:,:,1:], np.expand_dims(next_state, 2), axis=2)\n replay_memory.append(Transition(state, action, reward, next_state, done))\n\n if done:\n state = env.reset()\n state = state_processor.process(sess, state)\n state = np.stack([state] * 4, axis=2)\n else:\n state = next_state\n\n## env = Monitor(env,\n## directory=monitor_path,\n## resume=True,\n## video_callable=lambda count: count % record_video_every == 0)\n\n for i_episode in range(num_episodes):\n saver.save(tf.get_default_session(), checkpoint_path)\n\n state = env.reset()\n state = state_processor.process(sess, state)\n state = np.stack([state] * 4, axis=2)\n loss = None\n\n for t in itertools.count():\n epsilon = epsilons[min(total_t, epsilon_decay_steps - 1)]\n\n episode_summary = tf.Summary()\n episode_summary.value.add(simple_value=epsilon, tag='epsilon')\n q_estimator.summary_writer.add_summary(episode_summary, total_t)\n\n if total_t % update_target_estimator_every == 0:\n copy_model_parameters(sess, q_estimator, target_estimator)\n\n## print('\\nStep {} ({}) @ Episode {} / {}, loss: {}'.format(\n## t, total_t, i_episode + 1, num_episodes, loss), end='')\n## sys.stdout.flush()\n\n action_probs = policy(sess, state, epsilon)\n action = np.random.choice(np.arange(len(action_probs)), p=action_probs)\n next_state, reward, done, _ = env.step(VALID_ACTIONS[action])\n\n## cv2.imshow('', cv2.resize(next_state, (0, 0), fx=3, fy=3))\n## cv2.waitKey(1)\n \n next_state = state_processor.process(sess, next_state)\n next_state = np.append(state[:,:,1:], np.expand_dims(next_state, 2), axis=2)\n\n if len(replay_memory) == replay_memory_size:\n replay_memory.pop(0)\n\n replay_memory.append(Transition(state, action, reward, next_state, done))\n\n stats.episode_rewards[i_episode] += reward\n stats.episode_lengths[i_episode] = t\n\n samples = random.sample(replay_memory, batch_size)\n states_batch, action_batch, reward_batch, next_states_batch, done_batch = map(np.array, zip(*samples))\n\n q_values_next = q_estimator.predict(sess, next_states_batch)\n best_actions = np.argmax(q_values_next, axis=1)\n q_values_next_target = target_estimator.predict(sess, next_states_batch)\n targets_batch = reward_batch + np.invert(done_batch).astype(np.float32) * discount_factor * q_values_next_target[np.arange(batch_size), best_actions]\n\n states_batch = np.array(states_batch)\n loss = q_estimator.update(sess, states_batch, action_batch, targets_batch)\n\n if done:\n break\n\n state = next_state\n total_t += 1\n\n episode_summary = tf.Summary()\n episode_summary.value.add(simple_value=stats.episode_rewards[i_episode], node_name='episode_reward', tag='episode_reward')\n episode_summary.value.add(simple_value=stats.episode_lengths[i_episode], node_name='episode_length', tag='episode_length')\n q_estimator.summary_writer.add_summary(episode_summary, total_t)\n q_estimator.summary_writer.flush()\n\n yield total_t, EpisodeStats(\n episode_lengths=stats.episode_lengths[:i_episode + 1],\n episode_rewards=stats.episode_rewards[:i_episode + 1])\n\n## env.monitor.close()\n return stats\n\ntf.reset_default_graph()\nexperiment_dir = os.path.abspath('./experiments/{}'.format(env.spec.id))\nglobal_step = tf.Variable(0, name='global_step', trainable=False)\n\nq_estimator = Estimator(scope='q', summaries_dir=experiment_dir)\ntarget_estimator = Estimator(scope='target_q')\n\nstate_processor = StateProcessor()\n\nwith tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n for t, stats in deep_q_learning(sess,\n env,\n q_estimator=q_estimator,\n target_estimator=target_estimator,\n state_processor=state_processor,\n experiment_dir=experiment_dir,\n num_episodes=10000,\n replay_memory_size=50000,\n replay_memory_init_size=5000,\n update_target_estimator_every=1000,\n epsilon_start=1.0,\n epsilon_end=.1,\n epsilon_decay_steps=50000,\n discount_factor=.99,\n batch_size=32):\n print('\\nEpisode Reward: {}'.format(stats.episode_rewards[-1]))\n","sub_path":"Breakout/dqn.py","file_name":"dqn.py","file_ext":"py","file_size_in_byte":11581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"15783494","text":"import networkx as nx\n\n\n\nfrom addax.utilities.dataIO import ReadGraph\n\n\n\ndef ParseCertificate(graph, k, certificate):\n \"\"\"\n Produce a canonical graph from a certificate\n\n @param graph: the input graph from which the certificate was generated\n @param k: motif size\n @param certificate: the certificate from Nauty to parse\n \"\"\"\n # this will require substantial debugging and validation for k > 256\n # currently skipped since motifs that size are computationally infeasible\n # nauty almost certainly can never run on graphs that size\n assert (k < 256)\n\n # each vertex gets a certain number of bits in the certificate that contain the adjacency\n # matrix for that vertex. The number of bits is determined by the no_setwords in pynauty. This variable\n # matches the number of 64-bit words (on a 64-bit system) needed to fit all vertices.\n # for colored graphs we also add on 64 bits for each node in the subgraph for coloring\n if graph.colored:\n # if the graph is colored, there are 16 characters per vertex\n # rest of the string represents the canonical labeling\n coloring = certificate[-16 * k:]\n certificate = certificate[:-16 * k]\n\n # convert the vertex bytes (in hex) to base 10 integer\n vertex_colors = [int(coloring[16 * iv: 16 * (iv + 1)], 16) for iv in range(k)]\n\n # create a new netwokx graph object\n if graph.directed:\n nx_graph = nx.DiGraph()\n else:\n nx_graph = nx.Graph()\n\n # add a vertex for each of the k nodes in the subgraph\n for index in range(k):\n # colored graphs have labels for their colors \n if graph.colored:\n nx_graph.add_node(index, label = 'Color: {}'.format(vertex_colors[index]))\n else:\n nx_graph.add_node(index)\n\n # get the number of words per veretx (must be a multiple of 2 * k)\n assert (not (len(certificate) % (2 * k)))\n # based on our output of using hexademical in cpp-enumerate.cpp (i.e., %02x),\n # each byte is written with two letters in our input string (e.g., aa, 02, 10, etc.)\n bytes_per_vertex = len(certificate) // k // 2\n\n # iterate over every vertex and extract the corresponding adjacency matrix\n for vertex in range(k):\n # multiple by two since we are using two characters in the string per byte (wrriten in hexademical)\n certificate_bytes = certificate[vertex * bytes_per_vertex * 2:(vertex + 1) * bytes_per_vertex * 2]\n\n for byte_offset, iv in enumerate(range(0, len(certificate_bytes), 2)):\n # get the byte as an integer (using hexadecimal currently)\n byte = int(certificate_bytes[iv:iv+2], 16)\n assert (byte < 256)\n\n # 8 bits per byte (little endian)\n for bit_offset in range(8):\n bit = byte & (2 ** 7)\n byte = byte << 1\n\n # if this bit is 1, there is an edge from vertex to this location\n if bit:\n # determine the neighbor by the byte and bit offset\n neighbor_vertex = 8 * (bytes_per_vertex - byte_offset - 1) + bit_offset\n nx_graph.add_edge(vertex, neighbor_vertex)\n\n return nx_graph\n\n\n\ndef ParseCertificates(input_filename, k):\n \"\"\"\n Parse the certificates generated for this subgraph\n\n @param input_filename: location for the graph to enumerate\n @parak k: the motif subgraph size to find\n \"\"\"\n # read the graph\n graph = ReadGraph(input_filename, vertices_only = True)\n\n # read the combined enumerated subgraphs file\n subgraphs_filename = 'subgraphs/{}/motif-size-{:03d}.txt'.format(graph.prefix, k)\n with open(subgraphs_filename, 'r') as fd:\n # read all of the certificates and enumerated subgraphs\n for subgraph_index, certificate_info in enumerate(fd.readlines()):\n certificate = certificate_info.split(':')[0].strip()\n nsubgraphs = int(certificate_info.split(':')[1].strip())\n\n # parse the certificate for this graph\n nx_graph = ParseCertificate(graph, k, certificate)\n\n # create the graph drawing structure\n A = nx.nx_agraph.to_agraph(nx_graph)\n A.layout(prog='dot')\n\n output_filename = 'subgraphs/{}/motif-size-{:03d}-motif-{}-found-{}.dot'.format(graph.prefix, k, subgraph_index, nsubgraphs)\n A.draw(output_filename)\n","sub_path":"kavosh/classify.py","file_name":"classify.py","file_ext":"py","file_size_in_byte":4393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"505881902","text":"#-----------------------------------------------------------------------------------------\n# @Auteur : Aurélien Vannieuwenhuyze\n# @Entreprise : Junior Makers Place\n# @Livre :\n# @Chapitre : 09 - Détermination d'opinons grâce à la classification de textes\n#\n# Modules necessaires :\n# PANDAS 0.24.2\n# NUMPY 1.16.3\n# SCIKIT-LEARN : 0.21.0\n# NLTK : 3.4\n#\n# Pour installer un module :\n# Cliquer sur le menu File > Settings > Project:nom_du_projet > Project interpreter > bouton +\n# Dans la zone de recherche en haut à gauche saisir le nom du module\n# Choisir la version en bas à droite\n# Cliquer sur le bouton install situé en bas à gauche\n#-----------------------------------------------------------------------------------------\n\n#Chargement du fichier\nimport pandas as pnd\nmessagesTwitter = pnd.read_csv(\"datas/rechauffementClimatique.csv\", delimiter=\";\")\n\n#Informations sur le nombres d'observations et leur contenu\nprint(messagesTwitter.shape)\nprint(messagesTwitter.head(2))\n\n#Transformation de la feature Croyance\nmessagesTwitter['CROYANCE'] = (messagesTwitter['CROYANCE']=='Yes').astype(int)\nprint(messagesTwitter.head(100))\n\n#Fonction de normalisation\nimport re\ndef normalisation(message):\n message = re.sub('((www\\.[^\\s]+)|(https?://[^\\s]+))','URL', message)\n message = re.sub('@[^\\s]+','USER', message)\n message = message.lower().replace(\"ё\", \"е\")\n message = re.sub('[^a-zA-Zа-яА-Я1-9]+', ' ', message)\n message = re.sub(' +',' ', message)\n return message.strip()\n\n\n#Normalisation\nmessagesTwitter[\"TWEET\"] = messagesTwitter[\"TWEET\"].apply(normalisation)\nprint(messagesTwitter.head(10))\n\n#Chargement des StopWords\nfrom nltk.corpus import stopwords\nstopWords = stopwords.words('english')\n\n#Suppression des Stops Words dans les différentes phrases\nmessagesTwitter['TWEET'] = messagesTwitter['TWEET'].apply(lambda message: ' '.join([mot for mot in message.split() if mot not in (stopWords)]))\nprint(messagesTwitter.head(10))\n\n\n#Stemmatisation\nfrom nltk.stem.snowball import SnowballStemmer\nstemmer = SnowballStemmer('english')\nmessagesTwitter['TWEET'] = messagesTwitter['TWEET'].apply(lambda message: ' '.join([stemmer.stem(mot) for mot in message.split(' ')]))\nprint(messagesTwitter.head(10))\n\n\n#Lemmatization\nfrom nltk.stem import WordNetLemmatizer\nlemmatizer = WordNetLemmatizer()\nmessagesTwitter['TWEET'] = messagesTwitter['TWEET'].apply(lambda message: ' '.join([lemmatizer.lemmatize(mot) for mot in message.split(' ')]))\nprint(messagesTwitter.head(10))\n\nprint(\"Fin de la préparation !\")\n\n\n#Jeux d'apprentissage et de test :\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(messagesTwitter['TWEET'].values, messagesTwitter['CROYANCE'].values,test_size=0.2)\n\n\n#Creation du pipeline d'apprentissage\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.feature_extraction.text import TfidfTransformer\nfrom sklearn.naive_bayes import MultinomialNB\n\netapes_apprentissage = Pipeline([('frequence', CountVectorizer()),\n ('tfidf', TfidfTransformer()),\n ('algorithme', MultinomialNB())])\n\n\n#Apprentissage\nmodele = etapes_apprentissage.fit(X_train,y_train)\n\nfrom sklearn.metrics import classification_report\nprint(classification_report(y_test, modele.predict(X_test), digits=4))\n\n#Nouvelle Phrase :\nphrase = \"Why should trust scientists with global warming if they didnt know Pluto wasnt a planet\"\nprint(phrase)\n\n#Normalisation\nphrase = normalisation(phrase)\n\n#Suppression des stops words\nphrase = ' '.join([mot for mot in phrase.split() if mot not in (stopWords)])\n\n#Stemmatization\nphrase = ' '.join([stemmer.stem(mot) for mot in phrase.split(' ')])\n\n#Lemmitization\nphrase = ' '.join([lemmatizer.lemmatize(mot) for mot in phrase.split(' ')])\nprint (phrase)\n\nprediction = modele.predict([phrase])\nprint(prediction)\nif(prediction[0]==0):\n print(\">> Ne croit pas au rechauffement climatique...\")\nelse:\n print(\">> Croit au rechauffement climatique...\")\n\n\n\n#------ Utilisation de SVM ---\n\n#Définition du Pipeline\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.feature_extraction.text import TfidfTransformer\nfrom sklearn import svm\netapes_apprentissage = Pipeline([('frequence', CountVectorizer()),\n ('tfidf', TfidfTransformer()),\n ('algorithme', svm.SVC(kernel='linear', C=2))])\n\n\n#Apprentissage\nmodele = etapes_apprentissage.fit(X_train,y_train)\nfrom sklearn.metrics import classification_report\nprint(classification_report(y_test, modele.predict(X_test), digits=4))\n\n#Recherche du meilleur paramètre C\nfrom sklearn.model_selection import GridSearchCV\nparametresC = {'algorithme__C':(1,2,4,5,6,7,8,9,10,11,12)}\n\nrechercheCOptimal = GridSearchCV(etapes_apprentissage, parametresC,cv=2)\nrechercheCOptimal.fit(X_train,y_train)\nprint(rechercheCOptimal.best_params_)\n\n\n#Nouveau Paramètre C=1\netapes_apprentissage = Pipeline([('frequence', CountVectorizer()),\n ('tfidf', TfidfTransformer()),\n ('algorithme', svm.SVC(kernel='linear', C=1))])\n\nmodele = etapes_apprentissage.fit(X_train,y_train)\nfrom sklearn.metrics import classification_report\nprint(classification_report(y_test, modele.predict(X_test), digits=4))","sub_path":"code ch9/determinationOpinionsTwitter.py","file_name":"determinationOpinionsTwitter.py","file_ext":"py","file_size_in_byte":5437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"490662993","text":"import unittest\nimport string\n\nclass TestCenter(unittest.TestCase):\n\n def test_center_default(self):\n # cases are (arguments, [possible results of centering])\n cases = [(('a', 5), [' a ']),\n (('a', 4), [' a ', ' a ']),\n (('[]', 5), [' [] ', ' [] ']),\n (('[]', 4), [' [] ']),\n (('test', 2), ['test']),\n (('', 3), [' ']),\n ((' a', 5), [' a ', ' a '])]\n\n # test all cases\n for (str_, width), expected in cases:\n output = string.center(str_, width)\n self.assertEqual(len(output), max(width, len(str_)))\n self.assertIn(output, expected)\n\n def test_center_fillchar(self):\n cases = [(('a', 5), ['**a**']),\n (('a', 4), ['*a**', '**a*'])]\n\n # test all cases\n for fillchar in ['#', '5', ' ']:\n for (str_, width), expected in cases:\n output = string.center(str_, width, fillchar)\n self.assertEqual(len(output), max(width, len(str_)))\n self.assertIn(output.replace(fillchar, '*'), expected)\n\n def test_errors(self):\n with self.assertRaises(TypeError):\n string.center('a', '')\n\n with self.assertRaises(TypeError):\n string.center('a', '*#')\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"Wednesday/carpentry_solutions/test_center/test_center.py","file_name":"test_center.py","file_ext":"py","file_size_in_byte":1399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"532544542","text":"# coding: utf-8\n\"\"\"Tests for plugin.py.\"\"\"\n\nfrom datetime import timedelta\nimport logging\nimport os\nfrom nose.tools import assert_raises\n\nfrom owslib.fes import PropertyIsGreaterThanOrEqualTo\n\nfrom ckan.logic import get_action\nfrom ckan.logic.action.update import package_update\n\nfrom ckanext.harvest.queue import (\n gather_stage ,\n fetch_and_import_stages ,\n)\nfrom ckanext.harvest.model import (\n HarvestObject ,\n)\n\nfrom ckanext.spatial.harvesters.base import SpatialHarvester\nfrom ckanext.spatial.model import ISODocument\n\nfrom ckanext.fisbroker.plugin import (\n FisbrokerPlugin,\n marked_as_opendata,\n marked_as_service_resource,\n filter_tags,\n extract_license_and_attribution,\n extract_reference_dates,\n extract_url,\n extract_preview_markup,\n extras_as_list,\n TIMEOUT_DEFAULT,\n TIMEDELTA_DEFAULT,\n)\nfrom ckanext.fisbroker.tests import FisbrokerTestBase, _assert_equal\nfrom ckanext.fisbroker.tests.mock_fis_broker import reset_mock_server\n\nLOG = logging.getLogger(__name__)\n\nclass TestTransformationHelpers(FisbrokerTestBase):\n '''Tests for transformation helper methods used in get_package_dict. To see how CSW documents are mapped\n to ISO, check `ckanext.spatial.model.harvested_metadata.py/ISODocument`.'''\n\n def _open_xml_fixture(self, xml_filename):\n xml_filepath = os.path.join(os.path.dirname(__file__),\n 'xml',\n xml_filename)\n with open(xml_filepath, 'rb') as f:\n xml_string_raw = f.read()\n\n return xml_string_raw\n\n def _csw_resource_data_dict(self, dataset_name):\n '''Return an example open data dataset as expected as input\n to get_package_dict().'''\n\n xml_string = self._open_xml_fixture(dataset_name)\n iso_document = ISODocument(xml_string)\n iso_values = iso_document.read_values()\n base_harvester = SpatialHarvester()\n source = self._create_source()\n obj = HarvestObject(\n source=source,\n )\n obj.save()\n package_dict = base_harvester.get_package_dict(iso_values, obj)\n\n data_dict = {\n 'package_dict': package_dict ,\n 'iso_values': iso_values\n }\n return data_dict\n\n def _resource_list(self):\n return [\n {\n u'description': u'WFS Service',\n u'format': u'WFS',\n u'id': u'0776059c-b9a7-4b9f-9cae-7c7ff0ca9f86',\n u'internal_function': u'api',\n u'main': u'True',\n u'name': u'WFS Service',\n u'package_id': u'4e35031f-39ee-45bd-953f-f27398791ba1',\n u'position': 0,\n u'resource_locator_function': u'information',\n u'url': u'https://fbinter.stadt-berlin.de/fb/wfs/data/senstadt/s01_11_07naehr2015?request=getcapabilities&service=wfs&version=2.0.0',\n },\n {\n u'description': u'Serviceseite im FIS-Broker',\n u'format': u'HTML',\n u'id': u'dd7c056a-227b-453e-a2d0-516bf3fb1611',\n u'internal_function': u'web_interface',\n u'main': u'False',\n u'name': u'Serviceseite im FIS-Broker',\n u'package_id': u'4e35031f-39ee-45bd-953f-f27398791ba1',\n u'position': 1,\n u'resource_locator_function': u'information',\n u'url': u'https://fbinter.stadt-berlin.de/fb?loginkey=alphaDataStart&alphaDataId=s01_11_07naehr2015@senstadt',\n },\n {\n u'description': u'Inhaltliche Beschreibung',\n u'format': u'HTML',\n u'id': u'1e368892-d95b-459b-a065-ec19462f31d1',\n u'internal_function': u'documentation',\n u'main': u'False',\n u'name': u'Inhaltliche Beschreibung',\n u'package_id': u'4e35031f-39ee-45bd-953f-f27398791ba1',\n u'position': 2,\n u'resource_locator_function': u'information',\n u'url': u'https://www.stadtentwicklung.berlin.de/umwelt/umweltatlas/dd11107.htm',\n },\n {\n u'description': u'Technische Beschreibung',\n u'format': u'PDF',\n u'id': u'9737084b-b3e6-412d-a220-436a98d815cc',\n u'internal_function': u'documentation',\n u'main': u'False',\n u'name': u'Technische Beschreibung',\n u'package_id': u'4e35031f-39ee-45bd-953f-f27398791ba1',\n u'position': 3,\n u'resource_locator_function': u'information',\n u'url': u'https://fbinter.stadt-berlin.de/fb_daten/beschreibung/umweltatlas/datenformatbeschreibung/Datenformatbeschreibung_kriterien_zur_bewertung_der_bodenfunktionen2015.pdf',\n }\n ]\n\n def test_filter_tags(self):\n '''Check if all tags from `to_remove` are removed from the\n output tag list. In case of duplicate tags, all occurrences of\n a tag should be removed, not just the first one.'''\n to_remove = [\n 'open data', # that's a duplicate; both occurrences should be removed\n 'Berlin',\n 'Hamburg', # that's not in the original tag list, shouldn't change anything\n 'Boden',\n u'N\\xe4hrstoffversorgung',\n ]\n data_dict = self._csw_resource_data_dict('wfs-open-data.xml')\n simple_tag_list = data_dict['iso_values']['tags']\n complex_tag_list = data_dict['package_dict']['tags']\n expected_result = [\n {'name': 'inspireidentifiziert'},\n {'name': 'opendata'},\n {'name': 'Sachdaten'},\n {'name': 'Umweltatlas'},\n {'name': 'Bodengesellschaft'},\n {'name': 'Ausgangsmaterial'},\n {'name': 'Oberboden'},\n {'name': 'Unterboden'},\n {'name': 'KAKeff'},\n {'name': 'pH-Wert'},\n {'name': 'Bodenart'},\n {'name': u'Basens\\xe4ttigung'},\n {'name': u'B\\xf6den'},\n {'name': 'infoFeatureAccessService'},\n ]\n filter_tags(to_remove, simple_tag_list, complex_tag_list)\n _assert_equal(complex_tag_list, expected_result)\n\n def test_is_open_data(self):\n '''Test for correctly assigning Open Data status if the dataset\n has been marked as such.'''\n\n data_dict = self._csw_resource_data_dict('wfs-open-data.xml')\n assert marked_as_opendata(data_dict)\n\n def test_is_close_data(self):\n '''Test for correctly assigning Closed Data status if the dataset\n has not been marked as Open Data.'''\n\n data_dict = self._csw_resource_data_dict('wfs-closed-data.xml')\n assert not marked_as_opendata(data_dict)\n\n def test_skip_on_closed_data_resource(self):\n '''Test if get_package_dict() returns 'skip' for a closed data\n CSW resource.'''\n\n data_dict = self._csw_resource_data_dict('wfs-closed-data.xml')\n _assert_equal(FisbrokerPlugin().get_package_dict(self.context, data_dict), 'skip')\n\n def test_is_service_resource(self):\n '''Test to check if a dataset is correctly classified as a service\n resource.'''\n\n data_dict = self._csw_resource_data_dict('wfs-open-data.xml')\n _assert_equal(marked_as_service_resource(data_dict), True)\n\n def test_is_not_service_resource(self):\n '''Test to check if a dataset is correctly classified as not being service\n resource.'''\n\n data_dict = self._csw_resource_data_dict('dataset-open-data.xml')\n _assert_equal(marked_as_service_resource(data_dict), False)\n\n def test_skip_on_dataset_resource(self):\n '''Test if get_package_dict() returns 'skip' for a dataset\n CSW resource (as opposed to a service resource).'''\n\n data_dict = self._csw_resource_data_dict('dataset-open-data.xml')\n _assert_equal(FisbrokerPlugin().get_package_dict(self.context, data_dict), 'skip')\n\n def test_skip_on_missing_responsible_organisation(self):\n '''Test if get_package_dict() returns 'skip' for a service resource\n without any information of the responsible party.'''\n\n data_dict = self._csw_resource_data_dict('wfs-no-responsible-party.xml')\n _assert_equal(FisbrokerPlugin().get_package_dict(self.context, data_dict), 'skip')\n\n def test_skip_on_missing_org_name(self):\n '''Test if get_package_dict() returns 'skip' for a service resource\n without an organisation name in the responsible party information.'''\n\n data_dict = self._csw_resource_data_dict('wfs-no-org-name.xml')\n _assert_equal(FisbrokerPlugin().get_package_dict(self.context, data_dict), 'skip')\n\n def test_skip_on_missing_email(self):\n '''Test if get_package_dict() returns 'skip' for a service resource\n without an email in the responsible party information.'''\n\n data_dict = self._csw_resource_data_dict('wfs-no-email.xml')\n _assert_equal(FisbrokerPlugin().get_package_dict(self.context, data_dict), 'skip')\n\n def test_skip_on_missing_license_info(self):\n '''Test if get_package_dict() returns 'skip' for a service resource\n without parseable license information.'''\n\n data_dict = self._csw_resource_data_dict('wfs-no-license.xml')\n _assert_equal(FisbrokerPlugin().get_package_dict(self.context, data_dict), 'skip')\n\n def test_fix_bad_dl_de_id(self):\n '''Test if incorrect license id for DL-DE-BY has been corrected.'''\n\n data_dict = {\n 'iso_values': {\n 'limitations-on-public-access': [\n '{ \"id\": \"dl-de-by-2-0\" , \"name\": \" Datenlizenz Deutschland - Namensnennung - Version 2.0 \", \"url\": \"https://www.govdata.de/dl-de/by-2-0\", \"quelle\": \"Umweltatlas Berlin / [Titel des Datensatzes]\" }'\n ]\n }\n }\n license_and_attribution = extract_license_and_attribution(data_dict)\n _assert_equal(license_and_attribution['license_id'], \"dl-de-by-2.0\")\n\n def test_skip_on_missing_release_date(self):\n '''Test if get_package_dict() returns 'skip' for a service resource\n without a release date.'''\n\n data_dict = self._csw_resource_data_dict('wfs-no-release-date.xml')\n # LOG.info(\"iso_valalala: %s\", data_dict['iso_values'])\n # assert False\n _assert_equal(FisbrokerPlugin().get_package_dict(self.context, data_dict), 'skip')\n\n def test_revision_interpreted_as_updated_creation_as_released(self):\n '''Test if a reference date of type `revision` is interpreted as\n `\bdate_updated` and a date of type `creation` as `date_released`.\n `publication` should be ignored if `creation` was already present.'''\n\n creation = '1974-06-07'\n publication = '1994-05-03'\n revision = '2000-01-01'\n data_dict = {\n 'iso_values': {\n 'dataset-reference-date': [\n {\n 'type': 'creation',\n 'value': creation,\n } ,\n {\n 'type': 'publication',\n 'value': publication,\n } ,\n {\n 'type': 'revision' ,\n 'value': revision,\n } ,\n ]\n }\n }\n\n reference_dates = extract_reference_dates(data_dict)\n _assert_equal(reference_dates['date_released'], creation)\n _assert_equal(reference_dates['date_updated'], revision)\n\n def test_publication_interpreted_as_released(self):\n '''Test if a reference date of type `publication` is interpreted as\n `date_released` if `creation` is no present.'''\n\n publication = '1994-05-03'\n revision = '2000-01-01'\n data_dict = {\n 'iso_values': {\n 'dataset-reference-date': [\n {\n 'type': 'publication',\n 'value': publication,\n } ,\n {\n 'type': 'revision',\n 'value': revision,\n },\n ]\n }\n }\n\n reference_dates = extract_reference_dates(data_dict)\n _assert_equal(reference_dates['date_released'], publication)\n _assert_equal(reference_dates['date_updated'], revision)\n\n def test_date_updated_as_fallback_for_date_released(self):\n '''Test that, if no `date_released` could be extracted, the\n value of `date_updated` is used as a fallback.'''\n\n revision = '2000-01-01'\n data_dict = {\n 'iso_values': {\n 'dataset-reference-date': [\n {\n 'type': 'revision',\n 'value': revision,\n },\n ]\n }\n }\n\n reference_dates = extract_reference_dates(data_dict)\n _assert_equal(reference_dates['date_released'], revision)\n _assert_equal(reference_dates['date_updated'], revision)\n\n def test_web_interface_resource_picked_as_url(self):\n '''Test that the resource marked as `web_interface` is picked as the\n dataset's `url` metadatum.'''\n\n resources = self._resource_list()\n url = extract_url(resources)\n _assert_equal(\n url, u'https://fbinter.stadt-berlin.de/fb?loginkey=alphaDataStart&alphaDataId=s01_11_07naehr2015@senstadt')\n\n def test_api_resource_as_fallback_for_url(self):\n '''Test that the resource marked as `api` is picked as the\n dataset's `url` metadatum, if no `web_interface` is present.'''\n\n resources = self._resource_list()\n resources = list(filter(lambda x: x.get('internal_function') != 'web_interface', resources))\n url = extract_url(resources)\n _assert_equal(\n url, u'https://fbinter.stadt-berlin.de/fb/wfs/data/senstadt/s01_11_07naehr2015?request=getcapabilities&service=wfs&version=2.0.0')\n\n def test_no_web_interface_or_api_means_no_url(self):\n '''Test that no url is picked if neither `web_interface` nor `api` is present.'''\n\n resources = self._resource_list()\n resources = list(filter(lambda x: x.get('internal_function') != 'web_interface', resources))\n resources = list(filter(lambda x: x.get('internal_function') != 'api', resources))\n url = extract_url(resources)\n _assert_equal(url, None)\n\n def test_build_preview_graphic_markup(self):\n '''Test that, for a dataset that has an MD_BrowseGraphic named 'Vorschaugrafik',\n the correct image markdown is generated.'''\n data_dict = self._csw_resource_data_dict('wfs-open-data.xml')\n\n preview_markup = extract_preview_markup(data_dict)\n _assert_equal(\n preview_markup, u\"![Vorschaugrafik zu Datensatz 'Nährstoffversorgung des Oberbodens 2015 (Umweltatlas)'](https://fbinter.stadt-berlin.de/fb_daten/vorschau/sachdaten/svor_default.gif)\")\n\n def test_no_preview_graphic_wrong_name(self):\n '''Test that, for a dataset that has a MD_BrowseGraphic but not one named 'Vorschaugrafik',\n no image is generated.'''\n data_dict = self._csw_resource_data_dict('wfs-no-preview_1.xml')\n preview_markup = extract_preview_markup(data_dict)\n _assert_equal(preview_markup, None)\n\n def test_no_preview_graphic_no_image(self):\n '''Test that, for a dataset that has doesn't have any graphics,\n no image is generated.'''\n\n data_dict = self._csw_resource_data_dict('wfs-no-preview_2.xml')\n preview_markup = extract_preview_markup(data_dict)\n _assert_equal(preview_markup, None)\n\n def test_complex_extras_become_json(self):\n '''Test that converting extra-dicts to list of dicts works,\n including the conversion of complex values to JSON strings.'''\n\n extras_dict = {\n 'foo': 'bar' ,\n 'inners': [\n 'mercury', 'venus', 'earth', 'mars'\n ] ,\n 'holidays': {\n 'labour': '05-01' ,\n 'christmas-day': '12-25'\n }\n }\n extras_list = [\n { 'key': 'foo', 'value': 'bar' } ,\n { 'key': 'inners', 'value': '[\"mercury\", \"venus\", \"earth\", \"mars\"]' } ,\n {'key': 'holidays', 'value': '{\"christmas-day\": \"12-25\", \"labour\": \"05-01\"}'}\n ]\n\n _assert_equal(extras_as_list(extras_dict), extras_list)\n\nclass TestPlugin(FisbrokerTestBase):\n '''Tests for the main plugin class.'''\n\n def test_open_data_wfs_service(self):\n '''Do the whole process: import and convert a document from the CSW-server, test\n if all the values in the converted dict are as expected.'''\n # Create source1\n wfs_fixture = {\n 'title': 'Test Source',\n 'name': 'test-source',\n 'url': u'http://127.0.0.1:8999/wfs-open-data.xml',\n 'object_id': u'65715c6e-bbaf-3def-982b-3b5156272da7',\n 'source_type': u'fisbroker'\n }\n\n source, job = self._create_source_and_job(wfs_fixture)\n\n harvest_object = self._run_job_for_single_document(job, wfs_fixture['object_id'])\n\n package_dict = get_action('package_show_rest')(self.context,{'id':harvest_object.package_id})\n\n # Package was created\n assert package_dict\n _assert_equal(package_dict['state'], u'active')\n _assert_equal(harvest_object.current, True)\n\n # Package has correct tags (filtering was successful)\n expected_tags = [\n 'Ausgangsmaterial',\n u'Basens\\xe4ttigung',\n 'Berlin',\n 'Boden',\n 'Bodenart',\n 'Bodengesellschaft',\n u'B\\xf6den',\n 'KAKeff',\n u'N\\xe4hrstoffversorgung',\n 'Oberboden',\n 'Sachdaten',\n 'Umweltatlas',\n 'Unterboden',\n 'infoFeatureAccessService',\n 'inspireidentifiziert',\n 'pH-Wert',\n ]\n _assert_equal(package_dict['tags'], expected_tags)\n\n # Package has correct contact info\n _assert_equal(package_dict['author'], u\"Senatsverwaltung f\\xFCr Umwelt, Verkehr und Klimaschutz Berlin\")\n _assert_equal(package_dict['maintainer_email'], \"michael.thelemann@senuvk.berlin.de\")\n _assert_equal(package_dict['maintainer'], \"Hr. Dr. Thelemann\")\n\n # Package has correct license and attribution\n _assert_equal(package_dict['license_id'], \"dl-de-by-2.0\")\n _assert_equal(package_dict['extras']['attribution_text'],\n \"Umweltatlas Berlin / [Titel des Datensatzes]\")\n\n # Package has correct reference dates\n _assert_equal(package_dict['extras']['date_released'], \"2018-08-13\")\n _assert_equal(package_dict['extras']['date_updated'], \"2018-08-13\")\n\n # Package has correct number of resources (i.e., uniqing was successful)\n _assert_equal(len(package_dict['resources']), 5)\n\n # url\n _assert_equal(\n package_dict['url'], \"https://fbinter.stadt-berlin.de/fb?loginkey=alphaDataStart&alphaDataId=s01_11_07naehr2015@senstadt\")\n\n # preview graphic - check if description contains something that looks like one\n assert u\"![Vorschaugrafik zu Datensatz 'Nährstoffversorgung des Oberbodens 2015 (Umweltatlas)'](https://fbinter.stadt-berlin.de/fb_daten/vorschau/sachdaten/svor_default.gif)\" in package_dict['notes']\n\n # title\n _assert_equal(\n u\"Nährstoffversorgung des Oberbodens 2015 (Umweltatlas) - [WFS]\", package_dict['title'])\n\n # name\n _assert_equal(\n \"nahrstoffversorgung-des-oberbodens-2015-umweltatlas-wfs-65715c6e\", package_dict['name']\n )\n\n def test_empty_config(self):\n '''Test that an empty config just returns unchanged.'''\n _assert_equal(FisbrokerPlugin().validate_config(None), None)\n _assert_equal(FisbrokerPlugin().validate_config({}), {})\n\n def test_import_since_must_be_valid_iso(self):\n '''Test that the `import_since` config must be a valid ISO8601 date.'''\n config = '{ \"import_since\": \"2019-01-01\" }'\n assert FisbrokerPlugin().validate_config(config)\n # invalid date:\n config = '{ \"import_since\": \"2019.01.01\" }'\n with assert_raises(ValueError):\n assert FisbrokerPlugin().validate_config(config)\n\n def test_timeout_must_be_int(self):\n '''Test that the `timeout` config must be an int.'''\n config = '{ \"timeout\": 30 }'\n assert FisbrokerPlugin().validate_config(config)\n # invalid timout:\n config = '{ \"timeout\": \"hurtz\" }'\n with assert_raises(ValueError):\n assert FisbrokerPlugin().validate_config(config)\n\n def test_timedelta_must_be_int(self):\n '''Test that the `timedelta` config must be an int.'''\n config = '{ \"timedelta\": 2 }'\n assert FisbrokerPlugin().validate_config(config)\n # invalid timedelta:\n config = '{ \"timedelta\": \"two\" }'\n with assert_raises(ValueError):\n assert FisbrokerPlugin().validate_config(config)\n\n def test_undefined_import_since_is_none(self):\n '''Test that an undefined `import_since` config returns None.'''\n\n FisbrokerPlugin().source_config = {}\n import_since = FisbrokerPlugin().get_import_since_date(None)\n _assert_equal(import_since, None)\n\n def test_import_since_big_bang_means_none(self):\n '''Test that 'big_bang' for the `import_since` config means\n returns None.'''\n\n FisbrokerPlugin().source_config = { 'import_since': \"big_bang\" }\n import_since = FisbrokerPlugin().get_import_since_date(None)\n _assert_equal(import_since, None)\n\n def test_import_since_regular_value_returned_unchanged(self):\n '''Test that any value other than 'big_bang' or 'last_changed' for\n `import_since` is returned unchanged.'''\n\n FisbrokerPlugin().source_config = {'import_since': \"2020-03-01\"}\n import_since = FisbrokerPlugin().get_import_since_date(None)\n _assert_equal(import_since, \"2020-03-01\")\n\n def test_undefined_timeout_gives_default(self):\n '''Test that an undefined `timeout` config returns the default.'''\n\n FisbrokerPlugin().source_config = {}\n timeout = FisbrokerPlugin().get_timeout()\n _assert_equal(timeout, TIMEOUT_DEFAULT)\n\n def test_undefined_time_delta_gives_default(self):\n '''Test that an undefined `timedelta` config returns the default.'''\n\n FisbrokerPlugin().source_config = {}\n timedelta = FisbrokerPlugin().get_timedelta()\n _assert_equal(timedelta, TIMEDELTA_DEFAULT)\n\n def test_timeout_config_returned_as_int(self):\n '''Test that get_timeout() always returns an int, if the `timeout``\n config is set.'''\n\n FisbrokerPlugin().source_config = { 'timeout': '100' }\n timeout = FisbrokerPlugin().get_timeout()\n _assert_equal(timeout, 100)\n\n def test_timedelta_config_returned_as_int(self):\n '''Test that get_timedelta() always returns an int, if the `timedelta``\n config is set.'''\n\n FisbrokerPlugin().source_config = { 'timedelta': '1' }\n timedelta = FisbrokerPlugin().get_timedelta()\n _assert_equal(timedelta, 1)\n\n def test_last_error_free_returns_correct_job(self):\n '''Test that, after a successful job A, last_error_free() returns A.'''\n\n source, job = self._create_source_and_job()\n object_ids = gather_stage(FisbrokerPlugin(), job)\n for object_id in object_ids:\n harvest_object = HarvestObject.get(object_id)\n fetch_and_import_stages(FisbrokerPlugin(), harvest_object)\n job.status = u'Finished'\n job.save()\n\n new_job = self._create_job(source.id)\n last_error_free_job = FisbrokerPlugin().last_error_free_job(new_job)\n _assert_equal(last_error_free_job, job)\n\n # the import_since date should be the time job_a finished:\n FisbrokerPlugin().source_config['import_since'] = \"last_error_free\"\n import_since = FisbrokerPlugin().get_import_since_date(new_job)\n import_since_expected = (job.gather_started +\n timedelta(hours=FisbrokerPlugin().get_timedelta()))\n _assert_equal(import_since, import_since_expected.strftime(\"%Y-%m-%dT%H:%M:%S%z\"))\n\n # the query constraints should reflect the import_since date:\n constraint = FisbrokerPlugin().get_constraints(new_job)[0]\n _assert_equal(constraint.literal, PropertyIsGreaterThanOrEqualTo(\n 'modified', import_since).literal)\n _assert_equal(constraint.propertyname, PropertyIsGreaterThanOrEqualTo(\n 'modified', import_since).propertyname)\n\n def test_last_error_free_does_not_return_unsuccessful_job(self):\n '''Test that, after a successful job A, followed by an unsuccessful\n job B, last_error_free() returns A.'''\n\n source, job_a = self._create_source_and_job()\n object_ids = gather_stage(FisbrokerPlugin(), job_a)\n for object_id in object_ids:\n harvest_object = HarvestObject.get(object_id)\n fetch_and_import_stages(FisbrokerPlugin(), harvest_object)\n job_a.status = u'Finished'\n job_a.save()\n\n # This harvest job should fail, because the mock FIS-broker will look for a different\n # file on the second harvest run, will not find it and return a \"no_record_found\"\n # error.\n job_b = self._create_job(source.id)\n object_ids = gather_stage(FisbrokerPlugin(), job_b)\n for object_id in object_ids:\n harvest_object = HarvestObject.get(object_id)\n fetch_and_import_stages(FisbrokerPlugin(), harvest_object)\n job_b.status = u'Finished'\n job_b.save()\n\n new_job = self._create_job(source.id)\n last_error_free_job = FisbrokerPlugin().last_error_free_job(new_job)\n # job_a should be the last error free job:\n _assert_equal(last_error_free_job, job_a)\n\n # the import_since date should be the time job_a finished:\n FisbrokerPlugin().source_config['import_since'] = \"last_error_free\"\n import_since = FisbrokerPlugin().get_import_since_date(new_job)\n import_since_expected = (job_a.gather_started +\n timedelta(hours=FisbrokerPlugin().get_timedelta()))\n _assert_equal(import_since, import_since_expected.strftime(\"%Y-%m-%dT%H:%M:%S%z\"))\n\n # the query constraints should reflect the import_since date:\n constraint = FisbrokerPlugin().get_constraints(new_job)[0]\n _assert_equal(constraint.literal, PropertyIsGreaterThanOrEqualTo('modified', import_since).literal)\n _assert_equal(constraint.propertyname, PropertyIsGreaterThanOrEqualTo(\n 'modified', import_since).propertyname)\n\n def test_last_error_free_does_not_return_reimport_job(self):\n '''Test that reimport jobs are ignored for determining\n the last error-free job.'''\n\n # do a successful job\n source, job_a = self._create_source_and_job()\n object_ids = gather_stage(FisbrokerPlugin(), job_a)\n for object_id in object_ids:\n harvest_object = HarvestObject.get(object_id)\n fetch_and_import_stages(FisbrokerPlugin(), harvest_object)\n job_a.status = u'Finished'\n job_a.save()\n\n LOG.debug(\"successful job done ...\")\n\n # do an unsuccessful job\n # This harvest job should fail, because the mock FIS-broker will look for a different\n # file on the second harvest run, will not find it and return a \"no_record_found\"\n # error.\n job_b = self._create_job(source.id)\n object_ids = gather_stage(FisbrokerPlugin(), job_b)\n for object_id in object_ids:\n harvest_object = HarvestObject.get(object_id)\n fetch_and_import_stages(FisbrokerPlugin(), harvest_object)\n job_b.status = u'Finished'\n job_b.save()\n\n LOG.debug(\"unsuccessful job done ...\")\n\n # reset the mock server's counter\n reset_mock_server(1)\n\n # do a reimport job\n package_id = \"3d-gebaudemodelle-im-level-of-detail-2-lod-2-wms-f2a8a483\"\n self._get_test_app().get(\n url=\"/api/harvest/reimport?id={}\".format(package_id),\n headers={'Accept': 'application/json'},\n extra_environ={'REMOTE_USER': self.context['user'].encode('ascii')}\n )\n\n LOG.debug(\"reimport job done ...\")\n\n new_job = self._create_job(source.id)\n last_error_free_job = FisbrokerPlugin().last_error_free_job(new_job)\n # job_a should be the last error free job:\n _assert_equal(last_error_free_job.id, job_a.id)\n\n def test_import_since_date_is_none_if_no_jobs(self):\n '''Test that, if the `import_since` setting is `last_error_free`, but\n no jobs have run successfully (or at all), get_import_since_date()\n returns None.'''\n\n source, job = self._create_source_and_job()\n FisbrokerPlugin().source_config['import_since'] = \"last_error_free\"\n import_since = FisbrokerPlugin().get_import_since_date(job)\n _assert_equal(import_since, None)\n","sub_path":"ckanext/fisbroker/tests/test_plugin.py","file_name":"test_plugin.py","file_ext":"py","file_size_in_byte":29454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"543610453","text":"\"\"\"\nOptuna example that optimizes multi-layer perceptrons using PyTorch.\n\nIn this example, we optimize the validation accuracy of hand-written digit recognition using\nPyTorch and MNIST. We optimize the neural network architecture as well as the optimizer\nconfiguration. As it is too time consuming to use the whole MNIST dataset, we here use a small\nsubset of it.\n\nWe have the following two ways to execute this example:\n\n(1) Execute this code directly.\n $ python pytorch_simple.py\n\n\n(2) Execute through CLI.\n $ STUDY_NAME=`optuna create-study --direction maximize --storage sqlite:///example.db`\n $ optuna study optimize pytorch_simple.py objective --n-trials=100 --study $STUDY_NAME \\\n --storage sqlite:///example.db\n\n\"\"\"\n\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport torch.utils.data\nfrom torchvision import datasets\nfrom torchvision import transforms\n\nDEVICE = torch.device('cpu')\nBATCHSIZE = 128\nCLASSES = 10\nDIR = os.getcwd()\nEPOCHS = 10\nLOG_INTERVAL = 10\nN_TRAIN_EXAMPLES = BATCHSIZE * 30\nN_TEST_EXAMPLES = BATCHSIZE * 10\n\n\nclass Net(nn.Module):\n # Constructor for trial network.\n def __init__(self, trial):\n super(Net, self).__init__()\n self.layers = []\n self.dropouts = []\n\n # We optimize the number of layers, hidden untis in each layer and drouputs.\n n_layers = trial.suggest_int('n_layers', 1, 3)\n dropout = trial.suggest_uniform('dropout', 0.2, 0.5)\n input_dim = 28 * 28\n for i in range(n_layers):\n output_dim = int(trial.suggest_loguniform('n_units_l{}'.format(i), 4, 128))\n self.layers.append(nn.Linear(input_dim, output_dim))\n self.dropouts.append(nn.Dropout(dropout))\n input_dim = output_dim\n\n self.layers.append(nn.Linear(input_dim, CLASSES))\n\n # Assigning the layers as class variables (PyTorch requirement).\n for idx, layer in enumerate(self.layers):\n setattr(self, 'fc{}'.format(idx), layer)\n\n # Assigning the dropouts as class variables (PyTorch requirement).\n for idx, dropout in enumerate(self.dropouts):\n setattr(self, 'drop{}'.format(idx), dropout)\n\n # Forward pass computation function.\n def forward(self, data):\n data = data.view(-1, 28 * 28)\n for layer, dropout in zip(self.layers, self.dropouts):\n data = F.relu(layer(data))\n data = dropout(data)\n return F.log_softmax(self.layers[-1](data), dim=1)\n\n\ndef get_mnist():\n # Load MNIST dataset.\n train_loader = torch.utils.data.DataLoader(datasets.MNIST(DIR,\n train=True,\n download=True,\n transform=transforms.ToTensor()),\n batch_size=BATCHSIZE,\n shuffle=True)\n test_loader = torch.utils.data.DataLoader(datasets.MNIST(DIR,\n train=False,\n transform=transforms.ToTensor()),\n batch_size=BATCHSIZE,\n shuffle=True)\n\n return train_loader, test_loader\n\n\ndef objective(trial):\n\n # Generate the model.\n model = Net(trial).to(DEVICE)\n\n # Generate the optimizers.\n optimizer_name = trial.suggest_categorical('optimizer', ['Adam', 'RMSprop', 'SGD'])\n lr = trial.suggest_uniform('lr', 1e-5, 1e-1)\n optimizer = getattr(optim, optimizer_name)(model.parameters(), lr=lr)\n\n # Get the MNIST dataset.\n train_loader, test_loader = get_mnist()\n\n # Training of the model.\n model.train()\n for epoch in range(EPOCHS):\n for batch_idx, (data, target) in enumerate(train_loader):\n # Limiting training data for faster epochs.\n if batch_idx * BATCHSIZE >= N_TRAIN_EXAMPLES:\n break\n\n data, target = data.to(DEVICE), target.to(DEVICE)\n\n # Zeroing out gradient buffers.\n optimizer.zero_grad()\n # Performing a forward pass.\n output = model(data)\n # Computing negative Log Likelihood loss.\n loss = F.nll_loss(output, target)\n # Performing a backward pass.\n loss.backward()\n # Updating the weights.\n optimizer.step()\n\n # Validation of the model.\n model.eval()\n correct = 0\n with torch.no_grad():\n for batch_idx, (data, target) in enumerate(test_loader):\n # Limiting testing data.\n if batch_idx * BATCHSIZE >= N_TEST_EXAMPLES:\n break\n data, target = data.to(DEVICE), target.to(DEVICE)\n output = model(data)\n pred = output.argmax(dim=1, keepdim=True) # Get the index of the max log-probability.\n correct += pred.eq(target.view_as(pred)).sum().item()\n\n accuracy = correct / N_TEST_EXAMPLES\n return accuracy\n\n\nif __name__ == '__main__':\n import optuna\n study = optuna.create_study(direction='maximize')\n study.optimize(objective, n_trials=100)\n\n print('Number of finished trials: ', len(study.trials))\n\n print('Best trial:')\n trial = study.best_trial\n\n print(' Value: ', trial.value)\n\n print(' Params: ')\n for key, value in trial.params.items():\n print(' {}: {}'.format(key, value))\n","sub_path":"examples/pytorch_simple.py","file_name":"pytorch_simple.py","file_ext":"py","file_size_in_byte":5626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"213874836","text":"import itertools\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport numpy as np\nfrom scipy.sparse import csgraph\n\n\nclass Imputer(nn.Module):\n \"\"\"Impute missing data based on type.\"\"\"\n def __init__(self, impute_type, n_nodes, n_dim, seq_len=12,\n gcn_dropout=0.0, gcn_support_len=1, gcn_order=1,\n device=\"cpu\", adj=None, jitter=1e-6):\n super(Imputer, self).__init__()\n self.type = impute_type\n self.seq_len = seq_len\n self.n_nodes = n_nodes\n self.n_dim = n_dim\n self.device = device\n\n if self.type == \"ADJ\":\n self.gcn = nconv()\n if self.type == \"GCN\":\n self.gcn = gcn(c_in=n_dim, c_out=n_dim, dropout=gcn_dropout,\n support_len=gcn_support_len, order=gcn_order)\n if self.type == \"MVN\":\n self.device = \"cpu\"\n self.jitter = jitter\n self.create_normalized_laplacian(adj.to(self.device))\n self.mvn_mean = 0.0\n\n\n def create_normalized_laplacian(self, adj):\n \"\"\"Normalized graph Laplacian\"\"\"\n adjacency_matrix = adj.clone().fill_diagonal_(0.0)\n degree_matrix = torch.diag(\n 1.0 / adjacency_matrix.sum(-1).sqrt())\n degree_matrix[degree_matrix == float(\"inf\")] = 0.0\n matrix_matrix_product = degree_matrix.mm(\n adjacency_matrix).mm(degree_matrix)\n self.graph_laplacian = torch.eye(self.n_nodes, device=self.device) - \\\n matrix_matrix_product\n self.graph_laplacian = self.graph_laplacian.to(self.device)\n\n\n def forward(self, x, supports=None):\n imputed_x = x\n indices = (x == float(\"-inf\")).nonzero(as_tuple=True)\n if self.type != \"\" and len(indices[-1]) != 0:\n if self.type == \"ZERO\":\n imputed_x[indices] = 0.0\n elif self.type == \"LAST\":\n for _ in range(1, self.seq_len):\n seq_len_indices = indices[-1]\n left_shifted_indices = \\\n torch.clamp(seq_len_indices - 1, min=0)\n imputed_x[indices] = imputed_x[\n (indices[0], indices[1], indices[2],\n left_shifted_indices)]\n indices = \\\n (imputed_x == float(\"-inf\")).nonzero(as_tuple=True)\n if len(indices[-1]) == 0 or \\\n (indices[-1] == 0).all() or \\\n (len(indices[-1]) == len(seq_len_indices)) and \\\n (indices[-1] == seq_len_indices).all():\n break\n # default left-overs to zeros\n imputed_x[indices] = 0.0\n elif self.type == \"MEAN\":\n lookup = {}\n indices = torch.stack(indices, dim=1)\n for index in indices:\n batch = index[0].item()\n dim = index[1].item()\n node = index[2].item()\n seq = index[3].item()\n\n try:\n imputed_x[batch, dim, node, seq] = lookup[batch, node]\n except:\n mean = imputed_x[batch, dim, node, :][\n imputed_x[batch, dim, node, :] !=\n float(\"-inf\")].mean()\n mean = 0.0 if mean == float(\"-inf\") or \\\n torch.isnan(mean) else mean\n imputed_x[batch, dim, node, seq] = mean\n lookup[batch, node] = mean\n elif self.type in [\"ADJ\", \"GCN\"]:\n if self.type == \"ADJ\":\n supports = supports[0].to(x.device)\n else:\n imputed_x = x.clone().to(self.device)\n\n imputed_x[indices] = 0.0\n gcn_x = self.gcn(imputed_x, supports)\n imputed_x[indices] = gcn_x[indices]\n elif self.type == \"MVN\":\n lookup = set()\n for batch, dim, node, seq in zip(*indices):\n batch_ = batch.item()\n seq_ = seq.item()\n dim_ = dim.item()\n if (batch_, seq_) not in lookup:\n # Find missing nodes at each time slice\n unobserved_nodes = (x[batch_, dim_, :, seq_] ==\n float(\"-inf\")).nonzero(as_tuple=True)\n n_missing_nodes = len(unobserved_nodes[0])\n n_obs_nodes = self.n_nodes - n_missing_nodes\n unobs_indices = (\n batch.repeat(n_missing_nodes),\n dim.repeat(n_missing_nodes),\n unobserved_nodes[0],\n seq.repeat(n_missing_nodes))\n if n_missing_nodes == self.n_nodes:\n # Use default mean if all nodes are missing\n imputed_x[unobs_indices] = self.mvn_mean\n else:\n observed_nodes = torch.from_numpy(\n np.setdiff1d(np.arange(self.n_nodes),\n unobserved_nodes[0].numpy()))\n obs_indices = (\n batch.repeat(n_obs_nodes),\n dim.repeat(n_obs_nodes),\n observed_nodes,\n seq.repeat(n_obs_nodes))\n x_obs = x[obs_indices] - self.mvn_mean\n x_obs = x_obs.contiguous().reshape(-1, 1)\n obs_row, obs_col = zip(*itertools.product(\n observed_nodes.tolist(), observed_nodes.tolist()))\n gl_obs = self.graph_laplacian[\n (torch.tensor(obs_row), torch.tensor(obs_col))]\n gl_obs = gl_obs.contiguous().reshape(\n n_obs_nodes, n_obs_nodes)\n try:\n gl_obs.diagonal().add_(self.jitter)\n chol_gl_obs = torch.cholesky(gl_obs)\n lhs = torch.cholesky_solve(x_obs, chol_gl_obs)\n except:\n gl_obs_inv = torch.inverse(gl_obs)\n lhs = gl_obs_inv.mm(x_obs)\n\n unobs_row, unobs_col = zip(*itertools.product(\n unobserved_nodes[0].tolist(), observed_nodes.tolist()))\n gl_unobs = self.graph_laplacian[\n (torch.tensor(unobs_row), torch.tensor(unobs_col))]\n gl_unobs = gl_unobs.contiguous().reshape(\n n_missing_nodes, n_obs_nodes)\n x_imputed = self.mvn_mean + torch.mm(gl_unobs, lhs)\n imputed_x[unobs_indices] = x_imputed.squeeze()\n\n lookup.add((batch_, seq_))\n else:\n return NotImplementedError()\n\n\n return imputed_x.contiguous()\n\n\nclass nconv(nn.Module):\n def __init__(self):\n super(nconv, self).__init__()\n\n\n def forward(self, x, A):\n x = torch.einsum('ncvl,vw->ncwl', x, A)\n\n return x.contiguous()\n\n\nclass gcn(nn.Module):\n def __init__(self, c_in, c_out, dropout=0.0, support_len=3, order=2):\n super(gcn, self).__init__()\n self.nconv = nconv()\n c_in = (order * support_len + 1) * c_in\n self.mlp = nn.Linear(c_in, c_out)\n self.dropout = dropout\n self.order = order\n\n\n def forward(self, x, support):\n out = [x]\n x0 = x\n for a in support:\n x1 = self.nconv(x, a)\n out.append(x1)\n for k in range(2, self.order + 1):\n x2 = 2 * self.nconv(x1, a) - x0\n out.append(x2)\n x1, x0 = x2, x1\n\n h = torch.cat(out, dim=1)\n h = self.mlp(h.permute(0, 2, 3, 1)).permute(0, 3, 1, 2)\n h = F.dropout(h, self.dropout, training=self.training)\n\n return h\n\n\nif __name__ == \"__main__\":\n SEQ_LENGTH = 3\n BATCH_SIZE = 1\n N_NODES = 2\n DIM = 1\n\n # [[[1, 2, 3]\n # [4, 5, 6]]]\n data = torch.arange(1, 1 + N_NODES * SEQ_LENGTH, dtype=float).reshape(\n BATCH_SIZE, DIM, N_NODES, SEQ_LENGTH)\n\n # [[[-inf, 2, 3]\n # [4, 5, -inf]]]\n left_missing = data.scatter(\n -1, torch.tensor([[[[0], [2]]]]), float(\"-inf\"))\n\n # [[[-inf, -inf, 3]\n # [4, -inf, -inf]]]\n block_missing = data.scatter(\n -1, torch.tensor([[[[0, 1], [1, 2]]]]), float(\"-inf\"))\n\n # [[[-inf, -inf, -inf]\n # [4, 5, 6]]]\n row_missing = data.scatter(\n -1, torch.tensor([[[[0, 1, 2], ]]]), float(\"-inf\"))\n\n #\n # NON IMPUTATION\n #\n non_impute = Imputer(\"\", N_NODES, DIM, SEQ_LENGTH)\n imputed_left_missing = non_impute(left_missing)\n imputed_data = non_impute(data)\n assert (left_missing == imputed_left_missing).all()\n assert (data == imputed_data).all()\n\n #\n # IMPUTATION WITH ZEROS\n #\n zero_impute = Imputer(\"ZERO\", N_NODES, DIM, SEQ_LENGTH)\n\n # [[[-inf, 2, 3] ---> [[[0.0, 2, 3]\n # [4, 5, -inf]]] [4, 5, 0.0]]]\n left_missing_ground_truth = data.scatter(\n -1, torch.tensor([[[[0], [2]]]]), 0.0)\n imputed_data = zero_impute(left_missing)\n assert (imputed_data == left_missing_ground_truth).all()\n\n # [[[-inf, -inf, 3] ---> [[[0.0, 0.0, 3]\n # [4, -inf, -inf]]] [4, 0.0, 0.0]]]\n block_missing_ground_truth = data.scatter(\n -1, torch.tensor([[[[0, 1], [1, 2]]]]), 0.0)\n imputed_data = zero_impute(block_missing)\n assert (imputed_data == block_missing_ground_truth).all()\n\n # [[[-inf, -inf, -inf] ---> [[[0.0, 0.0, 0.0]\n # [4, 5, 6]]] [4, 5, 6]]]\n row_missing_ground_truth = data.scatter(\n -1, torch.tensor([[[[0, 1, 2], ]]]), 0.0)\n imputed_data = zero_impute(row_missing)\n assert (imputed_data == row_missing_ground_truth).all()\n\n #\n # IMPUTATION WITH LAST VALUE IN WINDOW, DEFAULT TO 0.0\n #\n last_impute = Imputer(\"LAST\", N_NODES, DIM, SEQ_LENGTH)\n\n # [[[-inf, 2, 3]\n # [4, 5, -inf]]]\n left_missing = data.scatter(\n -1, torch.tensor([[[[0], [2]]]]), float(\"-inf\"))\n\n # [[[-inf, -inf, 3]\n # [4, -inf, -inf]]]\n block_missing = data.scatter(\n -1, torch.tensor([[[[0, 1], [1, 2]]]]), float(\"-inf\"))\n\n # [[[-inf, -inf, -inf]\n # [4, 5, 6]]]\n row_missing = data.scatter(\n -1, torch.tensor([[[[0, 1, 2], ]]]), float(\"-inf\"))\n\n # [[[-inf, 2, 3] ---> [[[0.0, 2, 3]\n # [4, 5, -inf]]] [4, 5, 5]]]\n left_missing_ground_truth = data.scatter(\n -1, torch.tensor([[[[0], ]]]), 0.0)\n left_missing_ground_truth[0, 0, 1, 2] = 5\n imputed_data = last_impute(left_missing)\n assert (imputed_data == left_missing_ground_truth).all()\n\n # [[[-inf, -inf, 3] ---> [[[0.0, 0.0, 3]\n # [4, -inf, -inf]]] [4, 4, 4]]]\n block_missing_ground_truth = data.scatter(\n -1, torch.tensor([[[[0, 1], ]]]), 0.0)\n block_missing_ground_truth[0, 0, 1, 1] = \\\n block_missing_ground_truth[0, 0, 1, 2] = 4.\n imputed_data = last_impute(block_missing)\n assert (imputed_data == block_missing_ground_truth).all()\n\n # [[[-inf, -inf, -inf] ---> [[[0.0, 0.0, 0.0]\n # [4, 5, 6]]] [4, 5, 6]]]\n row_missing_ground_truth = data.scatter(\n -1, torch.tensor([[[[0, 1, 2], ]]]), 0.0)\n imputed_data = last_impute(row_missing)\n assert (imputed_data == row_missing_ground_truth).all()\n\n #\n # IMPUTATION WITH MEAN VALUE IN WINDOW, DEFAULT TO 0.0\n #\n mean_impute = Imputer(\"MEAN\", N_NODES, DIM, SEQ_LENGTH)\n\n # [[[-inf, 2, 3]\n # [4, 5, -inf]]]\n left_missing = data.scatter(\n -1, torch.tensor([[[[0], [2]]]]), float(\"-inf\"))\n\n # [[[-inf, -inf, 3]\n # [4, -inf, -inf]]]\n block_missing = data.scatter(\n -1, torch.tensor([[[[0, 1], [1, 2]]]]), float(\"-inf\"))\n\n # [[[-inf, -inf, -inf]\n # [4, 5, 6]]]\n row_missing = data.scatter(\n -1, torch.tensor([[[[0, 1, 2], ]]]), float(\"-inf\"))\n\n # [[[-inf, 2, 3] ---> [[[2.5, 2, 3]\n # [4, 5, -inf]]] [4, 5, 4.5]]]\n left_missing_ground_truth = data.scatter(\n -1, torch.tensor([[[[0], ]]]), 2.5)\n left_missing_ground_truth[0, 0, 1, 2] = 4.5\n imputed_data = mean_impute(left_missing)\n assert (imputed_data == left_missing_ground_truth).all()\n\n # [[[-inf, -inf, 3] ---> [[[3, 3, 3]\n # [4, -inf, -inf]]] [4, 4, 4]]]\n block_missing_ground_truth = data.scatter(\n -1, torch.tensor([[[[0, 1], ]]]), 3)\n block_missing_ground_truth[0, 0, 1, 1] = \\\n block_missing_ground_truth[0, 0, 1, 2] = 4.\n imputed_data = mean_impute(block_missing)\n assert (imputed_data == block_missing_ground_truth).all()\n\n # [[[-inf, -inf, -inf] ---> [[[0.0, 0.0, 0.0]\n # [4, 5, 6]]] [4, 5, 6]]]\n row_missing_ground_truth = data.scatter(\n -1, torch.tensor([[[[0, 1, 2], ]]]), 0.0)\n imputed_data = mean_impute(row_missing)\n assert (imputed_data == row_missing_ground_truth).all()\n\n #\n # IMPUTATION WITH 1 HOP NEIGHBOUR'S AVERAGE, DEFAULT TO 0.0\n #\n adj = torch.tensor([[0.1, 0.9],\n [0.6, 0.4]]).double()\n one_hop_impute = Imputer(\"ADJ\", N_NODES, DIM, SEQ_LENGTH)\n\n # [[[-inf, 2, 3]\n # [4, 5, -inf]]]\n left_missing = data.scatter(\n -1, torch.tensor([[[[0], [2]]]]), float(\"-inf\"))\n\n # [[[-inf, -inf, 3]\n # [4, -inf, -inf]]]\n block_missing = data.scatter(\n -1, torch.tensor([[[[0, 1], [1, 2]]]]), float(\"-inf\"))\n\n # [[[-inf, -inf, -inf]\n # [4, 5, 6]]]\n row_missing = data.scatter(\n -1, torch.tensor([[[[0, 1, 2], ]]]), float(\"-inf\"))\n\n # [[[-inf, 2, 3] ---> [[[3.6, 2, 3]\n # [4, 5, -inf]]] [4, 5, 1.8]]]\n left_missing_ground_truth = data.scatter(\n -1, torch.tensor([[[[0], ]]]), 3.6)\n left_missing_ground_truth[0, 0, 1, 2] = 1.8\n imputed_data = one_hop_impute(left_missing, [adj.T])\n assert torch.allclose(imputed_data, left_missing_ground_truth)\n\n # [[[-inf, -inf, 3] ---> [[[3.6, 0, 3]\n # [4, -inf, -inf]]] [4, 0, 1.8]]]\n block_missing_ground_truth = data.scatter(\n -1, torch.tensor([[[[0], ]]]), 3.6)\n block_missing_ground_truth[0, 0, 1, 2] = 1.8\n block_missing_ground_truth = block_missing_ground_truth.scatter(\n -1, torch.tensor([[[[1], [1]]]]), 0.0)\n imputed_data = one_hop_impute(block_missing, [adj.T])\n assert torch.allclose(imputed_data, block_missing_ground_truth)\n\n # [[[-inf, -inf, -inf] ---> [[[3.6, 4.5, 5.4]\n # [4, 5, 6]]] [4, 5, 6]]]\n row_missing_ground_truth = data.scatter(\n -1, torch.tensor([[[[0], ]]]), 3.6)\n row_missing_ground_truth = row_missing_ground_truth.scatter(\n -1, torch.tensor([[[[1], ]]]), 4.5)\n row_missing_ground_truth = row_missing_ground_truth.scatter(\n -1, torch.tensor([[[[2], ]]]), 5.4)\n imputed_data = one_hop_impute(row_missing, [adj.T])\n assert torch.allclose(imputed_data, row_missing_ground_truth)\n\n #\n # IMPUTATION WITH MVN, DEFAULT TO 0.0\n #\n adj = torch.tensor([[0.1, 0.9],\n [0.6, 0.4]]).double()\n\n # gl = [[1.0, -1.2247],\n # [-0.8165, 1.0]]\n gl = torch.tensor(csgraph.laplacian(adj.numpy(), normed=True))\n mvn_impute = Imputer(\"MVN\", N_NODES, DIM, SEQ_LENGTH, adj=adj)\n\n # Test normalized graph laplacian\n assert torch.allclose(gl, mvn_impute.graph_laplacian, atol=1e-8)\n\n # [[[-inf, 2, 3]\n # [4, 5, -inf]]]\n left_missing = data.scatter(\n -1, torch.tensor([[[[0], [2]]]]), float(\"-inf\"))\n\n # [[[-inf, -inf, 3]\n # [4, -inf, -inf]]]\n block_missing = data.scatter(\n -1, torch.tensor([[[[0, 1], [1, 2]]]]), float(\"-inf\"))\n\n # [[[-inf, -inf, -inf]\n # [4, 5, 6]]]\n row_missing = data.scatter(\n -1, torch.tensor([[[[0, 1, 2], ]]]), float(\"-inf\"))\n\n # [[[-inf, 2, 3] ---> [[[-4.8990, 2, 3]\n # [4, 5, -inf]]] [4, 5, -2.4495]]]\n left_missing_ground_truth = data.scatter(\n -1, torch.tensor([[[[0], ]]]), -4.8990)\n left_missing_ground_truth[0, 0, 1, 2] = -2.4495\n imputed_data = mvn_impute(left_missing)\n assert torch.allclose(imputed_data, left_missing_ground_truth, atol=1e-4)\n\n # [[[-inf, -inf, 3] ---> [[[-4.8990, 0, 3]\n # [4, -inf, -inf]]] [4, 0, -2.4495]]]\n block_missing_ground_truth = data.scatter(\n -1, torch.tensor([[[[0], ]]]), -4.8990)\n block_missing_ground_truth[0, 0, 1, 2] = -2.4495\n block_missing_ground_truth = block_missing_ground_truth.scatter(\n -1, torch.tensor([[[[1], [1]]]]), 0.0)\n imputed_data = mvn_impute(block_missing)\n assert torch.allclose(imputed_data, block_missing_ground_truth, atol=1e-4)\n\n # [[[-inf, -inf, -inf] ---> [[[-4.8990, -6.1237, -7.3485]\n # [4, 5, 6]]] [4, 5, 6]]]\n row_missing_ground_truth = data.scatter(\n -1, torch.tensor([[[[0], ]]]), -4.8990)\n row_missing_ground_truth = row_missing_ground_truth.scatter(\n -1, torch.tensor([[[[1], ]]]), -6.1237)\n row_missing_ground_truth = row_missing_ground_truth.scatter(\n -1, torch.tensor([[[[2], ]]]), -7.3485)\n imputed_data = mvn_impute(row_missing)\n assert torch.allclose(imputed_data, row_missing_ground_truth)\n","sub_path":"imputer.py","file_name":"imputer.py","file_ext":"py","file_size_in_byte":17781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"139221103","text":"import pygame\nfrom model.CarregadorImagem import load_image\n\nclass Wall(pygame.sprite.Sprite):\n \"\"\"This class represents the bar at the bottom that the player controls \"\"\"\n def __init__(self, x, y, width, height):\n \"\"\" Constructor function \"\"\"\n # Call the parent's constructor\n pygame.sprite.Sprite.__init__(self)\n\n # Make a BLUE wall, of the size specified in the parameters\n self.image, self.rect = load_image('view/img/wall.jpg')\n\n # Make our top-left corner the passed-in location.\n self.rect = self.image.get_rect()\n self.rect.y = y\n self.rect.x = x","sub_path":"model/Sprites/Wall.py","file_name":"Wall.py","file_ext":"py","file_size_in_byte":623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"349972706","text":"import requests\nimport json\nimport time\nfrom flask import Flask, jsonify, request\nfrom splitwise import Splitwise\nfrom splitwise.expense import Expense\nfrom splitwise.user import ExpenseUser\n\napp = Flask(__name__)\n\nstate = {\n 'john': {'balance': 3000, 'credit': 999, 'rewards': 1337},\n 'mary': {'balance': 200, 'credit': 700, 'rewards': 500},\n 'leonard': {'balance': 0, 'credit': 100, 'rewards': 1}\n}\nAUTH_THRESH = 60\nauth = time.time() - 60\n\nip_alexa = '82.132.222.99'\n\n#splitwise shit\nsession = {}\nconsumer_key = \"8K5e87K3y5haqW8hmG6x6mbP8GeOwyFqoed01b6q\"\nconsumer_secret = \"pW2YnEoK7vuiNCyES5c6Rvj2iBo0z5xOaFfujm4L\"\nsession['access_token'] = {'oauth_token': 'y5dvUvYXr5MO038WUBBpfCVKoYSMxHq7jQjHqGJG', 'oauth_token_secret': 'CyoxnwNMTi9sZ5BMD1ASl1r6e7Z9SRahLZq58lY6'}\nsObj = Splitwise(consumer_key,\n consumer_secret)\nsObj.setAccessToken(session['access_token'])\n\ndef add_bill(cost=100.0):\n users = []\n group = sObj.getGroup(10204809)\n people = group.getMembers()\n\n expense = Expense()\n expense.setCost(str(cost))\n expense.setDescription(\"Capital One Transfer\")\n # per_person = str(round(cost / len(people), 2))\n per_person = cost\n\n paying_user =sObj.getCurrentUser()\n paying_id = paying_user.getId()\n paying_expense_user = ExpenseUser()\n paying_expense_user.setId(paying_id)\n paying_expense_user.setPaidShare(str(cost))\n paying_expense_user.setOwedShare(per_person)\n users.append(paying_expense_user)\n\n\n for friend in people:\n id = friend.getId()\n if id == paying_id:\n continue\n user = ExpenseUser()\n user.setId(id)\n user.setPaidShare('0.0')\n user.setOwedShare(per_person)\n users.append(user)\n expense.setUsers(users)\n expense = sObj.createExpense(expense)\n print(expense.getId())\n\n@app.route('/splitwise/', methods=['GET', 'POST'])\ndef splitwise():\n data = request.get_json()\n value = data['value']\n add_bill(int(value))\n\n@app.route('/authenticate/', methods=['GET', 'POST'])\ndef authenticate():\n data = request.get_json()\n\n target = data['target']\n value = data['value']\n source = data['source']\n operation = data['operation']\n # Make a transfer\n if operation == 'transfer':\n if state[source]['balance'] < value:\n return jsonify({'auth': 0})\n\n if not phone_auth():\n return jsonify({'auth': 0})\n\n state[source]['balance'] -= value\n state[target]['balance'] += value\n\n print(state)\n global auth\n auth = -1\n return jsonify({'auth': 1})\n # Check users' current balance\n elif operation == 'balance':\n return jsonify({'value':state[source]['balance']})\n # Check users' credit score\n elif operation == 'credit_score':\n return jsonify({'value':state[source]['credit']})\n # Check users' reward score\n elif operation == 'reward_points':\n return jsonify({'value':state[source]['rewards']})\n\ndef phone_auth():\n delta = time.time() - auth\n print(delta)\n if delta <= AUTH_THRESH:\n return True\n \n return False\n\n@app.route('/ping/', methods=['GET', 'POST', 'OPTIONS'])\ndef ping():\n ip_phone = request.remote_addr\n \n print('phone: ' + ip_phone)\n print('alexa: ' + ip_alexa)\n if ip_phone[:5] == ip_alexa[:5]:\n global auth\n auth = time.time()\n print(time.time() - auth)\n print('Pinged!')\n \n data = request.get_json()\n return 'pinged'\n\nif __name__ == \"__main__\":\n app.run(host='0.0.0.0')\n\n# sample operations if the API documentation had worked \n\n# def transform_id(api_id, t_name):\n# result = 0\n# url = 'http://api.reimaginebanking.com/customers?key={}'.format(api_id)\n# f_name, l_name = t_name.split(' ')\n\n# account_list = requests.get(url).json()\n# for n in range(account_list.len()):\n# if (account_list[n]['first_name'] == f_name) and (account_list[n]['first_name'] == l_name):\n# result = account_list[n]['_id']\n\n# return result\n\n# def proceed_request(cus_id, api_id, payload_operation, payload_accname, amount, points, transfer_id):\n\n# url = 'http://api.reimaginebanking.com/customers/{}/accounts?key={}'.format(cus_id, api_id)\n\n# # Create a Savings Account\n# if payload_operation == 'Savings':\n# payload = {\n# \"operation\": payload_operation,\n# \"nickname\": payload_accname,\n# \"rewards\": points,\n# \"balance\": amount,\n# }\n# response = requests.post(\n# url,\n# data=json.dumps(payload),\n# headers={'content-operation': 'application/json'},\n# )\n# if response.status_code == 201:\n# return 'Account created'\n# else:\n# return 'Account creation failed')\n\n# # Make a Transfer\n# elif payload_operation == 'Transfer':\n# payload = {\n# \"operation\": payload_operation,\n# \"nickname\": payload_accname,\n# \"balance\": amount,\n# \"transfer\": transfer_id, # id of the receiving account\n# }\n# response = requests.post(\n# url,\n# data=json.dumps(payload),\n# headers={'content-operation': 'application/json'},\n# )\n# if response.status_code == 202:\n# return 'Transfer executed'\n# else:\n# return 'Transfer failed'\n# else:\n# return 'Transfer request failed'\n\n# # Check the balance of an account\n# elif payload_operation == 'Balance':\n# acc_details = requests.get(url).json()\n# for n in range(acc_details.len()):\n# if (acc_details[n]['nickname'] == payload_accname)):\n# result = acc_details[n]['balance']\n# return 'Current balance is '+result+' '+acc_details[n]['currency']\n# return 'Account balance is unavailable'\n# else:\n# return 'Request operation not supported'\n\n# return 'Request failed'\n\n\n# if __name__ == \"__main__\":\n\n# t_id = transform_id(key, t_name)\n# proceed_request(id, key, 'Savings', 'test', 10, 0, t_id) # Parameters taken from Alexa App\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"329423025","text":"# !/usr/bin/env python3\nimport numpy as np\nimport keras\nimport cv2 as cv\nfrom imutils import paths\nfrom keras.applications.inception_v3 import InceptionV3\nfrom keras.models import Model\nfrom keras.layers import Dense, GlobalAveragePooling2D, Flatten\nfrom keras import backend as K\n\n\ndef extract_name(fp: str):\n return fp.split('/')[-2]\n\n\ndef extract_datasets(image_paths):\n X_binary = []\n Y_binary = []\n X_cat = []\n Y_cat = []\n for fp in image_paths:\n img = cv.imread(fp)\n name = extract_name(fp)\n img = cv.resize(img, (75, 75), interpolation=cv.INTER_AREA)\n if name == 'empty':\n Y_binary.append([1, 0])\n X_binary.append(img)\n\n else:\n Y_binary.append([0, 1])\n X_binary.append(img)\n ytemp = [0] * 9\n ytemp[int(name) - 1] = 1\n Y_cat.append(ytemp)\n X_cat.append(img)\n\n return np.array(X_binary), np.array(Y_binary), np.array(X_cat), np.array(Y_cat)\n\n\nimg_paths = list(paths.list_images('./images/dataset'))\nX_b, Y_b, X_c, Y_c = extract_datasets(img_paths)\n\nbase_model = InceptionV3(weights='imagenet', include_top=False, input_shape=(75, 75, 3))\n\nx = base_model.output\nx = Flatten()(x)\n# x = Dense(256, activation = 'relu')(x)\npred = Dense(9, activation='softmax', kernel_regularizer=keras.regularizers.l1_l2())(x)\n\nmodel = Model(input=base_model.input, output=pred)\nmodel.summary()\n\nfor layer in base_model.layers:\n layer.trainable = False\nfrom keras.optimizers import RMSprop\n\nmodel.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['acc'])\n\nmodel.fit(x=X_c, y=Y_c, batch_size=32, epochs=10, validation_split=0.2)\n\nfor layer in model.layers[:249]:\n layer.trainable = False\nfor layer in model.layers[249:]:\n layer.trainable = True\n\nfrom keras.optimizers import SGD\n\nmodel.compile(optimizer=SGD(learning_rate=0.0001, momentum=0.9), loss='categorical_crossentropy', metrics=['acc'])\nmodel.fit(x=X_c, y=Y_c, batch_size=32, epochs=10, validation_split=0.2)\n","sub_path":"train_classifier.py","file_name":"train_classifier.py","file_ext":"py","file_size_in_byte":2025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"338591863","text":"# coding=utf-8\n# --------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for\n# license information.\n#\n# Code generated by Microsoft (R) AutoRest Code Generator.\n# Changes may cause incorrect behavior and will be lost if the code is\n# regenerated.\n# --------------------------------------------------------------------------\n\nfrom msrest.serialization import Model\n\n\nclass JobDetails(Model):\n \"\"\"Job details.\n\n Variables are only populated by the server, and will be ignored when\n sending a request.\n\n All required parameters must be populated in order to send to Azure.\n\n :param id: The job id.\n :type id: str\n :param name: The job name. Is not required for the name to be unique and\n it's only used for display purposes.\n :type name: str\n :param container_uri: Required. The blob container SAS uri, the container\n is used to host job data.\n :type container_uri: str\n :param input_data_uri: The input blob SAS uri, if specified, it will\n override the default input blob in the container.\n :type input_data_uri: str\n :param input_data_format: Required. The format of the input data.\n :type input_data_format: str\n :param input_params: The input parameters for the job. JSON object used by\n the target solver. It is expected that the size of this object is small\n and only used to specify parameters for the execution target, not the\n input data.\n :type input_params: object\n :param provider_id: Required. The unique identifier for the provider.\n :type provider_id: str\n :param target: Required. The target identifier to run the job.\n :type target: str\n :param metadata: The job metadata. Metadata provides client the ability to\n store client-specific information\n :type metadata: dict[str, str]\n :param output_data_uri: The output blob SAS uri. When a job finishes\n successfully, results will be uploaded to this blob.\n :type output_data_uri: str\n :param output_data_format: The format of the output data.\n :type output_data_format: str\n :ivar status: The job status. Possible values include: 'Waiting',\n 'Executing', 'Succeeded', 'Failed', 'Cancelled'\n :vartype status: str or ~azure.quantum.models.JobStatus\n :ivar creation_time: The creation time of the job.\n :vartype creation_time: datetime\n :ivar begin_execution_time: The time when the job began execution.\n :vartype begin_execution_time: datetime\n :ivar end_execution_time: The time when the job finished execution.\n :vartype end_execution_time: datetime\n :ivar cancellation_time: The time when a job was successfully cancelled.\n :vartype cancellation_time: datetime\n :ivar error_data: The error data for the job. This is expected only when\n Status 'Failed'.\n :vartype error_data: ~azure.quantum.models.ErrorData\n \"\"\"\n\n _validation = {\n 'container_uri': {'required': True},\n 'input_data_format': {'required': True},\n 'provider_id': {'required': True},\n 'target': {'required': True},\n 'status': {'readonly': True},\n 'creation_time': {'readonly': True},\n 'begin_execution_time': {'readonly': True},\n 'end_execution_time': {'readonly': True},\n 'cancellation_time': {'readonly': True},\n 'error_data': {'readonly': True},\n }\n\n _attribute_map = {\n 'id': {'key': 'id', 'type': 'str'},\n 'name': {'key': 'name', 'type': 'str'},\n 'container_uri': {'key': 'containerUri', 'type': 'str'},\n 'input_data_uri': {'key': 'inputDataUri', 'type': 'str'},\n 'input_data_format': {'key': 'inputDataFormat', 'type': 'str'},\n 'input_params': {'key': 'inputParams', 'type': 'object'},\n 'provider_id': {'key': 'providerId', 'type': 'str'},\n 'target': {'key': 'target', 'type': 'str'},\n 'metadata': {'key': 'metadata', 'type': '{str}'},\n 'output_data_uri': {'key': 'outputDataUri', 'type': 'str'},\n 'output_data_format': {'key': 'outputDataFormat', 'type': 'str'},\n 'status': {'key': 'status', 'type': 'str'},\n 'creation_time': {'key': 'creationTime', 'type': 'iso-8601'},\n 'begin_execution_time': {'key': 'beginExecutionTime', 'type': 'iso-8601'},\n 'end_execution_time': {'key': 'endExecutionTime', 'type': 'iso-8601'},\n 'cancellation_time': {'key': 'cancellationTime', 'type': 'iso-8601'},\n 'error_data': {'key': 'errorData', 'type': 'ErrorData'},\n }\n\n def __init__(self, **kwargs):\n super(JobDetails, self).__init__(**kwargs)\n self.id = kwargs.get('id', None)\n self.name = kwargs.get('name', None)\n self.container_uri = kwargs.get('container_uri', None)\n self.input_data_uri = kwargs.get('input_data_uri', None)\n self.input_data_format = kwargs.get('input_data_format', None)\n self.input_params = kwargs.get('input_params', None)\n self.provider_id = kwargs.get('provider_id', None)\n self.target = kwargs.get('target', None)\n self.metadata = kwargs.get('metadata', None)\n self.output_data_uri = kwargs.get('output_data_uri', None)\n self.output_data_format = kwargs.get('output_data_format', None)\n self.status = None\n self.creation_time = None\n self.begin_execution_time = None\n self.end_execution_time = None\n self.cancellation_time = None\n self.error_data = None\n","sub_path":"src/quantum/azext_quantum/vendored_sdks/azure_quantum/models/job_details.py","file_name":"job_details.py","file_ext":"py","file_size_in_byte":5533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"344073602","text":"import logging\nimport sys\n\nfrom settings import DEBUG\n\n\ndef get_logger(lvl=logging.DEBUG, log_file_name=None, logger_name='default', elk_host=None, elk_port=None):\n logger = logging.getLogger(logger_name)\n logger.setLevel(lvl)\n stdout_formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n\n if elk_host and elk_port:\n import logstash\n logstash_handler = logstash.LogstashHandler(elk_host, int(elk_port))\n logstash_handler.setLevel(lvl)\n logger.addHandler(logstash_handler)\n\n if log_file_name:\n hdlr = logging.FileHandler(log_file_name)\n hdlr.setFormatter(stdout_formatter)\n hdlr.setLevel(lvl)\n logger.addHandler(hdlr)\n\n stdout_handler = logging.StreamHandler(sys.stdout)\n stdout_handler.setLevel(lvl)\n stdout_handler.setFormatter(stdout_formatter)\n logger.addHandler(stdout_handler)\n\n if not DEBUG:\n logger.disabled = True\n\n return logger\n\nlogger = get_logger(logger_name='i008')\n","sub_path":"logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":1008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"237250028","text":"import dash\nfrom dash import dcc, html\nfrom dash.dependencies import State, Input, Output\nimport dash_bootstrap_components as dbc\nimport plotly\nimport plotly.graph_objs as go\nfrom plotly import figure_factory as FF\nimport pandas as pd\nimport functools\nfrom common import app\nfrom common import graphconfig\nfrom tools import get_facet_group_options, logging_config, map_to_human_readable\nimport bwypy\nimport json\nimport logging\nfrom logging.config import dictConfig\n\ndictConfig(logging_config)\nlogger = logging.getLogger()\n\nwith open('config.json','r') as options_file:\n bwypy_options = json.load(options_file)\n\nbwypy.set_options(database=bwypy_options['settings']['dbname'], endpoint=bwypy_options['settings']['endpoint'])\nbw = bwypy.BWQuery(verify_fields=False,verify_cert=False)\n\nfacet_opts = get_facet_group_options(bw)\n\n# This will cache identical calls\n@functools.lru_cache(maxsize=32)\ndef get_results(group):\n bw.counttype = ['WordCount', 'TextCount']\n bw.groups = ['*'+group]\n bw.search_limits = { group + '__id' : {\"$lt\": 60 } }\n return bw.run()\n\nbw_date = bwypy.BWQuery(verify_fields=False,verify_cert=False)\n\n@functools.lru_cache(maxsize=32)\ndef get_date_distribution(group, facet):\n bw_date.groups = ['date_year']\n bw_date.counttype = ['TextCount']\n bw_date.search_limits = { group: facet }\n results = bw_date.run()\n df = results.frame(index=False)\n logging.debug(\"Got date distribution\")\n logging.debug(df)\n try:\n df = map_to_human_readable(df,group)\n logging.debug(\"Ran map to human readable\")\n logging.debug(df)\n except Exception as e:\n logging.error(\"ERROR with date distribution\")\n logging.error(e)\n df.date_year = pd.to_numeric(df.date_year)\n logging.debug(\"Converted dates to numeric\")\n df2 = df.query('(date_year > 1800) and (date_year < 2016)').sort_values('date_year', ascending=True)\n df2['smoothed'] = df2.TextCount.rolling(10, 0).mean()\n return df2\n\nheader = '''\n# Bookworm Bar Chart\nSelect a field and see the raw counts in the Bookworm database of the 17 million volume [HathiTrust](https://www.hathitrust.org) collection.\n'''\n\ncontrols = html.Div([\n dcc.Markdown(header),\n html.Label(\"Facet Group\", className='mb-2'),\n dcc.Dropdown(id='bar-group-dropdown', options=facet_opts, value='languages'),\n html.Label(\"Number of results to show\", className='mb-2'),\n dcc.Slider(id='trim-slider', min=10, max=60, value=20, step=5,\n marks={str(n): str(n) for n in range(10, 61, 10)}, className='py-0 px-0'),\n html.Label(\"Ignore unknown values:\", className='mb-2 pt-3'),\n dcc.RadioItems(\n id='drop-radio',\n options=[\n {'label': u'Yes', 'value': 'drop'},\n {'label': u'No', 'value': 'keep'}\n ],\n value='drop',\n labelClassName='mb-2'\n ),\n html.Label(\"Count by:\", className='mb-2'),\n dcc.RadioItems(id='counttype-dropdown', options=[\n {'label': u'# of Texts', 'value': 'TextCount'},\n {'label': u'# of Words', 'value': 'WordCount'}\n ], value='TextCount', labelClassName='mb-2')\n ],\n className='col-md-3 px-3')\n\napp.layout = html.Div([\n \n html.Div([\n controls,\n html.Div([dcc.Graph(id='bar-chart-main-graph', config=graphconfig)], className='col-md-9 px-3')\n ],\n className='row'),\n html.Div([\n html.Div([html.H2(\"Data\"), dcc.Graph(id='bar-data-table')], id='data-table', className='col-md-5 px-3'),\n html.Div([dcc.Graph(id='date-distribution')], id='graph-wrapper', className='col-md-7 px-3')\n ],\n className='row')\n\n], className='container-fluid')\n\n#def show_processing(facet,figure):\n#@app.callback(\n# Output('bar-group-dropdown', 'disabled'),\n# Input('bar-group-dropdown', 'value'),\n# Input('bar-chart-main-graph', 'figure'),\n# Input('bar-data-table', 'figure')\n#)\n#def show_processing(facet):#, chart, table):\n# logging.debug(dash.callback_context)\n# logging.debug(\"Show Processing\")\n# return False\n# logging.debug(\"Show Processing\")\n# logging.debug(dash.callback_context.triggered)\n# for element in dash.callback_context.triggered:\n# logging.debug(element['prop_id'])\n# context = dash.callback_context.triggered[0]['prop_id'].split('.')[0]\n# if len(context) > 0:\n# return True\n# else:\n# return False\n#\n# if context == 'bar-group-dropdown' or len(context) == 0:\n# logging.debug(context)\n# return False\n# else:\n# logging.debug(context)\n# return True\n# if context == 'bar-chart-main-graph':\n# return False\n# else:\n# return True\n\n@app.callback(\n Output('bar-chart-main-graph', 'figure'),\n Input('bar-group-dropdown', 'value'),\n Input('trim-slider', 'value'),\n Input('drop-radio', 'value'),\n Input('counttype-dropdown', 'value')\n)\ndef update_figure(group, trim_at, drop_radio, counttype):\n bw.groups = [group]\n logging.debug(\"Groups:\")\n logging.debug(bw.groups)\n results = get_results(group)\n logging.debug(\"Results for new figure:\")\n logging.debug(results)\n\n df = results.frame(index=False, drop_unknowns=(drop_radio=='drop'))\n logging.debug(\"Created DataFrame of results\")\n logging.debug(df)\n try:\n df = map_to_human_readable(df,group)\n logging.debug(\"Ran map to human readable\")\n except Exception as e:\n logging.error(\"ERROR occured!\")\n logging.error(e)\n df = df.copy()\n df_trimmed = df.head(trim_at)\n \n data = [\n go.Bar(\n x=df_trimmed[group],\n y=df_trimmed[counttype]\n )\n ]\n \n return {\n 'data': data,\n 'layout': {\n 'yTitle': counttype,\n 'title': group.replace('_', ' ').title()\n }\n }\n\n@app.callback(\n Output('bar-data-table', 'figure'),\n Input('bar-group-dropdown', 'value'),\n Input('drop-radio', 'value')\n)\ndef update_table(group, drop_radio):\n results = get_results(group)\n df = results.frame(index=False, drop_unknowns=(drop_radio=='drop'))\n logging.debug(\"Updated table\")\n logging.debug(df)\n df = map_to_human_readable(df,group)\n df = df.copy()\n return FF.create_table(df)\n #return html.Table(\n # Header\n #[html.Tr([html.Th(col) for col in df.columns])] +\n # Body\n #[html.Tr([\n # html.Td(df.iloc[i][col]) for col in df.columns\n # ]) for i in range(min(len(df), 100))]\n #)\n\n@app.callback(\n Output('date-distribution', 'figure'),\n Input('bar-chart-main-graph', 'hoverData'),\n State('bar-group-dropdown', 'value')\n)\ndef print_hover_data(clickData, group):\n if clickData:\n facet_value = clickData['points'][0]['x']\n\n with open('data/map_to_ld.json','r') as map_to_ld_file:\n map_to_ld = json.load(map_to_ld_file)\n\n if group in map_to_ld:\n df = get_date_distribution(group, map_to_ld[group][facet_value])\n else:\n df = get_date_distribution(group, facet_value)\n df = df.copy()\n data = [\n go.Scatter(\n x=df['date_year'],\n y=df['smoothed']\n )\n ]\n return {\n 'data': data,\n 'layout': {\n 'height': 300,\n 'yaxis': {'range': [0, int(df.smoothed.max())+100]},\n 'title': 'Date Distribution for ' + facet_value.replace('_', ' ').title()\n }\n }\n else:\n data = [\n go.Scatter(\n x=list(range(1800, 2016)),\n y=[0]*(2013-1800)\n )\n ]\n return {\n 'data': data,\n 'layout': {\n 'height': 300,\n 'yaxis': {'range': [0, 100000]},\n 'title': 'Select a ' + group.replace('_', ' ') + ' to see date distribution' }\n }\n \nif __name__ == '__main__':\n # app.scripts.config.serve_locally = False\n app.config.supress_callback_exceptions = True\n app.run_server(debug=True, port=10012, threaded=True, host='0.0.0.0')\n","sub_path":"bar_chart.py","file_name":"bar_chart.py","file_ext":"py","file_size_in_byte":8241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"285652637","text":"# -*- coding: utf-8 -*-\n__author__ = 'zyzy'\nimport requests\nimport json\nimport sys\nimport os.path\nimport time\n\n\nclass BaiduTranslate:\n def __init__(self, query, outfile=None, type='f'):\n self.query = query\n self.outfile = outfile\n self.type = type\n self.url = 'http://fanyi.baidu.com/v2transapi'\n self.url_bing = 'https://www.bing.com/translator/api/Dictionary/Lookup?from=en&to=zh-CHS'\n self.url_bing = 'https://www.bing.com/translator/api/Translate/TranslateArray?from=-&to=zh-CHS'\n self.header = {\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_2) AppleWebKit/604.4.7 (KHTML, like Gecko)'\n ' Version/11.0.2 Safari/604.4.7'\n }\n self.header_bing = {\n 'Referer': 'https://www.bing.com/translator/',\n 'Content-Type': 'application/json;charset=UTF-8',\n 'Origin': 'https://www.bing.com',\n 'Host': 'www.bing.com',\n 'Accept': 'application/json,text/javascript,*/*;q=0.01',\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_2) AppleWebKit/604.4.7 (KHTML, like Gecko)'\n ' Version/11.0.2 Safari/604.4.7'\n }\n self.post_date = {\n 'from': 'en',\n 'to': 'zh',\n 'query': 'test',\n 'transtype': 'translang',\n 'simple_means_flag': '3'\n }\n self.post_date_bing = {\n \"from\": \"en\",\n \"to\": \"zh-CHS\",\n }\n self.post_json_bing = json.dumps({\n \"from\": \"en\",\n \"to\": \"zh-CHS\",\n \"items\": [\n {\n # \"id\": str(int(time.time() * 1000))[10:0:-1],\n \"id\": '112785',\n \"text\": \"red\",\n \"wordAlignment\": \"\"\n }\n ]\n })\n\n def run(self):\n if self.outfile:\n with open(self.outfile, 'w')as w:\n if os.path.isfile(self.query) and self.type == 'f':\n with open(self.query, 'r') as f:\n while True:\n query = f.readline()\n if query:\n w.write(self.translate(query) + '\\n')\n else:\n break\n else:\n w.write(self.translate(self.query))\n return self.outfile\n else:\n result = ''\n if os.path.exists(self.query) and self.type == 'f':\n with open(self.query, 'r') as f:\n while True:\n query = f.readline()\n if query:\n result = result + self.translate(query) + '\\n'\n else:\n break\n else:\n result = self.translate(self.query)\n return result\n\n def translate(self, query):\n if self.check_cn(query):\n self.post_date['from'] = 'zh'\n self.post_date['to'] = 'en'\n else:\n self.post_date['from'] = 'en'\n self.post_date['to'] = 'zh'\n self.post_date['query'] = query\n response = requests.post(self.url, self.post_date, headers=self.header)\n response = response.content.decode()\n dict_response = json.loads(response)\n return dict_response['trans_result']['data'][0]['dst']\n\n def translate_bing(self, query):\n if self.check_cn(query):\n self.post_date_bing['from'] = 'zh-CHS'\n self.post_date_bing['to'] = 'en'\n self.url_bing = self.url_bing + 'en'\n else:\n self.post_date_bing['from'] = 'en'\n self.post_date_bing['to'] = 'zh-CHS'\n self.url_bing = self.url_bing + 'zh-CHS'\n # self.post_date_bing['items'][0]['text'] = query\n response = requests.post(self.url_bing, self.post_date_bing, self.post_json_bing, headers=self.header)\n response = response.content.decode()\n dict_response = json.loads(response)\n return dict_response['trans_result']['data'][0]['dst']\n\n def check_cn(self, str):\n for ch in str:\n if u'\\u4e00' <= ch <= u'\\u9fff':\n return True\n return False\n\n\nif __name__ == '__main__':\n # print(BaiduTranslate('red', None).run())\n try:\n query = sys.argv[1]\n except:\n print('请输入要翻译的内容或文件')\n exit()\n try:\n outfile = sys.argv[2]\n if not outfile.endswith('.txt'):\n outfile = None\n except:\n outfile = None\n\n print(BaiduTranslate(query, outfile).run())\n\n","sub_path":"ArticleSpider/utils/baidu_translate.py","file_name":"baidu_translate.py","file_ext":"py","file_size_in_byte":4705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"55794861","text":"#!/usr/bin/env python3\n\"\"\"\nFile Name : Problem108.py\nDate started : 2012-10-06\nDate solved : 2013-01-17\nRun Time : 0.83703 seconds\n\nIn the following equation, x, y, and n are positive integers.\n\n 1 1 1\n - + - = -\n x y n\n\nFor n = 4, there are exactly three distinct solutions.\n\n 1 1 1\n - + - = -\n 5 20 4\n\n 1 1 1\n - + - = -\n 6 12 4\n\n 1 1 1\n - + - = -\n 8 8 4\n\nWhat is the least value of n for which the number or distinct solutions\n exceeds one thousand?\n\nSOLUTION:\n\nBecause x and y are defined as non-negative integers, it is implied that x > n\nand y > n\n\nLet x = n + r, and y = n + s\n\nWe now have:\n\n 1 1 1\n ----- + ----- = -\n n + r n + s n\n\nAfter some algebra, we get:\n\n n ^ 2 = s * r\n\nSo n has to be a square number.\n\nWe want the first value n of such that\n 1/2 * d(n**2) > 1000\nwhere d(x) is defined as:\n d(x) = (a_1 + 1) * (a_2 + 1) * (a_3 + 1) * ...\nfor a_i being the power of i-th prime factor of n\n\n\"\"\"\n\nimport project_euler\nimport project_euler.primes\n\n\nPROBLEM_NUMBER = 108\nSOLVED = 1\n\n\ndef numberOfPrimeFactors(n, power=1):\n \"\"\"numberOfPrimeFactors(n, power)\n\n We want the first value n of such that\n 1/2 * d(n ** power) > 1000\n where d(x) is defined as:\n d(x) = (a_1 + 1) * (a_2 + 1) * (a_3 + 1) * ...\n for a_i being the power of i-th prime factor of n\n \"\"\"\n power = int(power)\n if power < 1:\n power = 1\n n = int(n)\n if n < 2:\n return 0\n prod = 1\n facts = project_euler.primes.primeFactors(n)\n seen = set()\n for k in facts:\n if k in seen:\n continue\n seen.add(k)\n prod *= power * facts.count(k) + 1\n return prod\n\n\ndef problem108(input_=None):\n c, n = -1, 0\n max_c, max_n = c, n\n while max_c <= 1000:\n n += 1\n c = (numberOfPrimeFactors(n, 2) + 1) // 2\n if c > max_c:\n max_c, max_n = c, n\n return max_n\n\n\ndef run():\n print(project_euler.print_timing(problem108))\n\n\nif __name__ == \"__main__\":\n run()\n\n","sub_path":"problems/Problem108.py","file_name":"Problem108.py","file_ext":"py","file_size_in_byte":2180,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"432222447","text":"# Python Program to compute X0^2 for the Null Hypothesis in Applied Statistics.\n# Input your expected and observed values one at a time.\n\n#Variable Declarations\nobserved = []\nexpected = []\nvalue=int(input(\"How many observed values do you have?: \"))\n\ndef printValues():\n print(\"Input Observed Values\")\n print(observed)\n print(\"Input Expected Values\")\n print(expected)\n\ndef inputValues():\n print(\"What are your values you wish to input for the Observed and expected?: \")\n\n for i in range(0, value):\n observ = input(\"Observed: \")\n observed.append(observ)\n expect = input(\"Expected: \")\n expected.append(expect)\n\ndef caluculateChiSquared():\n counter = 0\n Summation = 0\n for i in range(0,value):\n observed_value = float(observed[counter])\n expected_value = float(expected[counter])\n difference = observed_value - expected_value\n squared = (difference*difference)\n divide_by_expect = (squared / expected_value)\n Summation = Summation + divide_by_expect\n counter = counter + 1\n print(\"Summation = \")\n print(Summation)\n\ninputValues()\nprintValues()\ncaluculateChiSquared()\n","sub_path":"StatisticsWorkspace.py","file_name":"StatisticsWorkspace.py","file_ext":"py","file_size_in_byte":1172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"91961681","text":"#!/usr/bin/env python\n# license removed for brevity\nimport rospy\nfrom std_msgs.msg import String\nfrom std_msgs.msg import Float32\nfrom std_msgs.msg import Int16\n\n\ndef command_callback(data):\n rospy.loginfo(rospy.get_caller_id() + \"recevied %s\", data.data)\n\ndef node():\n speed_pub = rospy.Publisher('oscc/speed', Float32, queue_size=10)\n steer_pub = rospy.Publisher('oscc/steering', Int16, queue_size=10)\n rospy.Subscriber(\"command\", String, command_callback)\n\n rospy.init_node('dummy_node', anonymous=True)\n rospy.loginfo(\"node started\")\n rate = rospy.Rate(10) # 10hz\n\n\n spd=0.0\n while not rospy.is_shutdown():\n \n spd=(spd+0.1 if spd<100 else 0.0)\n steer=(35+spd//10 if spd<50 else -20-spd//10)\n\n speed_pub.publish(Float32(spd))\n steer_pub.publish(Int16(steer))\n\n rate.sleep()\n\nif __name__ == '__main__':\n try:\n node()\n except rospy.ROSInterruptException:\n pass","sub_path":"ws_testserver/src/myride_test_server/scripts/dummy_node.py","file_name":"dummy_node.py","file_ext":"py","file_size_in_byte":948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"446995055","text":"from __future__ import absolute_import\n\nimport logging\n\nfrom mock import patch\nimport six\n\nfrom ably import AblyException\nfrom ably import AblyRest\nfrom ably import Capability\nfrom ably.types.tokendetails import TokenDetails\nfrom ably.types.tokenrequest import TokenRequest\n\nfrom test.ably.restsetup import RestSetup\nfrom test.ably.utils import VaryByProtocolTestsMetaclass, dont_vary_protocol, BaseTestCase\n\ntest_vars = RestSetup.get_test_vars()\nlog = logging.getLogger(__name__)\n\n\n@six.add_metaclass(VaryByProtocolTestsMetaclass)\nclass TestRestToken(BaseTestCase):\n\n def server_time(self):\n return self.ably.time()\n\n def setUp(self):\n capability = {\"*\": [\"*\"]}\n self.permit_all = six.text_type(Capability(capability))\n self.ably = AblyRest(key=test_vars[\"keys\"][0][\"key_str\"],\n rest_host=test_vars[\"host\"],\n port=test_vars[\"port\"],\n tls_port=test_vars[\"tls_port\"],\n tls=test_vars[\"tls\"])\n\n def per_protocol_setup(self, use_binary_protocol):\n self.ably.options.use_binary_protocol = use_binary_protocol\n self.use_binary_protocol = use_binary_protocol\n\n def test_request_token_null_params(self):\n pre_time = self.server_time()\n token_details = self.ably.auth.request_token()\n post_time = self.server_time()\n self.assertIsNotNone(token_details.token, msg=\"Expected token\")\n self.assertGreaterEqual(token_details.issued,\n pre_time,\n msg=\"Unexpected issued time\")\n self.assertLessEqual(token_details.issued,\n post_time,\n msg=\"Unexpected issued time\")\n self.assertEqual(self.permit_all,\n six.text_type(token_details.capability),\n msg=\"Unexpected capability\")\n\n def test_request_token_explicit_timestamp(self):\n pre_time = self.server_time()\n token_details = self.ably.auth.request_token(token_params={'timestamp': pre_time})\n post_time = self.server_time()\n self.assertIsNotNone(token_details.token, msg=\"Expected token\")\n self.assertGreaterEqual(token_details.issued,\n pre_time,\n msg=\"Unexpected issued time\")\n self.assertLessEqual(token_details.issued,\n post_time,\n msg=\"Unexpected issued time\")\n self.assertEqual(self.permit_all,\n six.text_type(Capability(token_details.capability)),\n msg=\"Unexpected Capability\")\n\n def test_request_token_explicit_invalid_timestamp(self):\n request_time = self.server_time()\n explicit_timestamp = request_time - 30 * 60 * 1000\n\n self.assertRaises(AblyException, self.ably.auth.request_token,\n token_params={'timestamp': explicit_timestamp})\n\n def test_request_token_with_system_timestamp(self):\n pre_time = self.server_time()\n token_details = self.ably.auth.request_token(query_time=True)\n post_time = self.server_time()\n self.assertIsNotNone(token_details.token, msg=\"Expected token\")\n self.assertGreaterEqual(token_details.issued,\n pre_time,\n msg=\"Unexpected issued time\")\n self.assertLessEqual(token_details.issued,\n post_time,\n msg=\"Unexpected issued time\")\n self.assertEqual(self.permit_all,\n six.text_type(Capability(token_details.capability)),\n msg=\"Unexpected Capability\")\n\n def test_request_token_with_duplicate_nonce(self):\n request_time = self.server_time()\n token_params = {\n 'timestamp': request_time,\n 'nonce': '1234567890123456'\n }\n token_details = self.ably.auth.request_token(\n token_params)\n self.assertIsNotNone(token_details.token, msg=\"Expected token\")\n\n self.assertRaises(AblyException, self.ably.auth.request_token,\n token_params)\n\n def test_request_token_with_capability_that_subsets_key_capability(self):\n capability = Capability({\n \"onlythischannel\": [\"subscribe\"]\n })\n\n token_details = self.ably.auth.request_token(\n token_params={'capability': capability})\n\n self.assertIsNotNone(token_details)\n self.assertIsNotNone(token_details.token)\n self.assertEqual(capability, token_details.capability,\n msg=\"Unexpected capability\")\n\n def test_request_token_with_specified_key(self):\n key = RestSetup.get_test_vars()[\"keys\"][1]\n token_details = self.ably.auth.request_token(\n key_name=key[\"key_name\"], key_secret=key[\"key_secret\"])\n self.assertIsNotNone(token_details.token, msg=\"Expected token\")\n self.assertEqual(key.get(\"capability\"),\n token_details.capability,\n msg=\"Unexpected capability\")\n\n @dont_vary_protocol\n def test_request_token_with_invalid_mac(self):\n self.assertRaises(AblyException, self.ably.auth.request_token,\n token_params={'mac': \"thisisnotavalidmac\"})\n\n def test_request_token_with_specified_ttl(self):\n token_details = self.ably.auth.request_token(token_params={'ttl': 100})\n self.assertIsNotNone(token_details.token, msg=\"Expected token\")\n self.assertEqual(token_details.issued + 100,\n token_details.expires, msg=\"Unexpected expires\")\n\n @dont_vary_protocol\n def test_token_with_excessive_ttl(self):\n excessive_ttl = 365 * 24 * 60 * 60 * 1000\n self.assertRaises(AblyException, self.ably.auth.request_token,\n token_params={'ttl': excessive_ttl})\n\n @dont_vary_protocol\n def test_token_generation_with_invalid_ttl(self):\n self.assertRaises(AblyException, self.ably.auth.request_token,\n token_params={'ttl': -1})\n\n def test_token_generation_with_local_time(self):\n timestamp = self.ably.auth._timestamp\n with patch('ably.rest.rest.AblyRest.time', wraps=self.ably.time) as server_time,\\\n patch('ably.rest.auth.Auth._timestamp', wraps=timestamp) as local_time:\n self.ably.auth.request_token()\n self.assertTrue(local_time.called)\n self.assertFalse(server_time.called)\n\n def test_token_generation_with_server_time(self):\n timestamp = self.ably.auth._timestamp\n with patch('ably.rest.rest.AblyRest.time', wraps=self.ably.time) as server_time,\\\n patch('ably.rest.auth.Auth._timestamp', wraps=timestamp) as local_time:\n self.ably.auth.request_token(query_time=True)\n self.assertFalse(local_time.called)\n self.assertTrue(server_time.called)\n\n\n@six.add_metaclass(VaryByProtocolTestsMetaclass)\nclass TestCreateTokenRequest(BaseTestCase):\n\n def setUp(self):\n self.ably = AblyRest(key=test_vars[\"keys\"][0][\"key_str\"],\n rest_host=test_vars[\"host\"],\n port=test_vars[\"port\"],\n tls_port=test_vars[\"tls_port\"],\n tls=test_vars[\"tls\"])\n self.key_name = self.ably.options.key_name\n self.key_secret = self.ably.options.key_secret\n\n def per_protocol_setup(self, use_binary_protocol):\n self.ably.options.use_binary_protocol = use_binary_protocol\n self.use_binary_protocol = use_binary_protocol\n\n @dont_vary_protocol\n def test_key_name_and_secret_are_required(self):\n ably = AblyRest(token='not a real token',\n rest_host=test_vars[\"host\"],\n port=test_vars[\"port\"],\n tls_port=test_vars[\"tls_port\"],\n tls=test_vars[\"tls\"])\n self.assertRaisesRegexp(AblyException, \"40101 401 No key specified\",\n ably.auth.create_token_request)\n self.assertRaisesRegexp(AblyException, \"40101 401 No key specified\",\n ably.auth.create_token_request,\n key_name=self.key_name)\n self.assertRaisesRegexp(AblyException, \"40101 401 No key specified\",\n ably.auth.create_token_request,\n key_secret=self.key_secret)\n\n @dont_vary_protocol\n def test_with_local_time(self):\n timestamp = self.ably.auth._timestamp\n with patch('ably.rest.rest.AblyRest.time', wraps=self.ably.time) as server_time,\\\n patch('ably.rest.auth.Auth._timestamp', wraps=timestamp) as local_time:\n self.ably.auth.create_token_request(\n key_name=self.key_name, key_secret=self.key_secret, query_time=False)\n self.assertTrue(local_time.called)\n self.assertFalse(server_time.called)\n\n @dont_vary_protocol\n def test_with_server_time(self):\n timestamp = self.ably.auth._timestamp\n with patch('ably.rest.rest.AblyRest.time', wraps=self.ably.time) as server_time,\\\n patch('ably.rest.auth.Auth._timestamp', wraps=timestamp) as local_time:\n self.ably.auth.create_token_request(\n key_name=self.key_name, key_secret=self.key_secret, query_time=True)\n self.assertTrue(server_time.called)\n self.assertFalse(local_time.called)\n\n def test_token_request_can_be_used_to_get_a_token(self):\n token_request = self.ably.auth.create_token_request(\n key_name=self.key_name, key_secret=self.key_secret)\n self.assertIsInstance(token_request, TokenRequest)\n\n def auth_callback(token_params):\n return token_request\n\n ably = AblyRest(auth_callback=auth_callback,\n rest_host=test_vars[\"host\"],\n port=test_vars[\"port\"],\n tls_port=test_vars[\"tls_port\"],\n tls=test_vars[\"tls\"],\n use_binary_protocol=self.use_binary_protocol)\n\n token = ably.auth.authorise()\n\n self.assertIsInstance(token, TokenDetails)\n\n @dont_vary_protocol\n def test_nonce_is_random_and_longer_than_15_characters(self):\n token_request = self.ably.auth.create_token_request(\n key_name=self.key_name, key_secret=self.key_secret)\n self.assertGreater(len(token_request.nonce), 15)\n\n another_token_request = self.ably.auth.create_token_request(\n key_name=self.key_name, key_secret=self.key_secret)\n self.assertGreater(len(another_token_request.nonce), 15)\n\n self.assertNotEqual(token_request.nonce, another_token_request.nonce)\n\n @dont_vary_protocol\n def test_ttl_is_optional_and_specified_in_ms(self):\n token_request = self.ably.auth.create_token_request(\n key_name=self.key_name, key_secret=self.key_secret)\n self.assertEquals(\n token_request.ttl, TokenDetails.DEFAULTS['ttl'])\n\n @dont_vary_protocol\n def test_accept_all_token_params(self):\n token_params = {\n 'ttl': 1000,\n 'capability': Capability({'channel': ['publish']}),\n 'client_id': 'a_id',\n 'timestamp': 1000,\n 'nonce': 'a_nonce',\n }\n token_request = self.ably.auth.create_token_request(\n token_params,\n key_name=self.key_name, key_secret=self.key_secret,\n )\n self.assertEqual(token_request.ttl, token_params['ttl'])\n self.assertEqual(token_request.capability, str(token_params['capability']))\n self.assertEqual(token_request.client_id, token_params['client_id'])\n self.assertEqual(token_request.timestamp, token_params['timestamp'])\n self.assertEqual(token_request.nonce, token_params['nonce'])\n\n def test_capability(self):\n capability = Capability({'channel': ['publish']})\n token_request = self.ably.auth.create_token_request(\n key_name=self.key_name, key_secret=self.key_secret,\n token_params={'capability': capability})\n self.assertEqual(token_request.capability, str(capability))\n\n def auth_callback(token_params):\n return token_request\n\n ably = AblyRest(auth_callback=auth_callback,\n rest_host=test_vars[\"host\"],\n port=test_vars[\"port\"],\n tls_port=test_vars[\"tls_port\"],\n tls=test_vars[\"tls\"],\n use_binary_protocol=self.use_binary_protocol)\n\n token = ably.auth.authorise()\n\n self.assertEqual(str(token.capability), str(capability))\n\n @dont_vary_protocol\n def test_hmac(self):\n ably = AblyRest(key_name='a_key_name', key_secret='a_secret')\n token_params = {\n 'ttl': 1000,\n 'nonce': 'abcde100',\n 'client_id': 'a_id',\n 'timestamp': 1000,\n }\n token_request = ably.auth.create_token_request(\n token_params, key_secret='a_secret', key_name='a_key_name')\n self.assertEqual(\n token_request.mac, 'sYkCH0Un+WgzI7/Nhy0BoQIKq9HmjKynCRs4E3qAbGQ=')\n","sub_path":"test/ably/resttoken_test.py","file_name":"resttoken_test.py","file_ext":"py","file_size_in_byte":13424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"297530717","text":"import numpy as np\nimport sys\nimport argparse\nimport os\nimport json\n\nimport re\nimport csv\nimport math\nif os.path.isdir('/u/cs401'):\n prefix = '/u/cs401/Wordlists/'\n data = '/u/cs401/A1/data/'\n featpfx = '/u/cs401/A1/feats/'\nelse:\n pwd = os.getcwd()\n prefix = pwd + '/../extras/Wordlists/'\n data = pwd+'/../data'\n featpfx = ''\n\nfirstperson = prefix + 'First-person'\nsecondperson = prefix + 'Second-person'\nthirdperson = prefix + 'Third-person'\nslang = prefix + 'Slang'\n\nwith open(firstperson) as f:\n firstpersonPat = re.sub('\\n', '', r' (('+ r')|('.join(f.readlines()) + r'))\\/')\n\nwith open(secondperson) as f:\n secondpersonPat = re.sub('\\n', '', r' (('+ r')|('.join(f.readlines()) + r'))\\/')\n \nwith open(thirdperson) as f:\n thirdpersonPat = re.sub('\\n', '', r' (('+ r')|('.join(f.readlines()) + r'))\\/')\n\nwith open(slang) as f:\n slangPat = re.sub('\\n', '', r' (('+ r')|('.join(f.readlines()) + r'))\\/')\n \n\nBNGL = {}\nwith open(prefix+'BristolNorms+GilhoolyLogie.csv', newline ='') as csvfile:\n reader = csv.DictReader(csvfile)\n for row in reader:\n if row['WORD']:\n BNGL[row['WORD']] = {\"AoA\": float(row['AoA (100-700)']), \"IMG\": float(row['IMG']), \"FAM\": float(row['FAM'])}\n\nWarr = {}\nwith open(prefix+'Ratings_Warriner_et_al.csv', newline ='') as csvfile:\n reader = csv.DictReader(csvfile)\n for row in reader:\n if row['Word']:\n Warr[row['Word']] = {\"V.Mean.Sum\":float(row['V.Mean.Sum']), \"A.Mean.Sum\": float(row['A.Mean.Sum']), \"D.Mean.Sum\": float(row['D.Mean.Sum'])}\n\nif featpfx:\n cats = ['Alt', 'Center', 'Left', 'Right']\n ID = {}\n featArr = {}\n for cat in cats:\n ID[cat] = {}\n featArr[cat] = np.load(featpfx+cat+'_feats.dat.npy')\n with open(featpfx+cat+'_IDs.txt') as f:\n for index, id in enumerate(f.readlines()):\n ID[cat][id.strip('\\n')] = index\n\ndef extract1( comment ):\n ''' This function extracts features from a single comment\n\n Parameters:\n comment : string, the body of a comment (after preprocessing)\n\n Returns:\n feats : numpy Array, a 173-length vector of floating point features (only the first 29 are expected to be filled, here)\n '''\n\n '''\n 1. Number of first-person pronouns \n 2. Number of second-person pronouns \n 3. Number of third-person pronouns \n 4. Number of coordinating conjunctions \n 5. Number of past-tense verbs \n 6. Number of future-tense verbs \n 7. Number of commas \n 8. Number of multi-character punctuation tokens \n 9. Number of common nouns \n 10. Number of proper nouns \n 11. Number of adverbs \n 12. Number of wh- words \n 13. Number of slang acronyms \n 14. Number of words in uppercase (≥ 3 letters long) \n 15. Average length of sentences, in tokens \n 16. Average length of tokens, excluding punctuation-only tokens, in characters \n 17. Number of sentences. \n 18. Average of AoA (100-700) from Bristol, Gilhooly, and Logie norms \n 19. Average of IMG from Bristol, Gilhooly, and Logie norms \n 20. Average of FAM from Bristol, Gilhooly, and Logie norms \n 21. Standard deviation of AoA (100-700) from Bristol, Gilhooly, and Logie norms \n 22. Standard deviation of IMG from Bristol, Gilhooly, and Logie norms \n 23. Standard deviation of FAM from Bristol, Gilhooly, and Logie norms \n 24. Average of V.Mean.Sum from Warringer norms \n 25. Average of A.Mean.Sum from Warringer norms \n 26. Average of D.Mean.Sum from Warringer norms \n 27. Standard deviation of V.Mean.Sum from Warringer norms \n 28. Standard deviation of A.Mean.Sum from Warringer norms \n 29. Standard deviation of D.Mean.Sum from Warringer norms \n '''\n feats = np.zeros(29)\n\n feats[0] += len(re.findall(firstpersonPat, comment)) #Number of first person pronouns\n feats[1] += len(re.findall(secondpersonPat, comment)) #Number of second person pronouns\n feats[2] += len(re.findall(secondpersonPat, comment)) #Number of second person pronouns\n feats[3] += len(re.findall(r'\\/CC ', comment)) #Number of Coordinating Conjunctions\n feats[4] += len(re.findall(r'\\/VBD ', comment)) #Number of Past tense verbs\n feats[5] += len(re.findall(r'((\\'ll)|(will)|(gonna)|(going\\/\\w+ to))\\/', comment)) #Number of Future-tense verbs\n feats[6] += len(re.findall(r'\\/, ', comment)) #number of commas\n feats[7] += len(re.findall(r'[?!.]{2,}', comment)) #number of multi-character punctuation\n feats[8] += len(re.findall(r'\\/((NN)|(NNS)) ', comment)) #number of common nouns\n feats[9] += len(re.findall(r'\\/((NNP)|(NNPS)) ', comment)) #number of proper nouns\n feats[10] += len(re.findall(r'\\/((RB)|(RBR)|(RBS)) ', comment)) #number of adverbs\n feats[11] += len(re.findall(r'\\/((WDT)|(WP)|(WP$)|(WRB)) ', comment)) #number of wh- words\n feats[12] += len(re.findall(slangPat, comment)) #find slang acronyms\n feats[13] += len(re.findall(r' ([A-Z]{3,})\\/', comment)) #find all capped words >= 3 letters long\n \n if len(re.findall(r'/.', comment)):\n feats[14] += (len(re.findall(r' ', comment)) + 1)/float(len(re.findall(r'/.', comment))) # avg number of tokens per sentence\n if len(re.findall(r'\\b[0-z]+\\/', comment)):\n feats[15] += (len(''.join(re.findall(r'\\b[0-z]+\\/', comment))) - 1)/float(len(re.findall(r'\\b[0-z]+\\/', comment))) #avg len of tokens\n else:\n feats[15] = 0\n \n feats[16] += len(re.findall(r'/.', comment)) #Number of sentences\n\n words = [word.strip('/') for word in re.findall(r'\\w+\\/', comment)]\n \n if len(words):\n feats[17] = sum([BNGL[word]['AoA'] for word in words if word in BNGL.keys()])/float(len(words))\n feats[18] = sum([BNGL[word]['IMG'] for word in words if word in BNGL.keys()])/float(len(words))\n feats[19] = sum([BNGL[word]['FAM'] for word in words if word in BNGL.keys()])/float(len(words))\n \n feats[23] = sum([Warr[word]['V.Mean.Sum'] for word in words if word in Warr.keys()])/float(len(words))\n feats[24] = sum([Warr[word]['A.Mean.Sum'] for word in words if word in Warr.keys()])/float(len(words))\n feats[25] = sum([Warr[word]['D.Mean.Sum'] for word in words if word in Warr.keys()])/float(len(words))\n else:\n feats[17:20] = [0]*3\n feats[23:26] = [0]*3\n if len(words)>1:\n feats[20] = math.sqrt(sum([(BNGL[word]['AoA'] - feats[17])**2 for word in words if word in BNGL.keys()])/float(len(words)-1))\n feats[21] = math.sqrt(sum([(BNGL[word]['IMG'] - feats[18])**2 for word in words if word in BNGL.keys()])/float(len(words)-1))\n feats[22] = math.sqrt(sum([(BNGL[word]['FAM'] - feats[19])**2 for word in words if word in BNGL.keys()])/float(len(words)-1))\n\n feats[26] = math.sqrt(sum([(Warr[word]['V.Mean.Sum'] - feats[17])**2 for word in words if word in Warr.keys()])/float(len(words)-1))\n feats[27] = math.sqrt(sum([(Warr[word]['A.Mean.Sum'] - feats[18])**2 for word in words if word in Warr.keys()])/float(len(words)-1))\n feats[28] = math.sqrt(sum([(Warr[word]['D.Mean.Sum'] - feats[19])**2 for word in words if word in Warr.keys()])/float(len(words)-1)) \n \n else:\n feats[20:23] = [0]*3\n feats[26:29] = [0]*3\n # TODO: your code here\n return feats\ndef main( args ):\n\n data = json.load(open(args.input))\n feats = np.zeros((len(data), 173+1))\n\n # TODO: your code here\n for i in range(len(data)):\n feats[i][:29] = extract1(data[i][\"body\"]) #load extracted feats\n id = data[i]['id']\n feats[i][29:-1] = featArr[data[i]['cat']][ID[data[i]['cat']][id]] #load Receptiviti feats\n if (data[i][\"cat\"] == \"Alt\"):\n feats[i][-1] = 3\n elif (data[i][\"cat\"] == \"Center\"):\n feats[i][-1] = 1\n elif (data[i][\"cat\"] == \"Left\"):\n feats[i][-1] = 0\n elif (data[i][\"cat\"] == \"Right\"):\n feats[i][-1] = 2\n \n\n np.savez_compressed( args.output, feats)\n\n \nif __name__ == \"__main__\": \n\n parser = argparse.ArgumentParser(description='Process each .')\n parser.add_argument(\"-o\", \"--output\", help=\"Directs the output to a filename of your choice\", required=True)\n parser.add_argument(\"-i\", \"--input\", help=\"The input JSON file, preprocessed as in Task 1\", required=True)\n args = parser.parse_args()\n \n\n main(args)\n\n","sub_path":"code/a1_extractFeatures.py","file_name":"a1_extractFeatures.py","file_ext":"py","file_size_in_byte":8340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"329233644","text":"class Solution(object):\n def rob(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n if(len(nums)==0):\n return 0\n if(len(nums)==1):\n return nums[0]\n if(len(nums)==2):\n return max(nums[0],nums[1])\n #rob the first one\n sum1=[]\n sum1.extend([nums[0],nums[0]])\n i=2\n while i JsonResponse:\n \"\"\"Guarda un mensaje enviado desde un visitante.\"\"\"\n name = request.POST.get(\"name\") or \"\"\n email = request.POST.get(\"email\") or \"\" # requerido o phone.\n phone = request.POST.get(\"phone\") or \"\" # requerido o email.\n address = request.POST.get(\"address\") or \"\"\n service_type = request.POST.get(\"service_type\") or \"\"\n warranty = request.POST.get(\"warranty\") or \"\"\n message = request.POST.get(\"message\") or \"\"\n\n # Prevenimos que el usuario envie multiples mensajes en un mismo día.\n request.session[\"message_send\"] = (request.session.get(\"message_send\") or \n {\"date\": None, \"email\": email, \"phone\": phone, \"name\": name})\n\n if request.session[\"message_send\"][\"date\"] == str(datetime.date.today()):\n if ((request.session[\"message_send\"][\"email\"] == email) or \n (request.session[\"message_send\"][\"phone\"] == phone)):\n return JsonResponse({\"error\": False, \"message\": _(\"Hemos recibido \"\n \"su mensaje. Estaremos en contacto con usted lo más pronto posible.\")})\n \n if (not email) and (not phone):\n return JsonResponse({\"error\": True, \"message\": _(\"Debe indicar su \"\n \"correo electrónico o número de teléfono donde podamos contactarlo.\")})\n\n if request.method == \"POST\":\n form = MessageForm(request.POST)\n if form.is_valid():\n instance = form.save()\n request.session[\"message_send\"] = {\n \"date\": str(datetime.date.today()),\n \"email\": instance.email,\n \"phone\": instance.phone,\n \"name\": instance.name,\n }\n return JsonResponse({\"error\": False, \"message\": _(\"¡Su mensaje ha \"\n \"sido recibido! Estaremos en contacto con usted lo más pronto posible.\")})\n return JsonResponse({\"error\": True, \n \"message\": _(\"Verifique los errores.\"), \"errors\": form.errors.as_json()})","sub_path":"base/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"95195712","text":"import parser\nimport os\nimport html_fillers as filler\n\nitems_in_row = 2 # max number of items in a row\n\ncollection_content = parser.parse_collection()\ncategory_order = [\n \"basic\", \"topomods\", \"path\", \"groups\", \"hacks\"\n]\n\ndir_path = os.path.dirname(os.path.realpath(__file__))\nf = open(dir_path + \"/examples.html\", \"w\")\n\n# generate header\nfiller.insert_header(f)\n\nitem_id = 1\n\nfor category_name in category_order:\n print(category_name)\n cat = collection_content[category_name]\n\n # add opening tags for a category\n filler.insert_section_start(f, cat[\"meta\"][\"label\"])\n\n filler.insert_row_start(f)\n\n row_count = 1\n item_details_list = []\n # add items\n for item in cat[\"items\"]:\n\n filler.insert_item_content(f=f, item_id=item_id, item=item)\n item_details_list.append({\n \"item_id\": item_id,\n \"data\": item\n })\n\n if row_count % items_in_row == 0:\n filler.insert_row_end(f)\n filler.insert_details_boxes(f=f, items=item_details_list)\n filler.insert_row_start(f)\n # reset stuff\n row_count = 0\n item_details_list.clear()\n\n item_id += 1\n row_count += 1\n\n # add trailing tags\n filler.insert_row_end(f)\n\n if len(item_details_list) > 0:\n filler.insert_details_boxes(f=f, items=item_details_list)\n\n filler.insert_section_end(f)\n\n# for category in collection_content:\n# if category not in category_order:\n# pass\n\n# add footer\nfiller.insert_footer(f)\n\nprint(\"finished\")\n\n\n","sub_path":"example-page-generator/html_generator.py","file_name":"html_generator.py","file_ext":"py","file_size_in_byte":1547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"184700683","text":"# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution(object):\n def addTwoNumbers(self, l1, l2):\n \"\"\"\n :type l1: ListNode\n :type l2: ListNode\n :rtype: ListNode\n \"\"\"\n n1 = 0\n while l1 != None:\n n1 = n1 * 10 + l1.val\n l1 = l1.next\n n2 = 0\n while l2 != None:\n n2 = n2 * 10 + l2.val\n l2 = l2.next\n n3 = n1 + n2\n tail = None\n head = ListNode(n3%10)\n while n3 != 0:\n head = ListNode(n3%10)\n head.next = tail\n tail = head\n n3 /= 10\n return head\n ","sub_path":"add-two-numbers-ii.py","file_name":"add-two-numbers-ii.py","file_ext":"py","file_size_in_byte":743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"121587058","text":"from WindPy import w\nimport pandas as pd\nimport os\nimport QuantLib as ql\nimport numpy as np\n\ndef save_optionsinfo(evalDate):\n # 50ETF currently trading contracts\n optioncontractbasicinfo = w.wset(\"optioncontractbasicinfo\",\n \"exchange=sse;windcode=510050.SH;status=all;field=wind_\"\n \"code,call_or_put,exercise_price,exercise_date\")\n df_option = pd.DataFrame(data=optioncontractbasicinfo.Data, index=optioncontractbasicinfo.Fields)\n df_option.to_json(os.path.abspath('..') + '\\marketdata\\optioncontractbasicinfo' + '.json')\n return optioncontractbasicinfo.ErrorCode\n\ndef save_optionsinfo_m(evalDate):\n # 豆粕\n optioncontractbasicinfo = w.wset(\"optionfuturescontractbasicinfo\",\n \"exchange=DCE;productcode=M;contract=all;\"\n \"field=wind_code,call_or_put,expire_date\")\n df_option = pd.DataFrame(data=optioncontractbasicinfo.Data, index=optioncontractbasicinfo.Fields)\n df_option.to_json(os.path.abspath('..') + '\\marketdata\\optioncontractbasicinfo_m' + '.json')\n return optioncontractbasicinfo.ErrorCode\n\n\ndef save_optionmkt(evalDate):\n # 50ETF market price data\n datestr = str(evalDate.year()) + \"-\" + str(evalDate.month()) + \"-\" + str(evalDate.dayOfMonth())\n query = \"startdate=\"+datestr+\";enddate=\"+datestr+\\\n \";exchange=sse;windcode=510050.SH;field=date,option_code,\" \\\n \"option_name,amount,pre_settle,open,highest,lowest,close,settlement_price\"\n optionmkt = w.wset(\"optiondailyquotationstastics\",query)\n df = pd.DataFrame(data=optionmkt.Data,index=optionmkt.Fields)\n df.to_json(os.path.abspath('..') + '\\marketdata\\optionmkt_' + datestr + '.json')\n return optionmkt.ErrorCode\n\ndef save_optionmkt_m(evalDate):\n # 50ETF market price data\n datestr = str(evalDate.year()) + \"-\" + str(evalDate.month()) + \"-\" + str(evalDate.dayOfMonth())\n query = \"startdate=\"+datestr+\";enddate=\"+datestr+\\\n \";exchange=sse;windcode=510050.SH;field=date,option_code,\" \\\n \"option_name,amount,pre_settle,open,highest,lowest,close,settlement_price\"\n optionmkt = w.wset(\"optiondailyquotationstastics\",query)\n df = pd.DataFrame(data=optionmkt.Data,index=optionmkt.Fields)\n df.to_json(os.path.abspath('..') + '\\marketdata\\optionmkt_' + datestr + '.json')\n return optionmkt.ErrorCode\n\ndef save_curve_treasury_bond(evalDate,daycounter):\n datestr = str(evalDate.year()) + \"-\" + str(evalDate.month()) + \"-\" + str(evalDate.dayOfMonth())\n curvedata = w.wsd(\"DR001.IB,CGB1M.WI,CGB3M.WI,CGB6M.WI,CGB9M.WI,CGB1Y.WI\",\n \"ytm_b\", datestr, datestr, \"returnType=1\")\n df = pd.DataFrame(data = curvedata.Data,index=curvedata.Fields)\n df.to_json(os.path.abspath('..') + '\\marketdata\\curvedata_tb_' + datestr + '.json')\n return curvedata.ErrorCode\n\n\ndef save_underlying_ts(evalDate,endDate):\n evalDate_str = str(evalDate.year()) + \"-\" + str(evalDate.month()) + \"-\" + str(evalDate.dayOfMonth())\n endDate_str = str(endDate.year()) + \"-\" + str(endDate.month()) + \"-\" + str(endDate.dayOfMonth())\n underlyingdata = w.wsd(\"510050.SH\", \"close\", evalDate_str, endDate_str, \"Fill=Previous;PriceAdj=F\")\n df = pd.DataFrame(data=underlyingdata.Data[0], index=underlyingdata.Times)\n df.to_json(os.path.abspath('..') + '\\marketdata\\spotclose' + '.json')\n return underlyingdata.ErrorCode\n\ndef save_ts_data(evalDate,endDate,daycounter,calendar):\n while(evalDate < endDate):\n evalDate = calendar.advance(evalDate, ql.Period(1, ql.Days))\n datestr = str(evalDate.year()) + \"-\" + str(evalDate.month()) + \"-\" + str(evalDate.dayOfMonth())\n try:\n optioncontractbasicinfo = pd.read_json(os.path.abspath('..') + '\\marketdata\\optioncontractbasicinfo' + '.json')\n except:\n save_optionsinfo(evalDate)\n try:\n optionmkt = pd.read_json(os.path.abspath('..')+ '\\marketdata\\optionmkt_' + datestr + '.json')\n except:\n save_optionmkt(evalDate)\n try:\n curvedata = pd.read_json(os.path.abspath('..') + '\\marketdata\\curvedata_tb_' + datestr + '.json')\n except:\n save_curve_treasury_bond(evalDate,daycounter)\n\n'''\nw.start()\n#save_underlying_ts(ql.Date(1,1,2015),ql.Date(20,7,2017))\n#spot = pd.read_pickle(os.getcwd()+'\\marketdata\\spotclose' +'.pkl')\n#print(spot)\nbegDate = ql.Date(1, 1, 2015)\n#begDate = ql.Date(10, 7, 2017)\nendDate = ql.Date(20, 7, 2017)\ncalendar = ql.China()\ndaycounter = ql.ActualActual()\nevalDate = begDate\n\nwhile evalDate <= endDate:\n evalDate = calendar.advance(evalDate, ql.Period(1, ql.Days))\n print(evalDate)\n datestr = str(evalDate.year()) + \"-\" + str(evalDate.month()) + \"-\" + str(evalDate.dayOfMonth())\n #print(os.getcwd())\n\n try:\n optionmkt = pd.read_json(os.getcwd() + '\\marketdata\\optionmkt_' + datestr + '.json')\n except :\n save_optionmkt(evalDate)\n optionmkt = pd.read_json(os.getcwd() + '\\marketdata\\optionmkt_' + datestr + '.json')\n\n #print(optionmkt.index)\n #print(optionmkt.values)\n\n\n try:\n optioncontractbasicinfo = pd.read_json(os.getcwd() +'\\marketdata\\optioncontractbasicinfo' + '.json')\n except:\n save_optionsinfo(evalDate)\n optioncontractbasicinfo = pd.read_json(os.getcwd() +'\\marketdata\\optioncontractbasicinfo' + '.json')\n\n try:\n curvedata = pd.read_json(os.getcwd() +'\\marketdata\\curvedata_tb_' + datestr + '.json')\n except :\n save_curve_treasury_bond(evalDate,daycounter)\n curvedata = pd.read_json(os.getcwd() +'\\marketdata\\curvedata_tb_' + datestr + '.json')\n #rates = curvedata.values[0]\n #print(rates)\n #krates = np.divide(rates, 100)\n #print(krates)\n'''","sub_path":"Utilities/svi_save_wind_data.py","file_name":"svi_save_wind_data.py","file_ext":"py","file_size_in_byte":5862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"224329106","text":"#!/usr/bin/env python\nimport SimpleITK as sitk\nimport sys\n\ndef RigidProp(fixedImage, movingImage, transformFile, binFlag, interp, outputName):\n\n rigidTransformix = sitk.TransformixImageFilter()\n rigidTransformParameterMap = sitk.ReadParameterFile(transformFile)\n if binFlag==1:\n rigidTransformParameterMap['DefaultPixelValue'] = ['0']\n rigidTransformParameterMap[\"FinalBSplineInterpolationOrder\"]= [interp]\n rigidTransformix.SetTransformParameterMap(rigidTransformParameterMap)\n\n rigidTransformix.SetMovingImage(sitk.Cast(movingImage, sitk.sitkFloat32))\n rigidTransformix.SetLogToFile(False)\n rigidTransformix.Execute()\n\n outputImage = rigidTransformix.GetResultImage()\n outputImage.CopyInformation(fixedImage)\n if binFlag==1:\n sitk.WriteImage(sitk.Cast(outputImage,sitk.sitkUInt8), outputName)\n else:\n sitk.WriteImage(sitk.Cast(outputImage,movingImage.GetPixelID()), outputName)\n\n return 1\n\n\nif __name__==\"__main__\":\n if len(sys.argv)!=7:\n print(\"Propagation of a rigid transformation using Elastix.\")\n print(\"Arguments:\")\n print(\" 1: Fixed image\")\n print(\" 2: Moving image\")\n print(\" 3: Transform file\")\n print(\" 4: Binary flag (1 or 0)\")\n print(\" 5: Interpolation order (0=NN, 1=Linear, etc.)\")\n print(\" 6: Output image\")\n sys.exit()\n else:\n fixed = sitk.ReadImage(sys.argv[1])\n moving = sitk.ReadImage(sys.argv[2])\n tfm = sys.argv[3]\n binFlag = int(sys.argv[4])\n interp = sys.argv[5]\n out = sys.argv[6]\n RigidProp(fixed, moving, tfm, binFlag, interp, out)\n","sub_path":"CLI/PropagateRigidTransform.py","file_name":"PropagateRigidTransform.py","file_ext":"py","file_size_in_byte":1650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"110217854","text":"import numpy as np\nimport pickle\n\ndef unpickle(file):\n with open(file, 'rb') as fo:\n dict = pickle.load(fo, encoding='bytes')\n\n return dict\n\ndef fold(a):\n red = a[0:1024].reshape(32, 32)\n green = a[1024:2048].reshape(32, 32)\n blue = a[2048:3072].reshape(32, 32)\n\n return np.stack((red, green, blue), axis=2)\n\nif __name__ == \"__main__\":\n data1 = unpickle(\"../../data/cifar/cifar-10-batches-py/data_batch_1\")\n pic1 = fold(data1[b'data'][1])\n import matplotlib.pyplot as plt\n plt.imshow(pic1)\n plt.show()\n","sub_path":"cifar/readData.py","file_name":"readData.py","file_ext":"py","file_size_in_byte":542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"499063338","text":"# -*- coding: utf-8 -*-\nimport sys\n\nfrom PySide import QtCore, QtGui\n\nfrom from10 import Ui_Form\n\n\nclass MainForm(QtGui.QWidget):\n def __init__(self, parent=None):\n QtGui.QWidget.__init__(self, parent)\n self.ui = Ui_Form()\n self.setupUi()\n\n def setupUi(self):\n self.ui.setupUi(self)\n\n\nclass ChibForm(MainForm):\n\n def setupUi(self):\n super(ChibForm, self).setupUi()\n button = QtGui.QPushButton(u'Поиск по адресу')\n self.ui.l_barcode.setText(u'Организация')\n self.ui.horizontalLayout_3.addWidget(button)\n\n\nif __name__ == \"__main__\":\n\n app = QtGui.QApplication(sys.argv)\n app.setStyle(QtGui.QStyleFactory.create('plastique'))\n main_form = ChibForm()\n main_form.show()\n sys.exit(app.exec_())\n\n","sub_path":"t8.py","file_name":"t8.py","file_ext":"py","file_size_in_byte":793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"33868640","text":"#!/usr/bin/env python\n\n# call as: python test_ensemble2bt.py \n# include plot code: plot_cov2ensemble.py\n \n# =======================================\n# Version 0.1\n# 24 July, 2019\n# https://patternizer.github.io/\n# michael.taylor AT reading DOT ac DOT uk\n# =======================================\n\nfrom optparse import OptionParser\nimport numpy as np\nimport scipy.linalg as la\nfrom scipy.special import erfinv\nimport sklearn\nfrom sklearn.decomposition import PCA\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.datasets import make_classification\nfrom netCDF4 import Dataset\nimport xarray\nimport seaborn as sns; sns.set(style='darkgrid')\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits import mplot3d\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom mpl_toolkits.mplot3d import proj3d\n\n#------------------------------------------------------------------------------\nimport ensemble_func as ensemble_func # functions for ensemble generation\nimport convert_func as convert # functions for L<-->BT conversion & HAR + CCI Meas Eqn\n#------------------------------------------------------------------------------\n\nif __name__ == \"__main__\":\n\n #------------------------------------------------------------------------------\n # parser = OptionParser(\"usage: %prog ch har_file ens_file mmd_file\")\n # (options, args) = parser.parse_args()\n #------------------------------------------------------------------------------\n # ch = args[0]\n # har_file = args[1]\n # ens_file = args[2]\n # mmd_file = args[3]\n #------------------------------------------------------------------------------\n\n #------------------------------------------------------------------------------\n # RUN PARAMETERS\n #------------------------------------------------------------------------------\n ch = 37\n # /gws/nopw/j04/fiduceo/Users/jmittaz/FCDR/Mike/FCDR_AVHRR/GBCS/dat_cci/\n har_file = 'FIDUCEO_Harmonisation_Data_' + str(ch) + '.nc' \n mmd_file = 'mta_mmd.nc'\n idx = 7 # MTA (see avhrr_sat)\n mns = False\n cci = True\n FLAG_new = True # NEW harmonisation structure (run >= '3.0-4d111a1')\n FLAG_plot = True\n# software_tag = '3e8c463' # job dir=job_avhxx_v6_EIV_10x_11 (old runs)\n# software_tag = '4d111a1' # job_dir=job_avhxx_v6_EIV_10x_11 (new runs)\n software_tag = 'v0.3Bet' # job_dir=job_avhxx_v6_EIV_10x_11 (new runs)\n #--------------------------------------------------------------------------\n\n if mns:\n plotstem = '_'+str(ch)+'_'+'MNS'+'_'+software_tag+'.png'\n ens_file = 'MC_Harmonisation_MNS.nc'\n else:\n plotstem = '_'+str(ch)+'_'+'CRS'+'_'+software_tag+'.png'\n ens_file = 'MC_Harmonisation_CRS.nc'\n\n mmd = xarray.open_dataset(mmd_file, decode_times=False) \n if ch == 37:\n channel = 3\n BT_mmd = mmd['avhrr-ma_ch3b'][:,3,3] # (55604, 7, 7)\n elif ch == 11:\n channel = 4\n BT_mmd = mmd['avhrr-ma_ch4'][:,3,3]\n else:\n channel = 5\n BT_mmd = mmd['avhrr-ma_ch5'][:,3,3]\n\n avhrr_sat = [b'N12',b'N14',b'N15',b'N16',b'N17',b'N18',b'N19',b'MTA',b'MTB'] # LUT ordering\n if FLAG_new:\n # RQ: NEW2 AATSR, ATSR2, MTA, N19, N18, N17, N16, N15, N14, N12, N11\n # index 0 1 2 3 4 5 6 7 8 9 10\n # --> new index map for LUT (N12 --> MTA)\n idx_ = 7 - idx + 2\n # RQ: NEW1 AATSR, MTA, N19, N18, N17, N16, N15, N14, N12, N11\n # index 0 1 2 3 4 5 6 7 8 9\n # --> new index map for LUT (N12 --> MTA)\n # idx_ = 7 - idx + 1\n else:\n # RQ: OLD MTA, N19, N18, N17, N16, N15, N14, N12, N11\n # index 0 1 2 3 4 5 6 7 8\n # --> new index map for LUT (N12 --> MTA)\n idx_ = 7 - idx\n\n lut = convert.read_in_LUT(avhrr_sat[idx])\n\n #------------------------------------------------\n\n har = xarray.open_dataset(har_file, decode_cf=True)\n\n # Load ensemble\n\n ncout = Dataset(ens_file,'r')\n if ch == 37:\n da = ncout.variables['delta_params3'][:]\n elif ch == 11:\n da = ncout.variables['delta_params4'][:]\n else:\n da = ncout.variables['delta_params5'][:]\n ncout.close()\n\n # Calculate ensemble BT and best-case BT\n\n BT_ens = ensemble_func.ensemble2BT(da, har, mmd, lut, channel, idx_, cci)\n BT_har = ensemble_func.ensemble2BT(da*0., har, mmd, lut, channel, idx_, cci)[:,0]\n\n # =======================================\n # INCLUDE PLOT CODE:\n exec(open('plot_cov2ensemble.py').read())\n # =======================================\n\n if FLAG_plot:\n\n plot_ensemble_diff_BT_scatterplot(BT_ens,BT_mmd)\n plot_ensemble_diff_BT_timeseries(BT_ens,BT_mmd)\n # plot_ensemble_diff_L_timeseries(L_ens,L)\n\n #------------------------------------------------ \n print('** end')\n\n\n\n\n\n\n\n","sub_path":"test_ensemble2bt.py","file_name":"test_ensemble2bt.py","file_ext":"py","file_size_in_byte":4977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"55115004","text":"import urllib.request \nimport json \n\nclient_id = \"rOc74uqftZkAWrS9HBLS\"\nclient_secret = \"Q7Q17I1bOs\"\nserch_text = urllib.parse.quote(\"빅데이터\")\npage_start = 1\ndisplay = 5\n\nurl = \"https://openapi.naver.com/v1/search/news?query=%s&start=%s&display=%s\"%(serch_text, page_start, display)\n\nreqObj=urllib.request.Request(url)\nprint(reqObj)\n\nreqObj.add_header(\"X-Naver-Client-Id\", client_id)\nreqObj.add_header(\"X-Naver-Client-Secret\", client_secret)\n\nhtmlObj = urllib.request.urlopen(reqObj)\nprint(htmlObj)\n\nhtmlObj_body = htmlObj.read()\nhtmlObj_body= htmlObj_body.decode('utf-8')\n\n\nwith open('result.json', 'w+') as json_file:\n json.dump(htmlObj_body, json_file)\n","sub_path":"crawling.py","file_name":"crawling.py","file_ext":"py","file_size_in_byte":665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"223104095","text":"import cv2\nimport os\n\n\ndef resize_image():\n \"\"\"\n lteerbox_image()将图片按照纵横比进行缩放,将空白部分用(128,128,128)填充,调整图像尺寸\n 具体而言,此时某个边正好可以等于目标长度,另一边小于等于目标长度\n 将缩放后的数据拷贝到画布中心,返回完成缩放\n \"\"\"\n image_path='/home/dl/Downloads/indoorCVPR_09/roiresize/'\n target_path='/home/dl/Downloads/indoorCVPR_09/roiresize1/'\n img_list=sorted(os.listdir(image_path))\n i=0\n for file in img_list:\n i=i+1\n img = cv2.imread(image_path+file)\n #print(img)\n img_w, img_h = img.shape[1], img.shape[0]\n w, h = (300,300)#inp_dim是需要resize的尺寸(如416*416)\n # 取min(w/img_w, h/img_h)这个比例来缩放,缩放后的尺寸为new_w, new_h,即保证较长的边缩放后正好等于目标长度(需要的尺寸),另一边的尺寸缩放后还没有填充满.\n new_w = int(img_w * min(w/img_w, h/img_h))\n new_h = int(img_h * min(w/img_w, h/img_h))\n image = cv2.resize(img, (new_w,new_h), interpolation = cv2.INTER_LINEAR)\n cv2.imwrite(target_path+file,image)\n \n #将图片按照纵横比不变来缩放为new_w x new_h,768 x 576的图片缩放成416x312.,用了双三次插值\n\nif __name__=='__main__':\n resize_image()\n\n\n","sub_path":"process_pic/hwresize.py","file_name":"hwresize.py","file_ext":"py","file_size_in_byte":1349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"119064114","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 ('promotion', '0008_auto_20150908_1121'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='newproduct',\n name='product',\n field=models.OneToOneField(related_name='newitem', verbose_name='推荐商品', to='catalogue.Product'),\n ),\n ]\n","sub_path":"apps/promotion/migrations/0009_auto_20150908_1123.py","file_name":"0009_auto_20150908_1123.py","file_ext":"py","file_size_in_byte":475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"50602944","text":"\r\n# Assigning values to the variables that will have a constant value\r\nbudget = 500\r\neconomy = 750\r\nvip = 2000\r\nbag_cost = 200\r\nmeal_cost = 150\r\n# Assigning values to the variables that will be changed later on,\r\n# depending on the input\r\nticket_cost = 0\r\nbag = 0\r\nmeal = 0\r\noption = 0\r\n\r\n# Printing out the ticket names and prices on the screen\r\nprint('Ticket types:')\r\nprint('1. Budget:', format(budget, '10'), 'kr')\r\nprint('2. Economy:', format(economy, '9'), 'kr')\r\nprint('3. VIP: ', format(vip, '12'), 'kr\\n')\r\n\r\n# Asking the user to choose the type of the ticket.\r\n# Depending on which number the user chooses the price\r\n# will be added to the ticket_cost.\r\nticket_type = int(input('Input ticket type here>>'))\r\nif ticket_type == 1:\r\n ticket_cost = budget\r\n\r\nelif ticket_type == 2:\r\n ticket_cost = economy\r\n\r\nelif ticket_type == 3:\r\n ticket_cost = vip\r\n\r\n# This loop will continue until the user chooses to finalize their ticket.\r\n# That means that if the user presses the wrong number or changes his/hers\r\n# mind they can just change it.\r\nwhile option != 5:\r\n print('\\nCurrently you have:\\n',\r\n bag, ' bag(s) registered\\n',\r\n meal, ' meal(s) registered\\n')\r\n\r\n print('Here are your options:\\n',\r\n '1. Add bag (max 1)\\n',\r\n '2. Add meal (max 1)\\n',\r\n '3. Remove bag\\n',\r\n '4. Remove meal\\n',\r\n '5. Finalize ticket\\n')\r\n\r\n # Asking the user to write the number of the option\r\n # which will be saved in a variable called option.\r\n option = int(input('Input option type here>>\\n'))\r\n if option == 1:\r\n bag = 1\r\n\r\n elif option == 2:\r\n meal = 1\r\n\r\n elif option == 3:\r\n bag = 0\r\n\r\n elif option == 4:\r\n meal = 0\r\n\r\n # Prints out the reciept for the costumer stating\r\n # all his/hers costs and the total\r\n elif option == 5:\r\n print('Receipt:')\r\n print('Ticket :', format(ticket_cost, '4')+'kr')\r\n if bag == 1:\r\n print('Bag :', format(bag*bag_cost, '4')+'kr')\r\n if meal == 1:\r\n print('Meal :', format(meal*meal_cost, '4')+'kr')\r\n print(' -------')\r\n print('Total :', format(ticket_cost +\r\n bag*bag_cost + meal*meal_cost, '4')+'kr')\r\n","sub_path":"lab1_1/Lab1_1a.py","file_name":"Lab1_1a.py","file_ext":"py","file_size_in_byte":2260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"291430636","text":"import boto3\nfrom botocore.config import Config\n\ndef connect(service: str = 'ec2', region: str = 'us-east-2', profile: str = 'default'):\n try:\n config = Config(region_name=region)\n session = boto3.Session(profile_name=profile)\n\n return session.client(service, config=config)\n except Exception as err:\n print('connect.error', err)\n raise err\n","sub_path":"jenkins/scripts/python/lib_connect_aws.py","file_name":"lib_connect_aws.py","file_ext":"py","file_size_in_byte":358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"412434430","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport sys\nimport seaborn as sns\n\n# ---THIS IS THE FILE OF STATIC FILE PATHS ; NEEDS TO BE EDITED ----\nfrom model_paths import base_path, data_path\nimport cartopy.io.shapereader as shpreader\nfrom cartopy.feature import ShapelyFeature\nimport cartopy.crs as ccrs\nfrom scipy import stats\n\nfrom seasonal_precip_error_df import seasonal_precip_error_df\nfrom inset_plot import make_an_inset_plot\nimport matplotlib.dates as mdates\n\n## Colorbrewer colors\nlgtblue = \"#a6cee3\"\ndarkblue = \"#1f78b4\"\nlgtgreen = \"#b2df8a\"\ndarkgreen = \"#33a02c\"\npink = \"#fb9a99\"\nred = \"#e31a1c\"\nlgtorange = \"#fdbf6f\"\norange = \"#ff7f00\"\n\n\ndef add_wy(index):\n wylist=[]\n for i in index:\n if i.month in [10,11, 12]:\n wy = int(i.year) + 1\n else:\n wy = int(i.year)\n wylist.append(wy)\n return wylist\n\ndef add_dowy(index):\n dowylist=[]\n # loop through the index\n for i in index:\n if i.dayofyear >= 274:\n dowy = i.dayofyear - 273\n else:\n dowy = i.dayofyear + (365-273)\n\n dowylist.append(dowy)\n return dowylist\n\ndatabase = data_path + \"/CO_snotel.db\"\ndbengine = \"sqlite:///{}\".format(database)\n\n\ndf = pd.read_sql_table('main', dbengine)\nlats = []\nlons = []\nnames = []\nfor i,row in df.iterrows():\n lats.append(row.lat)\n lons.append(row.lon)\n names.append(row.site_id)\n\ndef get_snotel(site_id):\n df = pd.read_sql_table(site_id, dbengine)\n df['IncPrecip'] = df['IncPrecip']*25.4\n df['time'] = df['Date']\n df = df.set_index('time')\n del df['Date']\n return df\n\n# read all of the snotels...\nall_snotel = pd.read_sql_table('main', dbengine)\nall_snotel = all_snotel.set_index(\"site_id\")\n\n# read wrf data\nwrf = pd.read_csv(\"wrf_snotel_dataframe.csv\")\nwrf = wrf.set_index(\"time\")\nwrf.index = pd.to_datetime(wrf.index)\ndel wrf['time.1']\n\n## get the heights of the snotels that we are looking at... the database hase em all\nsnotel_in_this_study = all_snotel.loc[wrf.columns].drop_duplicates()\nsnotel_height_sorted = snotel_in_this_study.sort_values(\"elev\")\n\n\nsndf = wrf.copy()\n\nfor i,col in enumerate(snotel_height_sorted.index[::-1]):\n sndf[col] = np.nan # zero out the rows...\n sn = get_snotel(col)\n sndf[col] = sn.IncPrecip\n\n\ndef corrplot(col):\n r2list = []\n interval = np.arange(1, 365, 1)\n for i in interval:\n snc = sndf[col].rolling(i).mean() # get the column..\n wrfc = wrf[col].rolling(i).mean() # same...\n mask= ~np.isnan(snc) & ~np.isnan(wrfc)\n reg = stats.linregress(snc[mask], wrfc[mask])\n r2list.append(reg.rvalue**2)\n return r2list, interval\n\n# r2list_main = []\n# for i in wrf.columns:\n# r2list, interval = corrplot(i)\n# r2list_main.append(r2list)\n\ndef make_ugly_dataframe(wrf_amount):\n # this is ajust a warpper so we can od this twice\n wrf_binary = wrf.copy()\n #wrf_binary[wrf_binary > 2.54] = 1.\n wrf_binary[wrf_binary > wrf_amount] = 1.\n\n snotel_binary = sndf.copy()\n snotel_binary[snotel_binary > 0] = 1.\n\n wet_dry = snotel_binary.copy() * 0\n wet_dry_matrix = np.zeros_like(wet_dry) * np.nan\n wet_dry_matrix[np.where((snotel_binary == 0) & (wrf_binary == 0))] = 0\n wet_dry_matrix[np.where((snotel_binary == 1) & (wrf_binary == 0))] = 1\n wet_dry_matrix[np.where((snotel_binary == 0) & (wrf_binary == 1))] = -1\n wet_dry_matrix[np.where((snotel_binary == 1) & (wrf_binary == 1))] = 2\n\n\n wet_dry_df = pd.DataFrame(wet_dry_matrix)\n wet_dry_df.columns = wrf_binary.columns\n wet_dry_df = wet_dry_df.set_index(wrf_binary.index)\n wet_dry_df['wy'] = add_wy(wet_dry_df.index)\n wet_dry_df['season'] = add_wy(wet_dry_df.index)\n cool_season = [10,11,12,1,2,3]\n warm_season = [4,5,6,7,8,9]\n\n\n ## add seasons to both dataframes...\n for i in wet_dry_df.index:\n if i.month in cool_season:\n wet_dry_df.at[i,\"cool_season\"] = 1\n else:\n wet_dry_df.at[i,\"cool_season\"] = 0\n\n\n cols = [\"0\", \"1\", \"-1\", \"2\"]\n wdf = pd.DataFrame(np.zeros((len(wrf.columns), 4)))\n wdf.set_index(wrf.columns)\n wdf.columns = cols\n\n\n cool = wet_dry_df[wet_dry_df[\"cool_season\"] == 1]\n warm = wet_dry_df[wet_dry_df[\"cool_season\"] == 0]\n\n\n\n def wd_stats(df, col):\n total = len(df[col][~df[col].isna()])\n both_wet = len(df[col][df[col] == 2])/total* 100\n both_dry = len(df[col][df[col] == 0])/total* 100\n wrf_wet_only = len(df[col][df[col] == -1])/total* 100\n snt_wet_only = len(df[col][df[col] == 1])/total* 100\n output= {\"both_wet\" : both_wet,\n \"both_dry\": both_dry,\n \"wrf_wet_only\": wrf_wet_only,\n \"snt_wet_only\": snt_wet_only}\n return output\n\n dblrange = np.arange(0, len(wrf.columns)*2, 2)\n main_df = pd.DataFrame(np.zeros((len(wrf.columns)*2, 1)))\n\n for c,i in enumerate(dblrange):\n col = wrf.columns[c]\n cool_out = wd_stats(cool, col)\n cool_out.update(dict(season=\"cool\", site=col))\n\n warm_out = wd_stats(warm, col)\n warm_out.update(dict(season=\"warm\", site=col))\n for c in warm_out.keys():\n main_df.at[i,c] = cool_out[c]\n main_df.at[i+1, c] = warm_out[c]\n\n\n main_df[\"wrf_wet_percent\"] = main_df[\"wrf_wet_only\"] + main_df[\"both_wet\"]\n main_df[\"snt_wet_percent\"] = main_df[\"snt_wet_only\"] + main_df[\"both_wet\"]\n\n\n cool = main_df[main_df[\"season\"] == \"cool\"]\n warm = main_df[main_df[\"season\"] == \"warm\"]\n return cool, warm\n### done!!\n\n\ncool0, warm0 = make_ugly_dataframe(0)\ncool, warm = make_ugly_dataframe(2.54)\n\n\nfig = plt.gcf()\nfig.set_size_inches(8,4.5)\n#[left, bottom, width, height]\nwidth = .12\nleft = .09\nbottom = .11\n\n# these two are barplots...\nax0 = plt.axes([left, bottom, width, .7])\nax1 = plt.axes([width + left, bottom, width, .7])\n\nax00 = plt.axes([width*2 + left + .05, bottom, width, .7])\nax11 = plt.axes([width*3 + left + .05, bottom, width, .7])\n\n\nax2 = plt.axes([width*4 + left + .15, bottom+.1, .185, .6])\n\n\n\n#ax2b = plt.axes([width*2 + .15, .65+bottom, .2, .15])\n\n\nxl = len(warm) # should be same as cold...\nx0 = np.arange(0, xl, 1)\n# this spans both\nmainwidth = .6\nax0.barh(x0, warm[\"both_wet\"], color=\"gray\", height=mainwidth)\nax0.barh(x0-mainwidth/4, warm[\"wrf_wet_only\"], left=warm[\"both_wet\"], height=mainwidth/2, color=lgtblue)\nax0.barh(x0+mainwidth/4, warm[\"snt_wet_only\"], left=warm[\"both_wet\"], height=mainwidth/2, color=lgtorange)\n\n\nax1.barh(x0, cool[\"both_wet\"], color=\"gray\", height=mainwidth, label='Both-Wet')\nax1.barh(x0-mainwidth/4, cool[\"wrf_wet_only\"], left=cool[\"both_wet\"], height=mainwidth/2, color=lgtblue, label=\"WRF-Only\")\nax1.barh(x0+mainwidth/4, cool[\"snt_wet_only\"], left=cool[\"both_wet\"], height=mainwidth/2, color=lgtorange, label=\"Snotel\")\nax1.legend(loc='upper right', bbox_to_anchor=(1.4, 1.), fontsize=12)\nax0.set_xlim(60.,0)\nax1.set_xlim(0,60.)\n\nax1.axvline(0, lw='2.5', color='black')\nax1.set_yticks([])\nax0.set_yticks(x0)\nax0.set_yticklabels(cool.site)\n\n# ax1.text(.8,.8, \"Cool\", transform=ax1.transAxes, weight='bold'))\n# ax0.text(..2,.8, \"Warm\", transform=ax0.transAxes, weight='bold'))\nax1.set_title(\"\\nCool\", fontsize=12)\nax0.set_title(\" \\\"Wet\\\" > 2.54mm \\n Warm\", fontsize=12)\n\n# get rid of some tikcs..\nax1.spines['left'].set_visible(False)\nax1.spines['right'].set_visible(False)\nax1.spines['top'].set_visible(False)\nax0.spines['top'].set_visible(False)\n\ncool_wrf_avg_wet = np.round(cool.wrf_wet_percent.mean(), 2)\nwarm_wrf_avg_wet = np.round(warm.wrf_wet_percent.mean(), 2)\n\ncool_snt_avg_wet = np.round(cool.snt_wet_percent.mean(), 2)\nwarm_snt_avg_wet = np.round(warm.snt_wet_percent.mean(), 2)\n\n# ax0.text(.05,.25, \"WRF Wet % \\n{}\\n Snotel Wet %\\n{}\".format(warm_wrf_avg_wet, warm_snt_avg_wet), transform=ax0.transAxes, fontsize=12, color='red')\n# ax1.text(.5,.25, \"WRF Wet % \\n{}\\n Snotel Wet %\\n{}\".format(cool_wrf_avg_wet, cool_snt_avg_wet), transform=ax1.transAxes, fontsize=12, color='red')\n\nax0.set_xticks([0, 25., 50.])\nax1.set_xticks([0, 25., 50.])\n\n\n###### DO THE SECOND ONE\nxl = len(warm) # should be same as cold...\nx0 = np.arange(0, xl, 1)\n# this spans both\nmainwidth = .6\nax00.barh(x0, warm0[\"both_wet\"], color=\"gray\", height=mainwidth)\nax00.barh(x0-mainwidth/4, warm0[\"wrf_wet_only\"], left=warm0[\"both_wet\"], height=mainwidth/2, color=lgtblue)\nax00.barh(x0+mainwidth/4, warm0[\"snt_wet_only\"], left=warm0[\"both_wet\"], height=mainwidth/2, color=lgtorange)\n\n\nax11.barh(x0, cool0[\"both_wet\"], color=\"gray\", height=mainwidth, label='Both-Wet')\nax11.barh(x0-mainwidth/4, cool0[\"wrf_wet_only\"], left=cool0[\"both_wet\"], height=mainwidth/2, color=lgtblue, label=\"WRF-Wet,\\nSnotel-Dry\")\nax11.barh(x0+mainwidth/4, cool0[\"snt_wet_only\"], left=cool0[\"both_wet\"], height=mainwidth/2, color=lgtorange, label=\"Snotel-Wet,\\nWRF-Dry\")\n#ax11.legend(loc='upper right', bbox_to_anchor=(1.4, 1.), fontsize=8)\nax00.set_xlim(60.,0)\nax11.set_xlim(0,60.)\n\nax11.axvline(0, lw='2.5', color='black')\nax11.set_yticks([])\nax11.set_yticklabels([])\nax00.set_yticks([])\nax00.set_yticklabels([])\n\nax00.set_xticks([0, 25., 50.])\nax11.set_xticks([0, 25., 50.])\n\n# ax1.text(.8,.8, \"Cool\", transform=ax1.transAxes, weight='bold'))\n# ax0.text(..2,.8, \"Warm\", transform=ax0.transAxes, weight='bold'))\nax11.set_title(\"\\nCool\", fontsize=12)\nax00.set_title(\" \\\"Wet\\\" > 0mm \\n Warm\", fontsize=12)\n\n# get rid of some tikcs..\nax11.spines['right'].set_visible(False)\nax11.spines['left'].set_visible(False)\nax11.spines['right'].set_visible(False)\nax11.spines['top'].set_visible(False)\nax00.spines['top'].set_visible(False)\nax00.spines['left'].set_visible(False)\n\n\n\ncool_wrf_avg_wet0 = np.round(cool0.wrf_wet_percent.mean(), 2)\nwarm_wrf_avg_wet0 = np.round(warm0.wrf_wet_percent.mean(), 2)\n\ncool_snt_avg_wet0 = np.round(cool0.snt_wet_percent.mean(), 2)\nwarm_snt_avg_wet0 = np.round(warm0.snt_wet_percent.mean(), 2)\n\n#ax00.text(.05,.25, \"WRF Wet % \\n{}\\n Snotel Wet %\\n{}\".format(warm_wrf_avg_wet0, warm_snt_avg_wet0), transform=ax00.transAxes, fontsize=12, color='red')\n#ax11.text(.5,.25, \"WRF Wet % \\n{}\\n Snotel Wet %\\n{}\".format(cool_wrf_avg_wet0, cool_snt_avg_wet0), transform=ax11.transAxes, fontsize=12, color='red')\nax00.set_xlabel(\" % Wet Days\")\nax0.set_xlabel(\" % Wet Days\")\n\nax0.set_ylabel(\"Snotel Station ID\")\nax0.text(0, 1.1, \"A.\", transform=ax0.transAxes, weight=\"bold\", fontsize=12)\n###########\n\n######### Make the thrid plot of means ...#####\n# place some text\n# ax3.bar([.4], [cool_snt_avg_wet], width=.2, color=lgtorange)\n# ax3.bar([.6], [cool_wrf_avg_wet], width=.2, color=lgtblue)\n\n# ax3.bar([1], [warm_snt_avg_wet], width=.2, color=lgtorange)\n# ax3.bar([1.2], [warm_wrf_avg_wet], width=.2, color=lgtblue)\n\n\n\n\n######### MAKE PRECIPITATION BY BINSIZE PLOTS ######\ndef precip_by_binsize(wc):\n wcsum = wc.sum()\n fraclist = []\n array = np.linspace(0, 60., 500)\n for i in array:\n frac = np.sum(wc[wc < i])/wcsum * 100\n fraclist.append(frac)\n return fraclist, array\n\n\n# do each columnn\nfraclist_array = np.zeros((500, len(wrf.columns)))\nfraclist_array_snt = np.zeros((500, len(wrf.columns)))\n\nfor i,c in enumerate(wrf.columns):\n wc = wrf[c]\n fraclist, array = precip_by_binsize(wc)\n fraclist_array[:, i] = fraclist\n\n# do the same thing for snotel...\nfor i,c in enumerate(wrf.columns):\n sc = sndf[c]\n fraclist, array = precip_by_binsize(sc)\n fraclist_array_snt[:, i] = fraclist\n\n\nfraclist_mean = fraclist_array.mean(axis=1)\nfraclist_mean_snt = fraclist_array_snt.mean(axis=1)\n\n# plot them all\nfor i in range(len(wrf.columns )):\n ax2.plot(fraclist_array[:,i], array, color='grey', alpha=.2)\n ax2.plot(fraclist_array_snt[:,i], array, color='grey', linestyle='--', alpha=.2)\n\n# plot the mean\nax2.plot(fraclist_mean, array, color=darkblue)\nax2.plot(fraclist_mean_snt, array, color=orange)\n\nax2.set_yticks(np.array([0., 2.54, 10., 20., 30., 40., 50., 60.]))\nax2.get_yticklabels()[1].set_color('red')\n\nax2.axhline(2.54, color=red, linestyle='--', zorder=0)\n\n# get location of percent that is closest to 2.54...\nwrf_point = np.interp(2.54, array, fraclist_mean)\nax2.scatter([wrf_point], [2.54], marker='x', zorder=4)\nax2.plot([wrf_point, wrf_point], [0, 2.54], color=darkblue, zorder=4, alpha=.5, linestyle='--')\n\n# plot lines showing wher ethe curve intecpets 2.54 ...\nsnt_point = fraclist_mean_snt[np.argmax(fraclist_mean_snt > 0)]\nax2.scatter([snt_point], [2.54], marker='x', color=orange, zorder=4)\nax2.plot([snt_point, snt_point], [0, 2.54], color=orange, zorder=4, alpha=.5, linestyle='--')\n\n\nax2.set_xticks(np.array([0., np.round(wrf_point,1), np.round(snt_point,1), 50., 100.]))\nax2.set_xticklabels(ax2.get_xticks(), rotation=45)\nax2.get_xticklabels()[1].set_color(darkblue)\nax2.get_xticklabels()[2].set_color(orange)\nax2.set_ylim(0,60)\nax2.set_ylabel(\"P. Rate [i] \\n (mm/day)\")\n\nax2.spines['right'].set_visible(False)\nax2.spines['top'].set_visible(False)\nax2.text(0, 1.1, \"B.\", transform=ax2.transAxes, weight=\"bold\", fontsize=12)\n\nxlabel = r'$\\sum (P < i ) / \\sum P * 100$' + \"\\n (%)\"\nax2.set_xlabel(xlabel)\n\n#plt.show()\nplt.savefig(\"WRF_Snotel_WetDryRate.png\", dpi=600)\n\n\n","sub_path":"wrf_correlations_binsize.py","file_name":"wrf_correlations_binsize.py","file_ext":"py","file_size_in_byte":13323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"307839137","text":"from django.db import models\nfrom multiselectfield import MultiSelectField\n\n# Create your models here.\n\nINCLUSIONS =(\n ('meals','Meals'),\n ('flight','Flight'),\n ('bus','Bus'),\n ('sightseeing','Sightseeing'),\n ('hotel','Hotel'),\n ('travel_insurance', 'Travel Insurance'),\n ('visa', 'Visa'),\n)\nEXCLUSIONS =(\n ('flight','Flight'),\n ('travel_insurance','Travel Insurance'),\n ('visa','Visa'),\n ('refunded','Refunded'),\n ('meals', 'Meals'),\n ('bus', 'Bus'),\n ('sightseeing', 'Sightseeing'),\n ('hotel', 'Hotel'),\n)\nTYPE=(\n ('couple','Couple'),\n ('person','Person')\n)\nCATEGORY=(\n ('family_holiday','Family Holiday'),\n ('road_trip','Road Trip'),\n ('natural_escape','Natural Escape'),\n\n)\n\n\nclass Provider(models.Model):\n name = models.CharField(max_length=30, null=True, blank=True)\n email = models.EmailField(null=True, blank=True)\n address=models.CharField(max_length=40, null=True, blank=True)\n\n def __str__(self):\n return self.name\n\nclass Tour(models.Model):\n name = models.CharField(max_length=30, null=True, blank=True)\n provider=models.ForeignKey(Provider,on_delete=models.CASCADE)\n inclusions=MultiSelectField(choices=INCLUSIONS, default='meals')\n exclusions =MultiSelectField(choices=EXCLUSIONS, default='flight', max_length=30)\n price=models.DecimalField(default=0.00, max_digits=30, decimal_places=2)\n discount=models.DecimalField(default=0.00, max_digits=30, decimal_places=2)\n number_of_days=models.BigIntegerField(default=1,)\n details=models.TextField(null=True, blank=True)\n conditions=models.TextField(null=True,blank=True)\n policy=models.TextField(null=True,blank=True)\n type=models.CharField(choices=TYPE,default='person',max_length=20)\n review=models.DecimalField(default=0.00, max_digits=30, decimal_places=2)\n destination=models.CharField(max_length=30, null=True, blank=True)\n catergory=MultiSelectField(choices=CATEGORY,default='family_holiday')\n image = models.ImageField(null=True, blank=True, upload_to='static_cdn/media_root')\n\n def __str__(self):\n return self.name","sub_path":"demo/demo/tours/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"308473647","text":"#!/usr/bin/env python\n#\n# Copyright 2019 MIT Probabilistic Computing Project.\n# Released under Apache 2.0; refer to LICENSE.txt\n\nimport os\nimport shutil\nimport subprocess\n\nfrom fractions import Fraction\n\nimport matplotlib;\nmatplotlib.use('Agg')\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom discrete_sampling.construct import construct_sample_alias\nfrom discrete_sampling.construct import construct_sample_interval\nfrom discrete_sampling.construct import construct_sample_ky_approx_encoding\nfrom discrete_sampling.construct import construct_sample_ky_approx_matrix\nfrom discrete_sampling.construct import construct_sample_ky_approx_matrix_cached\nfrom discrete_sampling.construct import construct_sample_ky_encoding\nfrom discrete_sampling.construct import construct_sample_ky_matrix\nfrom discrete_sampling.construct import construct_sample_ky_matrix_cached\nfrom discrete_sampling.construct import construct_sample_rejection_binary_search\nfrom discrete_sampling.construct import construct_sample_rejection_encoding\nfrom discrete_sampling.construct import construct_sample_rejection_hash_table\nfrom discrete_sampling.construct import construct_sample_rejection_matrix\nfrom discrete_sampling.construct import construct_sample_rejection_matrix_cached\nfrom discrete_sampling.construct import construct_sample_rejection_uniform\n\nfrom discrete_sampling.writeio import write_sample_alias\nfrom discrete_sampling.writeio import write_sample_interval\nfrom discrete_sampling.writeio import write_sample_ky_encoding\nfrom discrete_sampling.writeio import write_sample_ky_matrix\nfrom discrete_sampling.writeio import write_sample_ky_matrix_cached\nfrom discrete_sampling.writeio import write_sample_rejection_binary_search\nfrom discrete_sampling.writeio import write_sample_rejection_hash_table\nfrom discrete_sampling.writeio import write_sample_rejection_uniform\n\nfrom discrete_sampling.entropy import compute_entropy\nfrom discrete_sampling.entropy import get_alpha_entropies\nfrom discrete_sampling.utils import get_common_denominator\nfrom discrete_sampling.utils import get_common_numerators\nfrom discrete_sampling.utils import sample_dirichlet_multinomial_positive\n\nfrom parallel_map import parallel_map\nfrom parsable import parsable\n\ndef get_distribution_least_entropy(n, Z):\n assert n <= Z\n S = Z - n\n numerators = [1] * n\n numerators[0] += S\n assert sum(numerators) == Z\n return [Fraction(a, Z) for a in numerators]\n\ndef get_distribution_most_entropy(n, Z):\n assert n <= Z\n numerators = np.ones(n, dtype=int)\n S = Z - n\n numerators += S // n\n numerators[:(S%n)] += 1\n assert sum(numerators) == Z\n return [Fraction(int(a), Z) for a in numerators]\n\ndef get_distribution_entropy_bounds(n, Z):\n l = get_distribution_least_entropy(n, Z)\n h = get_distribution_most_entropy(n, Z)\n el = compute_entropy(l)\n eh = compute_entropy(h)\n assert el <= eh\n return (el, eh)\n\ndef write_samplers(args):\n (samplers, dirname, idx, p_target, entropy) = args\n structures = [\n ('ky.enc',\n construct_sample_ky_encoding,\n write_sample_ky_encoding),\n ('ky.mat',\n construct_sample_ky_matrix,\n write_sample_ky_matrix),\n ('ky.matc',\n construct_sample_ky_matrix_cached,\n write_sample_ky_matrix_cached),\n\n ('ky.approx.enc',\n construct_sample_ky_approx_encoding,\n write_sample_ky_encoding),\n ('ky.approx.mat',\n construct_sample_ky_approx_matrix,\n write_sample_ky_matrix),\n ('ky.approx.matc',\n construct_sample_ky_approx_matrix_cached,\n write_sample_ky_matrix_cached),\n\n ('rej.uniform',\n construct_sample_rejection_uniform,\n write_sample_rejection_uniform),\n ('rej.table',\n construct_sample_rejection_hash_table,\n write_sample_rejection_hash_table),\n ('rej.binary',\n construct_sample_rejection_binary_search,\n write_sample_rejection_binary_search),\n\n ('rej.enc',\n construct_sample_rejection_encoding,\n write_sample_ky_encoding),\n ('rej.mat',\n construct_sample_rejection_matrix,\n write_sample_ky_matrix),\n ('rej.matc',\n construct_sample_rejection_matrix_cached,\n write_sample_ky_matrix_cached),\n\n ('interval',\n construct_sample_interval,\n write_sample_interval),\n ('alias.exact',\n construct_sample_alias,\n write_sample_alias),\n ]\n\n for suffix, f_construct, f_write in structures:\n if samplers and suffix not in samplers:\n continue\n fpath = os.path.join(dirname, 'd.%05d.%s' % (idx, suffix))\n struc = f_construct(p_target)\n f_write(*struc, fpath)\n print(fpath)\n\n fname_dist = 'd.%05d.dist' % (idx,)\n fpath_dist = os.path.join(dirname, fname_dist)\n with open(fpath_dist, 'w') as f:\n n = len(p_target)\n Z = get_common_denominator(p_target)\n Ms = get_common_numerators(Z, p_target)\n f.write('%d\\n' % (Z,))\n f.write('%d %s\\n' % (n, ' '.join(map(str, Ms))))\n f.write('%1.5f\\n' % (entropy,))\n print(fpath_dist)\n\n # Make soft links to dist file for non ANCI C baselines.\n for suffix in ['alias.boost', 'inversion.std', 'alias.gsl']:\n if samplers and suffix not in samplers:\n continue\n fname_suffix = fname_dist.replace('.dist', '.%s' % (suffix,))\n fpath = os.path.join(dirname, fname_suffix)\n subprocess.check_output(['ln', fpath_dist, fpath])\n print(fpath)\n\n@parsable\ndef generate_distributions(N=10, Z=-1, seed=1, samplers='', thin=1,\n force=None, offset=0):\n \"\"\"Generate distributions and save to disk.\"\"\"\n Z = 2*N**2 + 1 if Z == - 1 else int(Z)\n dirname = 'dists.%d.%d.%d' % (N, Z, seed,)\n samplers = samplers.replace('\\'', '').split(' ') if samplers != '' else []\n if force and os.path.exists(dirname):\n shutil.rmtree(dirname)\n if not os.path.exists(dirname):\n os.mkdir(dirname)\n\n # XXX\n import sys; sys.setrecursionlimit(100000)\n\n rng = np.random.RandomState(seed)\n alphas = get_alpha_entropies(N, maxalpha=5, numalpha=1000, parallel=True)\n distributions = [\n sample_dirichlet_multinomial_positive(a, N, Z, rng)\n # for a in alphas\n for a in alphas[offset::thin]\n ]\n\n low, high = get_distribution_entropy_bounds(N, Z)\n entropies = parallel_map(compute_entropy, distributions)\n idxs = np.argsort(entropies)\n args = [\n (samplers, dirname, i, distributions[idx], entropies[idx])\n for i, idx in enumerate(idxs)\n ]\n parallel_map(write_samplers, args)\n # list(map(write_samplers, args))\n\nif __name__ == '__main__':\n parsable()\n","sub_path":"experiments/dists.py","file_name":"dists.py","file_ext":"py","file_size_in_byte":6832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"597088606","text":"'''웹 소설 로맨스 장르 페이지의 베스트 리그 >> 로맨스 장르\nname, writer, score의 정보를 가져와 보세요^^'''\n\nimport requests\nfrom bs4 import BeautifulSoup\n\n#### 웹소설 베스트리그 로맨스 1 page\n\nurl = \"https://novel.naver.com/best/genre.nhn?genre=101\"\n\n#http 요청 -> HTML 문서\nresponse = requests.get(url)\n#print(response.content)\nhtml_data = response.content\n\nsoup = BeautifulSoup(html_data, 'html.parser')\n\ntag_ul = soup.find(\"ul\",{\"class\":\"list_type1 v3 NE=a:lst_rom\"})\n#print(tag_ul)\n\ntag_lis = tag_ul.findAll(\"li\")\n#print(tag_lis)\n\nnaverWebFictions = []\n\nfor tag_li in tag_lis :\n # 웹 소설 제목\n tag_a = tag_li.find(\"a\")\n name = tag_a[\"title\"]\n\n #tag_img = tag_li.find(\"img\")\n #print(tag_img[\"alt\"])\n\n # 웹소설 작가\n tag_span = tag_li.find(\"span\",{\"class\":\"ellipsis\"})\n writer = tag_span.text\n\n # 웹 소설 평점\n #tag_span_score = tag_li.find(\"span\",{\"class\":\"score_area\"})\n #print(tag_span_score)\n tag_em = tag_li.find(\"em\")\n score = tag_em.text\n\n naverWebFictions.append({\"name\":name,\"writer\":writer,\"score\":score})\n\nprint(naverWebFictions)\n","sub_path":"com/week5/pm/01_crawl_web_fictions.py","file_name":"01_crawl_web_fictions.py","file_ext":"py","file_size_in_byte":1148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"414074858","text":"from matplotlib import pyplot\nfrom pymongo import MongoClient\n\nuri = \"mongodb://admin:admin@ds021182.mlab.com:21182/c4e\"\n\nclient = MongoClient(uri)\ndb = client.get_database()\ncustomers = db[\"customers\"]\n\nrefs = {}\n\ncustomers_list = customers.find()\nfor customer in customers_list:\n refs[customer[\"ref\"]] = refs.get(customer[\"ref\"], 0) + 1\n\nprint(\"The number of customers group by​ 'refs': \")\nfor (k, v) in refs.items():\n print(k, v, sep = \": \")\n\nref_count = list(refs.values())\nref_names = list(refs.keys())\n\npyplot.pie(ref_count, labels=ref_names, autopct=\"%.3f %%\", shadow=True)\npyplot.title(\"References from Events, Ads and Word of Mouth\")\npyplot.axis(\"equal\")\npyplot.show()\n\nclient.close()","sub_path":"Lab01/homework/exercise_4.py","file_name":"exercise_4.py","file_ext":"py","file_size_in_byte":701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"169099561","text":"from dwr import *\nfrom dwr.ds_partition.openaq_avg_by_parameter import *\n\n# Expect to have average of the error less than 10% error\nEPSILON = 0.05\n\nSAMPLE_TYPE = 'adaptive'\nsample_table = sample_table_name(INPUT_TABLE, SAMPLE_TYPE)\nsample_result_table = sample_table_name(RESULT_TABLE, SAMPLE_TYPE)\n\n# language=HQL - Create voila adaptive table\nhiveql.execute(\"\"\"\n CREATE TABLE IF NOT EXISTS adaptive_allocation (\n stratum string,\n sample_rate double \n ) \n PARTITIONED BY (\n ds string,\n table_name string\n )\n\"\"\")\n\n# create result table\nlogging.info('create result table')\nhiveql.execute(create_result_table.format(sample_result_table))\n\n# get full table's schema\nschema_column, partition_column = schema(INPUT_TABLE)\n\nlogging.info('Create sampled table')\n# language=HQL - Create sampled table\nhiveql.execute(\"\"\"\n CREATE TABLE IF NOT EXISTS {table_name} (\n {schema},\n sample_rate double\n )\n PARTITIONED BY (ds string)\n\"\"\".format(\n table_name=sample_table,\n schema=','.join('{0} {1}'.format(i, schema_column[i]) for i in schema_column if i not in partition_column),\n))\n\nfor ds in ds_list:\n logging.info(\"DS: {0}\".format(ds))\n\n logging.info('get old sample rate')\n # language=HQL\n hiveql.execute(\"\"\"\n SELECT stratum,\n sample_rate\n FROM adaptive_allocation\n WHERE ds = '{ds}'\n AND table_name = '{table_name}' \n \"\"\".format(\n ds=yesterday(ds),\n table_name=RESULT_TABLE,\n ))\n alloc = hiveql.fetchall()\n if len(alloc) > 1:\n alloc = {r[0]: r[1] for r in alloc}\n else:\n alloc = {}\n logging.info(\"Previous alloc: {0}\".format(alloc))\n\n logging.info('Get error from sample_error')\n # language=HQL\n hiveql.execute(\"\"\"\n SELECT attribute,\n error\n FROM sample_error\n WHERE ds = '{ds}'\n AND table_name = '{table_name}'\n AND sample_type = '{sample_type}'\n AND sample_rate = '{sample_rate}' \n \"\"\".format(\n ds=yesterday(ds),\n table_name=RESULT_TABLE,\n sample_type=SAMPLE_TYPE,\n sample_rate=0.1,\n ))\n error = hiveql.fetchall()\n if len(error) > 1:\n error = {r[0]: r[1] for r in error}\n else:\n error = {}\n logging.info(\"Previous error: {0}\".format(error))\n\n # adaptive allocation\n alloc = {i: max(0.01, min(1.0, alloc.get(i, 0.1) * (1.0 + error[i] - EPSILON))) for i in error}\n\n # language=HQL - insert new allocation\n if len(alloc) > 0:\n hiveql.execute(\"\"\"\n INSERT OVERWRITE TABLE adaptive_allocation \n PARTITION(ds='{ds}', table_name='{table_name}')\n VALUES {values} \n \"\"\".format(\n ds=ds,\n table_name=RESULT_TABLE,\n values=', '.join([\"('{0}', {1})\".format(k, alloc[k]) for k in alloc]),\n ))\n\n logging.info('Draw sample')\n # language=HQL\n hiveql.execute(\"\"\"\n INSERT OVERWRITE TABLE {table_name} PARTITION (ds = '{ds}')\n SELECT \n {schema},\n COALESCE(sample_rate, '{default_sample_rate}') AS sample_rate\n FROM {full_table} full_table \n LEFT JOIN adaptive_allocation alloc\n ON alloc.ds = '{ds}'\n AND alloc.table_name = '{table_name}'\n AND alloc.stratum = full_table.parameter || '_' || full_table.unit \n WHERE full_table.ds = '{ds}'\n AND RAND() <= COALESCE(sample_rate, '{default_sample_rate}')\n \"\"\".format(\n table_name=sample_table,\n full_table=INPUT_TABLE,\n ds=ds,\n schema=', '.join(i for i in schema_column if i not in partition_column),\n default_sample_rate=0.1,\n ))\n\n # run query over sampled table\n logging.info('run query over sampled table')\n hiveql.execute(average_by_parameter_sql.format(\n ds=ds,\n input_table=sample_table,\n result_table=sample_result_table,\n ))\n\n # evaluate sample error\n sample_evaluate(\n table_name=RESULT_TABLE,\n sample_type=SAMPLE_TYPE,\n sample_rate=0.1,\n group_by_columns=['parameter', 'unit'],\n aggregation_columns=['average'],\n partition={'ds': ds},\n sample_table=sample_result_table,\n )\n","sub_path":"dwr/adaptive_sampling/adaptive_senate_sampling_avg_parameter.py","file_name":"adaptive_senate_sampling_avg_parameter.py","file_ext":"py","file_size_in_byte":4265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"385800621","text":"from rest_framework import serializers\nfrom selectable.forms.widgets import AutoCompleteSelectWidget, AutoCompleteSelectMultipleWidget\n\nfrom costs.models import RVU, OrderSet\nfrom costs.lookups import RVULookup\nfrom myuser.models import FavoriteRVU, TestPerformed\n\n\nclass RVUSerializer(serializers.ModelSerializer):\n \"\"\"\n django-rest-framework serializer class to construct a JSON representation\n of the RVU data model.\n \"\"\"\n class Meta:\n model = RVU\n fields = ('id',\n 'year',\n 'code',\n 'mod',\n 'description',\n 'work',\n 'facility',\n 'malpractice',\n 'name' )\n\n name = serializers.SerializerMethodField('get_name')\n\n def get_name(self, obj):\n return obj.__unicode__()\n\n\nclass OrderSetSerializer(serializers.ModelSerializer):\n \"\"\"\n django-rest-framework serializer class to construct a JSON representation\n of the OrderSet data model.\n\n Returns a list or RVU primary keys.\n \"\"\"\n\n class Meta:\n model = OrderSet\n fields = ('name', 'RVUs')\n\n def __init__(self, instance=None, data=None, files=None,\n context=None, partial=False, many=None,\n allow_add_remove=False, **kwargs):\n super(OrderSetSerializer, self).__init__(instance, data, files,\n context, partial, many,\n allow_add_remove, **kwargs)\n self.fields['RVUs'].widget = AutoCompleteSelectMultipleWidget(lookup_class=RVULookup)\n\n\nclass OrderSetSerializerFull(OrderSetSerializer):\n \"\"\"\n django-rest-framework serializer class to construct a JSON representation\n of the OrderSet data model.\n\n Returns a list or RVU objects, using the RVU serializer.\n \"\"\"\n RVUs = RVUSerializer()\n\n\nclass FavoriteRVUSerializer(serializers.ModelSerializer):\n \"\"\"\n django-rest-framework serializer class to construct a JSON representation\n of a list of favorite RVUs, using the primary-key for each only.\n \"\"\"\n class Meta:\n model = FavoriteRVU\n fields = ('rvu', )\n\n def __init__(self, instance=None, data=None, files=None,\n context=None, partial=False, many=None,\n allow_add_remove=False, **kwargs):\n super(FavoriteRVUSerializer, self).__init__(instance, data, files,\n context, partial, many,\n allow_add_remove, **kwargs)\n self.fields['rvu'].widget = AutoCompleteSelectWidget(lookup_class=RVULookup)\n\n\nclass TestPerformedSerializer(serializers.ModelSerializer):\n \"\"\"\n django-rest-framework serializer class to construct a JSON representation\n of a list of the tests which have been performed, using the primary-key for\n each RVU only. Does not return the username or date performed.\n \"\"\"\n class Meta:\n model = TestPerformed\n fields = ('rvu', )\n\n def __init__(self, instance=None, data=None, files=None,\n context=None, partial=False, many=None,\n allow_add_remove=False, **kwargs):\n super(TestPerformedSerializer, self).__init__(instance, data, files,\n context, partial, many,\n allow_add_remove, **kwargs)\n self.fields['rvu'].widget = AutoCompleteSelectWidget(lookup_class=RVULookup)\n","sub_path":"api/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":3548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"385349933","text":"import requests\r\nimport urllib.request\r\nfrom bs4 import *\r\n\r\ndef course_dollars():\r\n \"\"\"Here we try to get course of dollars BeautifulSoup and Request\"\"\"\r\n \r\n path = \"https://prixdubaril.com/\"\r\n\r\n r = requests.get(path)\r\n\r\n page = r.content\r\n soup = BeautifulSoup(page, \"html.parser\")\r\n\r\n propriete = soup.find_all(\"span\")\r\n\r\n\r\n liste = []\r\n liste.append(str(propriete))\r\n\r\n\r\n dollar = liste[0][520:525]\r\n \r\n if dollar[0] == '+':\r\n return 'dollars augmente'\r\n else:\r\n return 'dollars baisse '\r\n #we let this space for visual aspect (for html page)\r\n\r\n\r\n\r\ndef soup_function():\r\n \r\n #course_dollars()\r\n dol = course_dollars() \r\n\r\n path = \"https://prixdubaril.com/\" \r\n r = requests.get(path)\r\n page = r.content\r\n soup = BeautifulSoup(page, \"html.parser\") \r\n\r\n propriete = soup.find_all(\"div\", {'class':'carburant_red'})\r\n\r\n return propriete, dol\r\n\r\n\r\ndef finding_function():\r\n \"\"\"Here we finding this words\r\n becasue we search red color\r\n it significate his increase\"\"\"\r\n \r\n #soup_function()\r\n propriete, dol = soup_function()\r\n \r\n a = str(propriete).find('Gas')\r\n b = str(propriete).find('Gas+')\r\n c = str(propriete).find('Gazole')\r\n d = str(propriete).find('Gazole+')\r\n\r\n\r\n gas = False\r\n gasplus = False \r\n \r\n if a or c >= 0: \r\n gas = True\r\n elif b or d >=0:\r\n gasplus = True\r\n\r\n return gas, gasplus, dol\r\n\r\n\r\n\r\n\r\ndef recup_tag():\r\n \"\"\"Here we get diesel and dollars courses\r\n to analyze in France the sale of siesel and\r\n therefore the rate of diesel car right now\"\"\"\r\n\r\n #finding_function()\r\n gas, gasplus, dol = finding_function()\r\n \r\n if gas == True and\\\r\n gasplus == True and\\\r\n dol == 'dollars baisse ':\r\n return 'tres fort'\r\n\r\n elif gas == True and\\\r\n gasplus == False and\\\r\n dol == 'dollars augmente':\r\n return 'moyen'\r\n\r\n elif gas == False and\\\r\n gasplus == True and\\\r\n dol == 'dollars augmente':\r\n return 'moyen'\r\n\r\n elif gas == False and\\\r\n gasplus == False and\\\r\n dol == 'dollars augmente':\r\n return 'bas'\r\n\r\n\r\n elif gas == True and\\\r\n gasplus == False and\\\r\n dol == 'dollars baisse ':\r\n return 'fort'\r\n\r\n elif gas == False and\\\r\n gasplus == True and\\\r\n dol == 'dollars baisse ':\r\n return 'fort'\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":"polu/donnée_site/diesel.py","file_name":"diesel.py","file_ext":"py","file_size_in_byte":2525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"376773026","text":"import torch\r\nimport torchvision\r\nimport numpy as np\r\n\r\nclass BaseTester():\r\n def __init__(self, model):\r\n self.model = model\r\n\r\n def extract(self, data_loader):\r\n self.model.eval()\r\n res_features = []\r\n\r\n for batch_index, (data, label) in enumerate(data_loader):\r\n print(\"batch_index is: {}\".format(batch_index))\r\n data = data.cuda()\r\n data = torch.autograd.Variable(data, volatile=True)\r\n output = self.model(data)\r\n output = output.data.cpu()\r\n res_features.extend(output.numpy())\r\n return np.array(res_features)\r\n\r\n\r\nclass TenCropTester():\r\n def __init__(self, model):\r\n self.model = model\r\n\r\n def extract(self, data_loader):\r\n self.model.eval()\r\n res_features = []\r\n len_ = len(data_loader)\r\n for batch_index, (data, label) in enumerate(data_loader):\r\n print(\"batch_index is: {}:{}\".format(batch_index,len_))\r\n data = data.cuda()\r\n data = torch.autograd.Variable(data, volatile=True)\r\n bs, ncrops, c, h, w = data.size()\r\n # print(\"ncrops is:{}\".format(ncrops))\r\n output = self.model(data.view(-1, c, h, w))\r\n output = output.data.cpu()\r\n output_avg = output.view(bs, ncrops, -1).mean(1).view(bs,-1)\r\n res_features.extend(output_avg.numpy())\r\n return np.array(res_features)\r\n","sub_path":"code/pytorch-architectrue/base_tester.py","file_name":"base_tester.py","file_ext":"py","file_size_in_byte":1433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"491932170","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nimport numpy as np\nimport copy\n\nclass Quad():\n\n def __init__(self, pos_x, pos_y, pos_z, vel_x, vel_y, vel_z,\n phi, theta, psi):\n self.pos_x = pos_x\n self.pos_y = pos_y\n self.pos_z = pos_z\n self.vel_x = vel_x\n self.vel_y = vel_y\n self.vel_z = vel_z\n self.phi = phi\n self.theta = theta\n self.psi = psi\n\n self.dt= 0.02\n self.m = 0.04\n self.l = 0.2\n self.g = 9.81\n # self.k1 = np.array([0.02, 0.02, 0.02])\n self.k1 = np.array([0, 0, 0])\n # self.k2 = np.array([0.1, 0.1, 0.1])\n self.k2 = np.array([0, 0, 0])\n\n def next_state(self, state, act, cur_t, act_noise=0.1):\n '''\n Dynamics for quad\n '''\n\n act = act.reshape([4,])\n state = state.reshape([9,])\n # if act_noise:\n # act = np.random.normal(act, act_noise)\n thrust = act[0]\n omega = act[1:]\n [pos_x, pos_y, pos_z, vel_x, vel_y, vel_z, phi, theta, psi] = state\n # wind = self.wind(pos_x, pos_y, pos_z)\n wind = self.wind(pos_x, pos_y, pos_z, cur_t)\n Rotation = np.array([\n np.cos(psi) * np.sin(theta) * np.cos(phi) + np.sin(psi) * np.sin(phi),\n np.sin(psi) * np.sin(theta) * np.cos(phi) - np.cos(psi) * np.sin(phi),\n np.cos(theta) * np.cos(phi)\n ])\n omega2euler = np.array([\n [1, np.sin(phi)*np.tan(theta), np.cos(phi)*np.tan(theta)],\n [0, np.cos(phi), -np.sin((phi))],\n [0, np.sin(phi)/np.cos(theta), np.cos(phi)/np.cos(theta)]\n ])\n accel = np.array([0,0,-self.g]) + (Rotation * thrust + wind - self.k1 * np.square(np.array([vel_x,vel_y,vel_z]))) / self.m\n vel = np.array([vel_x,vel_y,vel_z]) + accel * self.dt\n angle_dot = np.dot(omega2euler,omega).squeeze()\n\n return np.squeeze(np.concatenate([vel,accel,angle_dot], axis=0))\n\n def getState(self):\n return np.array(copy.deepcopy([self.pos_x, self.pos_y, self.pos_z,\n self.vel_x, self.vel_y, self.vel_z,\n self.phi, self.theta, self.psi]))\n\n # Pick wind speed function.\n def wind(self, x, y, z, t):\n v = [\n 0*1.75,\n 0*1.75,\n 0*0.05,\n ]\n return np.array(v)\n #\n # def wind(self, x, y, z, t):\n # if t >= 600:\n # v = [\n # -0.3 + 0.2 * np.cos((x - 1) * 0.86 / 20) * 0.86 / 1 + 0.5,\n # 0.3 - 0.2 * np.cos((y - 5) * 0.86 / 20) * 0.86 / 1 + 0.5,\n # 0.1 + 0.3,\n # ]\n # if t >= 300 and t <= 600:\n # v = [\n # -0.3 + 0.2 * np.cos((x - 1) * 0.86 / 20) * 0.86 / 1,\n # 0.3 - 0.2 * np.cos((y - 5) * 0.86 / 20) * 0.86 / 1,\n # 0.1,\n # ]\n # else:\n # v = [\n # -0.30,\n # 0.30,\n # 0.1,\n # ]\n # return np.array(v)\n\n def set_state(self, state):\n [self.pos_x, self.pos_y, self.pos_z,\n self.vel_x, self.vel_y, self.vel_z,\n self.phi, self.theta, self.psi] = state\n\n\nclass quad_env():\n def __init__(self):\n # set params for quad\n self.L = 20\n self.t = 0\n self.g = 9.81\n self.dt= 0.02\n self.state_dim = 9\n self.action_dim = 4\n\n # self.curve_pos = lambda t: np.array([-2 * np.sin(0.5 * t), 5 + 2 * np.cos(0.5 * t), 0 * t + 1])\n # self.curve_vel = lambda t: np.array([-np.cos(0.5 * t), -np.sin(0.5 * t), 0 * t])\n # self.curve_accel_0 = np.array([-1,0, 0])\n\n self.curve_pos = lambda t: np.array([\n np.clip(1.5 * (t - 0.02 * 200), 0, 1.5 * 0.02 * 100)\n + np.clip(1.5 * (t - 0.02 * 500), 0, 1.5 * 0.02 * 100)\n + np.clip(1.5 * (t - 0.02 * 800), 0, 1.5 * 0.02 * 200),\n\n np.clip(1.5 * t, 0, 1.5 * 0.02 * 200)\n + np.clip(-1.5 * (t - 0.02 * 300), -1.5 * 0.02 * 200, 0)\n + np.clip(1.5 * (t - 0.02 * 600), 0, 1.5 * 0.02 * 200),\n\n np.clip(1.5 * t, 0, 1.5 * 0.02 * 200)\n + np.clip(-1.5 * (t - 0.02 * 300), -1.5 * 0.02 * 200, 0)\n + np.clip(1.5 * (t - 0.02 * 600), 0, 1.5 * 0.02 * 200)])\n self.curve_vel = lambda t: np.array([\n ((np.clip(1.5 * (t + 0.02 - 0.02 * 200), 0, 1.5 * 0.02 * 100)\n + np.clip(1.5 * (t + 0.02 - 0.02 * 500), 0, 1.5 * 0.02 * 100)\n + np.clip(1.5 * (t + self.dt- 0.02 * 800), 0, 1.5 * 0.02 * 200))\n - (np.clip(1.5 * (t - 0.02 * 200), 0, 1.5 * 0.02 * 100)\n + np.clip(1.5 * (t - 0.02 * 500), 0, 1.5 * 0.02 * 100)\n + np.clip(1.5 * (t - 0.02 * 800), 0, 1.5 * 0.02 * 200))) / self.dt,\n\n ((np.clip(1.5 * (t + self.dt), 0, 1.5 * 0.02 * 200)\n + np.clip(-1.5 * (t + self.dt - 0.02 * 300), -1.5 * 0.02 * 200, 0)\n + np.clip(1.5 * (t + self.dt - 0.02 * 600), 0, 1.5 * 0.02 * 200))\n - (np.clip(1.5 * t, 0, 1.5 * 0.02 * 200)\n + np.clip(-1.5 * (t - 0.02 * 300), -1.5 * 0.02 * 200, 0)\n + np.clip(1.5 * (t - 0.02 * 600), 0, 1.5 * 0.02 * 200))) / self.dt,\n\n ((np.clip(1.5 * (t + self.dt), 0, 1.5 * 0.02 * 200)\n + np.clip(-1.5 * (t + self.dt - 0.02 * 300), -1.5 * 0.02 * 200, 0)\n + np.clip(1.5 * (t + self.dt - 0.02 * 600), 0, 1.5 * 0.02 * 200))\n - (np.clip(1.5 * t, 0, 1.5 * 0.02 * 200)\n + np.clip(-1.5 * (t - 0.02 * 300), -1.5 * 0.02 * 200, 0)\n + np.clip(1.5 * (t - 0.02 * 600), 0, 1.5 * 0.02 * 200))) / self.dt,\n ])\n\n self.curve_accel_0 = np.array([0, 0.5, 0.5])\n #\n # self.curve_pos = lambda t: np.array([0,0,4])\n # self.curve_vel = lambda t: np.array([0,0,0])\n # self.curve_accel_0 = np.array([0, 0, 0])\n self.init_pos = self.curve_pos(0)\n self.init_vel = self.curve_vel(0)\n self.init_accel = self.curve_accel_0\n self.psi_d = 0\n self.init_theta,self.init_phi = self.cal_theta_phi(self.init_accel, self.psi_d)\n self.quad = Quad(self.init_pos[0], self.init_pos[1], self.init_pos[2],\n self.init_vel[0], self.init_vel[1], self.init_vel[2],\n self.init_phi, self.init_theta, self.psi_d)\n # self.quad = Quad(0,0,0,0,0,0,0,0,0)\n # self.cur_angle = np.zeros(3)\n # self.curve = np.load('curve.npy')\n self.cur_angle = np.array([self.init_phi, self.init_theta, self.psi_d])\n self.barrier = np.array([\n # [3, 3, 3, 1],\n # [7, 7, 7, 1],\n # [3, 5, 1, 1],\n # [6, 6, 4, 1],\n # [7, 3, 5, 1],\n # [2, 6, 8, 1],\n # [4, 4, 2, 1],\n # [5, 7, 5, 1],\n # [7, 7, 5, 1],\n [-2 * np.sin(0.5 * 620 * 0.02), 5 + 2 * np.cos(0.5 * 620 * 0.02), .4 * 620 * 0.02],\n [-2 * np.sin(0.5 * 520 * 0.02) - 0.3, 4.15 + 2 * np.cos(0.5 * 600 * 0.02), .4 * 580 * 0.02],\n [-2 * np.sin(0.5 * 520 * 0.02) - 0.35, 4.6 + 2 * np.cos(0.5 * 600 * 0.02), .4 * 590 * 0.02],\n [-2 * np.sin(0.5 * 600 * 0.02), 5 + 2 * np.cos(0.5 * 610 * 0.02), .4 * 520 * 0.02]\n # self.curve_pos(20),\n ])\n self.obstacles = []\n self.obstacle_without_center = []\n # for i in range(10):\n # center = np.random.random(3,) * np.array([4,4,4]) + np.array([-2,3,0])\n # scale = 1\n # pts = np.random.random([3, 6])\n # pts = pts - np.mean(pts, axis=1)[:, np.newaxis]\n # pts = scale * pts + center[:, np.newaxis]\n # self.obstacles.append(pts)\n # for obstacle in self.barrier:\n # center = obstacle[:3]\n # scale = 1\n # # pts = np.array([[1/3,0,0],[0,-1/3/3**0.5,0],[0,1/3/3**0.5,0],[1/9,0,4]]).T\n # pts = np.random.random([3, 6])\n # pts = pts - np.mean(pts, axis=1)[:, np.newaxis]\n # self.obstacle_without_center.append(pts)\n # pts = scale * pts + center[:, np.newaxis]\n # self.obstacles.append(pts)\n\n def cal_theta_phi(self, accel, psi_d):\n x_dd, y_dd, z_dd = accel\n belta_a = x_dd * np.cos(psi_d) + y_dd * np.sin(psi_d)\n belta_b = z_dd + self.g\n belta_c = x_dd * np.sin(psi_d) - y_dd * np.cos(psi_d)\n theta_d = np.arctan2(belta_a,belta_b)\n phi_d = np.arctan2(belta_c, np.sqrt(belta_a ** 2 + belta_b ** 2))\n return theta_d, phi_d\n\n def getReward(self, action):\n s = self.quad.getState()\n r = np.sum(abs(action),axis=0)\n return r\n\n def reset(self, state=None):\n self.t = 0\n # [a,b,c] = np.random.random([3,])\n # a,b,c = 0.25, 0.25, 0.25\n # self.curve_pos = lambda t: np.array([(a+b)*t,(c+b)*t,(a+c)*t])\n # self.curve_vel = lambda t: np.array([(a+b),(c+b),(a+c)])\n # self.curve_accel = lambda t: np.array([0, 0, 0])\n self.init_pos = self.curve_pos(0)\n self.init_vel = self.curve_vel(0)\n self.init_accel = self.curve_accel_0\n self.psi_d = 0\n self.init_theta,self.init_phi = self.cal_theta_phi(self.init_accel, self.psi_d)\n self.cur_angle = np.array([self.init_phi, self.init_theta, self.psi_d])\n if not state:\n self.quad.set_state([self.init_pos[0]+0., self.init_pos[1]+0., self.init_pos[2]-0.,\n self.init_vel[0],self.init_vel[1],self.init_vel[2],0, 0,0])\n # self.quad.set_state([self.init_pos[0]+0., self.init_pos[1]+0., self.init_pos[2]-0.,\n # 0,0,0,0,0,0])\n else:\n state = np.squeeze(state)\n self.quad.set_state(state)\n return self.quad.getState()\n\n def step(self, action):\n # Runge-Kutta methods\n state = self.quad.getState()\n k1 = np.array(self.quad.next_state(state, action, self.t, 0) * self.quad.dt)\n # k2 = np.array(self.quad.next_state(state + k1/2.0, action) * self.quad.dt)\n # k3 = np.array(self.quad.next_state(state + k2/2.0, action) * self.quad.dt)\n # k4 = np.array(self.quad.next_state(state + k3, action) * self.quad.dt)\n r = self.getReward(action)\n self.t = self.t + self.quad.dt\n flag = False\n self.quad.set_state(state + (k1))# + 2.0 * (k2 + k3) + k4) / 6.0)\n\n # self.obstacles[0] = self.obstacle_without_center[0] + self.curve_pos(max(0, 4 - self.t)).reshape(-1,1)\n # self.obstacles[1] = self.obstacle_without_center[1] + self.curve_pos(max(0, 12 - self.t)).reshape(-1,1)\n # self.obstacles[2] = self.obstacle_without_center[2] + self.curve_pos(max(0, 20 - self.t)).reshape(-1,1)\n\n if self.t == self.L:\n self.t = 0\n flag = True\n return self.quad.getState(), r, flag\n\n def predict_f_g(self, obs):\n # Params\n self.dt = self.quad.self.dt\n m = self.quad.m\n g = self.quad.g\n dO = self.state_dim\n obs = obs.reshape(-1, dO)\n\n [pos_x, pos_y, pos_z, vel_x, vel_y, vel_z, phi, theta, psi] = obs.T\n\n sample_num = obs.shape[0]\n # calculate f with size [-1,9,1]\n f = np.concatenate([\n np.array(vel_x).reshape(sample_num, 1),\n np.array(vel_y).reshape(sample_num, 1),\n np.array(vel_z - g * self.dt).reshape(sample_num, 1),\n np.zeros([sample_num, 1]),\n np.zeros([sample_num, 1]),\n -g * np.ones([sample_num, 1]).reshape(-1, 1),\n np.zeros([sample_num,3]),\n ], axis=1)\n f = f * self.dt + obs\n f = f.reshape([-1, dO, 1])\n # calculate g with size [-1,9,4]\n accel_x = np.concatenate([\n (np.cos(psi) * np.sin(theta) * np.cos(phi) + np.sin(psi) * np.sin(phi)).reshape([-1, 1, 1]) / m,\n np.zeros([sample_num, 1, 3])\n ], axis=2)\n accel_y = np.concatenate([\n (np.sin(psi) * np.sin(theta) * np.cos(phi) - np.cos(psi) * np.sin(phi)).reshape([-1, 1, 1]) / m,\n np.zeros([sample_num, 1, 3])\n ], axis=2)\n accel_z = np.concatenate([\n (np.cos(theta) * np.cos(phi)).reshape([-1, 1, 1]) / m,\n np.zeros([sample_num, 1, 3])\n ], axis=2)\n phi_dot = np.concatenate([\n np.zeros([sample_num, 1, 1]),\n np.ones([sample_num, 1, 1]),\n (np.sin(phi)*np.tan(theta)).reshape([-1,1,1]),\n (np.cos(phi)*np.tan(theta)).reshape([-1,1,1])\n ], axis=2)\n theta_dot = np.concatenate([\n np.zeros([sample_num, 1, 2]),\n np.cos(phi).reshape([-1,1,1]),\n -np.sin(phi).reshape([-1,1,1])\n ], axis=2)\n psi_dot = np.concatenate([\n np.zeros([sample_num, 1, 2]),\n (np.sin(phi)/np.cos(theta)).reshape([-1,1,1]),\n (np.cos(phi)/np.cos(theta)).reshape([-1,1,1])\n ], axis=2)\n g_mat = np.concatenate([\n accel_x * self.dt,\n accel_y * self.dt,\n accel_z * self.dt,\n accel_x,\n accel_y,\n accel_z,\n phi_dot,\n theta_dot,\n psi_dot\n ], axis=1)\n g_mat = self.dt * g_mat\n return f, g_mat, np.copy(obs)\n\n def _predict_next_obs_uncertainty(self, obs, cur_acs, t=None, agent=None):\n f_nom, g, x = self.predict_f_g(obs)\n cur_acs = np.asarray(cur_acs).reshape([-1, 4, 1])\n\n # if (agent.firstIter == 1 and t < 20 * 0.02):\n # [m1, std1] = agent.GP_model[0].predict(x, return_std=True)\n # [m2, std2] = agent.GP_model[1].predict(x, return_std=True)\n # [m3, std3] = agent.GP_model[2].predict(x, return_std=True)\n # [m4, std4] = agent.GP_model[3].predict(x, return_std=True)\n # [m5, std5] = agent.GP_model[4].predict(x, return_std=True)\n # [m6, std6] = agent.GP_model[5].predict(x, return_std=True)\n #\n # f_nom[:, 6] = f_nom[:, 6] + m1 + np.sqrt(2 * np.log(1.667 * 15 * (np.pi * step_time) ** 2)) * 0\n # f_nom[:, 7] = f_nom[:, 7] + m2 + np.sqrt(2 * np.log(1.667 * 15 * (np.pi * step_time) ** 2)) * 0\n # f_nom[:, 9] = f_nom[:, 9] + m3 + np.sqrt(2 * np.log(1.667 * 15 * (np.pi * step_time) ** 2)) * 0\n # f_nom[:, 10] = f_nom[:, 10] + m4 + np.sqrt(2 * np.log(1.667 * 15 * (np.pi * step_time) ** 2)) * 0\n # f_nom[:, 12] = f_nom[:, 12] + m5 + np.sqrt(2 * np.log(1.667 * 15 * (np.pi * step_time) ** 2)) * 0\n # f_nom[:, 13] = f_nom[:, 13] + m6 + np.sqrt(2 * np.log(1.667 * 15 * (np.pi * step_time) ** 2)) * 0\n # elif (agent.firstIter == 1 and t >= 20 * 0.02):\n # [m1, std1] = agent.GP_model[0].predict(x, return_std=True)\n # [m2, std2] = agent.GP_model[1].predict(x, return_std=True)\n # [m3, std3] = agent.GP_model[2].predict(x, return_std=True)\n # [m4, std4] = agent.GP_model[3].predict(x, return_std=True)\n # [m5, std5] = agent.GP_model[4].predict(x, return_std=True)\n # [m6, std6] = agent.GP_model[5].predict(x, return_std=True)\n #\n # f_nom[:, 6] = f_nom[:, 6] + m1 + np.sqrt(2 * np.log(1.667 * 15 * (np.pi * step_time) ** 2))\n # f_nom[:, 7] = f_nom[:, 7] + m2 + np.sqrt(2 * np.log(1.667 * 15 * (np.pi * step_time) ** 2))\n # f_nom[:, 9] = f_nom[:, 9] + m3 + np.sqrt(2 * np.log(1.667 * 15 * (np.pi * step_time) ** 2))\n # f_nom[:, 10] = f_nom[:, 10] + m4 + np.sqrt(2 * np.log(1.667 * 15 * (np.pi * step_time) ** 2))\n # f_nom[:, 12] = f_nom[:, 12] + m5 + np.sqrt(2 * np.log(1.667 * 15 * (np.pi * step_time) ** 2))\n # f_nom[:, 13] = f_nom[:, 13] + m6 + np.sqrt(2 * np.log(1.667 * 15 * (np.pi * step_time) ** 2))\n # else:\n # [m1, std1] = agent.GP_model_prev[0].predict(x, return_std=True)\n # [m2, std2] = agent.GP_model_prev[1].predict(x, return_std=True)\n # [m3, std3] = agent.GP_model_prev[2].predict(x, return_std=True)\n # [m4, std4] = agent.GP_model_prev[3].predict(x, return_std=True)\n # [m5, std5] = agent.GP_model_prev[4].predict(x, return_std=True)\n # [m6, std6] = agent.GP_model_prev[5].predict(x, return_std=True)\n #\n # f_nom[:, 6] = f_nom[:, 6] + m1 + np.sqrt(2 * np.log(1.667 * 15 * (np.pi * step_time) ** 2)) * std1\n # f_nom[:, 7] = f_nom[:, 7] + m2 + np.sqrt(2 * np.log(1.667 * 15 * (np.pi * step_time) ** 2)) * std2\n # f_nom[:, 9] = f_nom[:, 9] + m3 + np.sqrt(2 * np.log(1.667 * 15 * (np.pi * step_time) ** 2)) * std3\n # f_nom[:, 10] = f_nom[:, 10] + m4 + np.sqrt(2 * np.log(1.667 * 15 * (np.pi * step_time) ** 2)) * std4\n # f_nom[:, 12] = f_nom[:, 12] + m5 + np.sqrt(2 * np.log(1.667 * 15 * (np.pi * step_time) ** 2)) * std5\n # f_nom[:, 13] = f_nom[:, 13] + m6 + np.sqrt(2 * np.log(1.667 * 15 * (np.pi * step_time) ** 2)) * std6\n\n # f = f_nom.reshape(-1, 1, 9)\n next_obs = f_nom + np.matmul(g, cur_acs)\n return next_obs\n\n def cal_u1(self,state,state_dsr):\n vector = self.direction(state,state_dsr)[0]\n u1 = np.linalg.norm(vector)\n return u1\n\n def direction(self,state,state_dsr,gp_prediction=np.zeros(6,)):\n self.dt = self.quad.self.dt\n g = self.quad.g\n m = self.quad.m\n pos_direction = ((state_dsr[:3] - state[:3] - gp_prediction[:3] - state[3:6] * self.dt) / self.dt ** 2 + np.array([0, 0, g])) * m\n vel_direction = ((state_dsr[3:6] - gp_prediction[3:6] - state[3:6]) / self.dt + np.array([0, 0, g])) * m\n return pos_direction, vel_direction\n\n def cost_func(self, action, state, plan_hor, dO, dU, t0, agent=None):\n state = np.asarray(state).reshape((dO, ))\n action = np.asarray(action).reshape((-1, plan_hor, dU))\n t = self.t\n init_obs = np.tile(state, (action.shape[0],1))\n init_cost = np.zeros((action.shape[0],))\n self.dt = self.quad.self.dt\n # t0 = int(t0//self.dt)\n # plan_hor = min(plan_hor, self.curve.shape[0] - t0)\n for i in range(plan_hor):\n cur_acs = action[:, i, :].reshape(-1, dU, 1)\n next_obs = self._predict_next_obs_uncertainty(init_obs, cur_acs, t, agent)\n init_obs = np.squeeze(next_obs)\n # Here to set the tracking curve\n # init_cost += np.sum(np.square(target[3:6].T - init_obs[:,3:6]), axis=1) * np.exp(-i*0.01)\n\n target = self.curve_pos(t0+i*self.dt)\n # target_v = self.curve_vel(t0+i*self.dt)\n init_cost += np.sum(np.square(target[:3] - init_obs[:, :3]), axis=1)\n # init_cost += np.sum(np.square(init_obs[:, 8]))\n # for b in self.barrier:\n # d = np.sqrt(np.sum(np.square(init_obs[:, :3] - b[:3]), axis=1))\n # temp = (np.sqrt(np.sum(np.square(init_obs[:, :3] - b[:3]), axis=1)) <= np.sqrt(0.3) + self.quad.l)\n # init_cost += temp*1000\n # init_cost + (init_obs[:, 2] <= 0) * 0.1\n cost = init_cost\n return cost\n","sub_path":"nmpc_following_bak/quadenv.py","file_name":"quadenv.py","file_ext":"py","file_size_in_byte":19284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"403844529","text":"def open_file_as_list():\n f = open('day1.txt')\n lines = f.readlines()\n file_list = list(lines)\n return file_list\n\nf = open_file_as_list()\nfor line in f:\n value1 = int(line)\n for line in f:\n value2= int(line)\n for line in f:\n value3= int(line)\n if value1 + value2 + value3 == 2020:\n print(\"found match \" + str(value1) + \" \" + str(value2) + \" \" + str(value3))\n print(\"multplied: \" + str(value1*value2*value3))","sub_path":"day1/day1-part2.py","file_name":"day1-part2.py","file_ext":"py","file_size_in_byte":491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"339984908","text":"from django.conf.urls import include, url\r\nfrom rest_framework_nested import routers\r\n\r\nfrom insights.views import ProductTriedViewSet, VisitorViewSet\r\nfrom stores.views import StoreViewSet, ActivatePlanViewSet, SyncViewSet, ProductViewSet, \\\r\n NonAuthenticatedGetProductViewSet\r\n\r\napp_name = 'stores'\r\nrouter = routers.DefaultRouter()\r\nrouter.register(r'stores', StoreViewSet)\r\n\r\nstores_router = routers.NestedSimpleRouter(\r\n router, r'stores', lookup='store')\r\n\r\nstores_router.register(\r\n r'visitors', VisitorViewSet, base_name='store-visitors')\r\n\r\nstores_router.register(\r\n r'activate', ActivatePlanViewSet, base_name='store-activate-plan')\r\n\r\nstores_router.register(\r\n r'sync', SyncViewSet, base_name='store-sync')\r\n\r\nstores_router.register(\r\n r'products', ProductViewSet, base_name='store-products')\r\n\r\nstores_router.register(\r\n r'nonauthenticatedgetproduct', NonAuthenticatedGetProductViewSet,\r\n base_name='nonauthenticated-get-product')\r\n\r\nproducts_router = routers.NestedSimpleRouter(\r\n stores_router, r'products', lookup='product')\r\nproducts_router.register(\r\n r'tries', ProductTriedViewSet, base_name='product_tries')\r\n\r\nurlpatterns = [\r\n url(r'^', include(router.urls)),\r\n url(r'^', include(stores_router.urls)),\r\n url(r'^', include(products_router.urls)),\r\n]\r\n","sub_path":"stores/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"185899811","text":"# Plutus Bitcoin Brute Forcer\r\n# Made by Isaac Delly\r\n# https://github.com/Isaacdelly/Plutus\r\n# Donate: 1B1k2fMs6kEmpxdYor6qvd2MRVUX2zGEHa\r\n\r\nimport requests\r\nimport os\r\nimport binascii\r\nimport ecdsa\r\nimport hashlib\r\nimport base58\r\nimport time\r\nimport sys\r\nfrom multiprocessing import Process, Queue\r\n\r\nclass pause: # Counts API failures for timeout\r\n p = 0\r\n\r\ndef privateKey(): # Generates random 256 bit private key in hex format\r\n return binascii.hexlify(os.urandom(32)).decode('utf-8')\r\n\r\ndef publicKey(privatekey): # Private Key -> Public Key\r\n privatekey = binascii.unhexlify(privatekey)\r\n s = ecdsa.SigningKey.from_string(privatekey, curve = ecdsa.SECP256k1)\r\n return '04' + binascii.hexlify(s.verifying_key.to_string()).decode('utf-8')\r\n\r\ndef address(publickey): # Public Key -> Wallet Address\r\n alphabet = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\"\r\n c = '0'; byte = '00'; zero = 0\r\n var = hashlib.new('ripemd160')\r\n var.update(hashlib.sha256(binascii.unhexlify(publickey.encode())).digest())\r\n a = (byte + var.hexdigest())\r\n doublehash = hashlib.sha256(hashlib.sha256(binascii.unhexlify(a.encode())).digest()).hexdigest()\r\n address = a + doublehash[0:8]\r\n for char in address:\r\n if (char != c):\r\n break\r\n zero += 1\r\n zero = zero // 2\r\n n = int(address, 16)\r\n output = []\r\n while (n > 0):\r\n n, remainder = divmod (n, 58)\r\n output.append(alphabet[remainder])\r\n count = 0\r\n while (count < zero):\r\n output.append(alphabet[0])\r\n count += 1\r\n return ''.join(output[::-1])\r\n\r\ndef balance(address): # Query API for wallet balance\r\n try:\r\n API = requests.get(\"https://blockchain.info/q/addressbalance/\" + str(address) + \"/balance\")\r\n if (API.status_code == 429):\r\n pause.p += 1\r\n if (pause.p >= 10):\r\n print (\"\\nUnable to connect to API after several attempts\\nRetrying in 30 seconds\\n\")\r\n time.sleep(30)\r\n pause.p = 0\r\n return -1\r\n print(\"\\nHTTP Error Code: \" + str(API.status_code) + \"\\n\")\r\n return -1\r\n if (API.status_code != 200 and API.status_code != 400):\r\n print(\"\\nHTTP Error Code: \" + str(API.status_code) + \"\\nRetrying in 5 seconds\\n\")\r\n time.sleep(5)\r\n return -1\r\n balance = int(API.text)\r\n pause.p = 0\r\n return balance\r\n except:\r\n pause.p += 1\r\n if (pause.p >= 10):\r\n print (\"\\nUnable to connect to API after several attempts\\nRetrying in 30 seconds\\n\")\r\n time.sleep(30)\r\n pause.p = 0 \r\n return -1\r\n\r\ndef toWIF(privatekey): # Hex Private Key -> WIF format\r\n var80 = \"80\" + str(privatekey) \r\n var = hashlib.sha256(binascii.unhexlify(hashlib.sha256(binascii.unhexlify(var80)).hexdigest())).hexdigest()\r\n return str(base58.b58encode(binascii.unhexlify(str(var80) + str(var[0:8]))))\r\n\r\ndef Plutus(): # Main Plutus Function\r\n data = [0,0,0,0]\r\n while True:\r\n data[0] = privateKey()\r\n data[1] = publicKey(data[0])\r\n data[2] = address(data[1])\r\n data[3] = balance(data[2])\r\n if (data[3] == -1):\r\n continue\r\n if (data[3] == 0):\r\n print(\"{:<34}\".format(str(data[2])) + \" = \" + str(data[3]))\r\n if (data[3] > 0):\r\n print (\"\\naddress: \" + str(data[2]) + \"\\n\" +\r\n \"private key: \" + str(data[0]) + \"\\n\" +\r\n \"WIF private key: \" + str(toWIF(str(data[0]))) + \"\\n\" +\r\n \"public key: \" + str(data[1]).upper() + \"\\n\" +\r\n \"balance: \" + str(data[3]) + \"\\n\")\r\n file = open(\"plutus.txt\",\"a\")\r\n file.write(\"address: \" + str(data[2]) + \"\\n\" +\r\n \"private key: \" + str(data[0]) + \"\\n\" +\r\n \"WIF private key: \" + str(toWIF(str(data[0]))) + \"\\n\" +\r\n \"public key: \" + str(data[1]).upper() + \"\\n\" +\r\n \"balance: \" + str(data[3]) + \"\\n\" +\r\n \"Donate to the author of this program: 1B1k2fMs6kEmpxdYor6qvd2MRVUX2zGEHa\\n\\n\")\r\n file.close()\r\n\r\n### Multiprocessing Extension Made By Wayne Yao https://github.com/wx-Yao ###\r\n \r\ndef put_dataset(queue):\r\n while True:\r\n if queue.qsize() > 100:\r\n time.sleep(10)\r\n else:\r\n privatekey = privateKey()\r\n publickey = publicKey(privatekey)\r\n Address = address(publickey)\r\n WIF = toWIF(privatekey)\r\n dataset = (Address, privatekey, publickey, WIF)\r\n queue.put(dataset, block = False)\r\n return None\r\n\r\ndef worker(queue):\r\n time.sleep(1)\r\n while True:\r\n if queue.qsize() > 0:\r\n dataset = queue.get(block = True)\r\n balan = balance(dataset[0])\r\n process_balance(dataset, balan)\r\n else:\r\n time.sleep(3)\r\n return None\r\n\r\ndef process_balance(dataset,balance):\r\n if balance == -1 :\r\n return None\r\n elif balance == 0 :\r\n print(\"{:<34}\".format(str(dataset[0])) + \" = \" + str(balance))\r\n return None\r\n else:\r\n addr = dataset[0]\r\n privatekey = dataset[1]\r\n publickey = dataset[2]\r\n WIF = dataset[3]\r\n file = open(\"plutus.txt\",\"a\")\r\n file.write(\"address: \" + str(addr) + \"\\n\" +\r\n \"private key: \" + str(privatekey) + \"\\n\" +\r\n \"WIF private key: \" + str(WIF) + \"\\n\" +\r\n \"public key: \" + str(publickey).upper() + \"\\n\" +\r\n \"balance: \" + str(balance) + \"\\n\" +\r\n \"Donate to the author of this program: 1B1k2fMs6kEmpxdYor6qvd2MRVUX2zGEHa\\n\\n\")\r\n file.close()\r\n return None\r\n\r\ndef multi():\r\n processes = []\r\n dataset = Queue()\r\n datasetProducer = Process(target = put_dataset, args = (dataset,))\r\n datasetProducer.daemon = True\r\n processes.append(datasetProducer)\r\n datasetProducer.start()\r\n for core in range(4):\r\n work = Process(target = worker, args = (dataset,))\r\n work.deamon = True\r\n processes.append(work)\r\n work.start()\r\n try:\r\n datasetProducer.join()\r\n except KeyboardInterrupt:\r\n for process in processes:\r\n process.terminate()\r\n print('\\n\\n------------------------\\nALL PROCESSES TERMINATED\\n')\r\n\r\n### End of Multiprocessing Extension ###\r\n\r\ndef main():\r\n if (\"-m\" in sys.argv):\r\n print(\"\\n-------- MULTIPROCESSING MODE ACTIVATED --------\\n\")\r\n time.sleep(3)\r\n print(\"\\n|-------- Wallet Address --------| = Balance in Satoshi\")\r\n multi()\r\n else:\r\n print(\"\\n|-------- Wallet Address --------| = Balance in Satoshi\")\r\n Plutus()\r\n\r\nif __name__ == '__main__':\r\n main()\r\n \r\n","sub_path":"plutus.py","file_name":"plutus.py","file_ext":"py","file_size_in_byte":6848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"457641848","text":"import os\nfrom nose.tools import eq_, raises\nfrom pyexcel._compact import StringIO\nfrom pyexcel_text.jsonp import JsonParser\n\n\nclass TestStructure:\n\n def setUp(self):\n self.parser = JsonParser(\"json\")\n\n @raises(Exception)\n def test_wrong_format(self):\n sheet_name = 'test'\n self.content = self.parser.parse_file(get_file(\"unknown.json\"),\n sheet_name=sheet_name)\n\n @raises(Exception)\n def test_bad_dict(self):\n sheet_name = 'test'\n self.content = self.parser.parse_file(get_file(\"bad_dict.json\"),\n sheet_name=sheet_name)\n\n def test_dict(self):\n sheet_name = 'test'\n self.content = self.parser.parse_file(get_file(\"dict.json\"),\n sheet_name=sheet_name)\n expected = {\n sheet_name: [\n ['a', 'b', 'c'],\n [1, 2, 4],\n [2, 3, 5]\n ]\n }\n self._verify(expected)\n\n def test_records(self):\n sheet_name = 'test'\n self.content = self.parser.parse_file(get_file(\"records.json\"),\n sheet_name=sheet_name)\n expected = {\n sheet_name: [\n ['a', 'b', 'c'],\n [1, 2, 3],\n [1, 2, 4]\n ]\n }\n self._verify(expected)\n\n def test_book_dict(self):\n sheet_name = 'test'\n self.content = self.parser.parse_file(get_file(\"bookdict.json\"),\n sheet_name=sheet_name)\n expected = {\n 'sheet 1': [[1, 2], [2, 3]],\n 'sheet 2': [[1, 2], [3, 4]]\n }\n\n self._verify(expected)\n\n def _verify(self, expected):\n for key in self.content:\n self.content[key] = list(self.content[key])\n eq_(self.content, expected)\n\n\nclass TestMedia:\n\n def setUp(self):\n self.parser = JsonParser(\"json\")\n\n def test_file(self):\n self.content = self.parser.parse_file(get_file(\"array.json\"),\n sheet_name='test')\n self._verify()\n\n def test_stream(self):\n with open(get_file(\"array.json\"), 'r') as f:\n file_stream = StringIO(f.read())\n self.content = self.parser.parse_file_stream(file_stream,\n sheet_name='test')\n self._verify()\n\n def test_content(self):\n with open(get_file(\"array.json\"), 'r') as f:\n file_content = f.read()\n self.content = self.parser.parse_file_content(file_content,\n sheet_name='test')\n self._verify()\n\n def _verify(self):\n for key in self.content:\n self.content[key] = list(self.content[key])\n eq_(self.content, {'test': [[1, 2, 3]]})\n\n\ndef get_file(file_name):\n return os.path.join(\"tests\", \"fixtures\", file_name)\n","sub_path":"tests/test_jsonp.py","file_name":"test_jsonp.py","file_ext":"py","file_size_in_byte":3010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"300395833","text":"# -*- coding: utf-8 -*-\nimport sys\nimport os\nimport decode\n# import pyrouge\nimport shutil\n\n\ndef abstract2id(article, wd2idx):\n\ttext = article.split(\" \");\n\tresult = []\n\tfor w in text:\n\t\tif w not in wd2idx:\n\t\t\twd2idx[w] = len(wd2idx)\n\t\tresult.append(str(wd2idx[w]))\n\treturn \" \".join(result)\n\ndef word2id(wd2idx, in_path, out_path):\n\tfiles = os.listdir(in_path);\n\tfor file in files:\n\t\tf = open(os.path.join(in_path, file))\n\t\ttext = f.readline().strip();\n\t\tresult = abstract2id(text, wd2idx)\n\t\twith open(os.path.join(out_path, file), 'wb') as writer:\n\t\t\twriter.write(result)\n\nif __name__ == '__main__':\n\t# if len(sys.argv) != 2: # prints a message if you've entered flags incorrectly#\n\t# \traise Exception(\"please enter two argv, one ref_dir, one dec_dir\")\n\n\tvocab_dict = {}\n\tref_dir = sys.argv[1]\n\tdec_dir = sys.argv[2]\n\ttemp_ref_dir = \"temp_ref\"\n\ttemp_dec_dir = \"temp_dec\"\n\n\tshutil.rmtree(temp_ref_dir)\n\tos.mkdir(temp_ref_dir)\n\tshutil.rmtree(temp_dec_dir)\n\tos.mkdir(temp_dec_dir)\n\n\twd2idx = {}\n\tword2id(wd2idx, ref_dir, temp_ref_dir);\n\tword2id(wd2idx, dec_dir, temp_dec_dir);\n\n\tresults_dict = decode.rouge_eval(temp_ref_dir, temp_dec_dir) #一个ref_dir,一个dec_dir\n\tdecode.rouge_log(results_dict, dec_dir)","sub_path":"rouge.py","file_name":"rouge.py","file_ext":"py","file_size_in_byte":1208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"437067897","text":"import unittest\nfrom os.path import dirname, join as path_join, realpath\n\nfrom nichtparasoup.config import parse_yaml_file\n\n\nclass ConfigParserDefaultsTest(unittest.TestCase):\n\n def test_set_optional_loglevel(self) -> None:\n # arrange\n file = realpath(path_join(dirname(__file__), 'configs', 'positive', 'logging_level_missing.yaml'))\n # act\n config = parse_yaml_file(file)\n # assert\n self.assertEqual(config['logging']['level'], 'INFO')\n\n def test_set_optional_weight(self) -> None:\n # arrange\n file = realpath(path_join(dirname(__file__), 'configs', 'positive', 'crawler_weight_missing.yaml'))\n # act\n config = parse_yaml_file(file)\n # assert\n self.assertEqual(len(config[\"crawlers\"]), 1)\n self.assertEqual(config[\"crawlers\"][0][\"weight\"], 1)\n\n def test_set_optional_config(self) -> None:\n # arrange\n file = realpath(path_join(dirname(__file__), 'configs', 'positive', 'crawler_config_missing.yaml'))\n # act\n config = parse_yaml_file(file)\n # assert\n self.assertEqual(len(config[\"crawlers\"]), 1)\n self.assertDictEqual(config[\"crawlers\"][0][\"config\"], dict())\n","sub_path":"tests/test_10_nichtparasoup/test_config/test_config_parser.py","file_name":"test_config_parser.py","file_ext":"py","file_size_in_byte":1210,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"433180620","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n# Exstrakey\n# Coded by Nedi Senja\n# Github: https://github.com/stepbystepexe/Exstrakey\n\nimport os, sys, time, random\nfrom time import sleep\n\ninfo = \"\"\"\nNama : Exstrakey\nVersi : 2.2 (Update: 26 Januari 2020, 8:00 AM)\nTanggal : 15 Juli 2019\nAuthor : Nedi Senja\nTujuan : Menampilkan keyboard plus\n untuk bantu para nob seperti saya\nTerimakasih : Allah SWT.\n FR13NDS, & seluruh\n manusia seplanet bumi\nNB : Manusia gax ada yang sempurna\n sama kaya tool ini.\n Silahkan laporkan kritik atau saran\n Ke - Email: d_q16x@outlook.co.id\n - WhatsApp: https://tinyurl.com/wel4alo\n\n[ \\033[4mGunakan tool ini dengan bijak \\033[0m]\\n \"\"\"\n\nexample = \"\"\"\\033[0;43;90;1m[ Exstrakey, My Github: @stepbystepexe ]\\033[0m\"\"\"\n\nlogo = \"\"\"\n \\033[0;35m█▀▀▀▀ █ █ █▀▀▀▀ ▀▀█▀▀ █▀▀▀▄ █▀▀▀█ \\033[0;37m█ █ █▀▀▀▀ █ █\n \\033[0;35m█▀▀▀ ▄▀▀▀▄ ▀▀▀▀█ █ █▀▀▀▄ █▀▀▀█ \\033[0;37m█▀▀▀▄ █▀▀▀ ▀▀█▀▀\n \\033[0;35m▀▀▀▀▀ ▀ ▀ ▀▀▀▀▀ ▀ ▀ ▀ ▀ ▀ \\033[0;37m▀ ▀ ▀▀▀▀▀ ▀\n\"\"\"\n\ndef restart():\n python = sys.executable\n os.execl(python, python, * sys.argv)\n curdir = os.getcwd()\n\ndef loads():\n o = [' . ',' .. ',' ... ']\n for i in o:\n print('\\r\\033[0m[\\033[0;34m●\\033[0m] Loading'+i,end=''),;sys.stdout.flush();time.sleep(1)\n\ndef write(o):\n for i in o + '\\n':\n sys.stdout.write(i)\n sys.stdout.flush()\n time.sleep(0.03)\n\ndef usage():\n os.system('clear')\n os.system('reset')\n time.sleep(1)\n print()\n print(logo)\n print(example)\n print()\n write(\"\\033[0m[ \\033[32mINFO \\033[0m] \\033[3mSaya tidak real kalo code program saya ini ditiru\")\n write(\" Seburuk apaun itu tolong hargai karya milik orang\\033[0m\\n\")\n print()\n loads()\n sleep(1)\n print()\n print()\n write('\\x1b[0m[\\x1b[91;1m!\\x1b[0m] \\x1b[77;1mMengecek ...')\n print('\\x1b[0m[\\x1b[92;1m+\\x1b[0m] \\x1b[0mProses Penginstalan')\n print()\n sleep(3)\n write('\\x1b[0m[\\x1b[93;1m!\\x1b[0m] \\x1b[77;1mMembuat properti folder termux ...')\n sleep(3)\n try:\n os.mkdir('/data/data/com.termux/files/home/.termux')\n except:\n pass\n print('\\x1b[0m[\\x1b[94;1m+\\x1b[0m] \\x1b[0mSukses')\n print()\n sleep(3)\n write('\\x1b[0m[\\x1b[95;1m!\\x1b[0m] \\x1b[77;1mMembuat setup file ...')\n sleep(3)\n key = \"extra-keys = [['ESC','/','-','HOME','UP','END','ENTER','clear','exit'],['TAB','CTRL','ALT','LEFT','DOWN','RIGHT','F1','DEL','tor']]\"\n control = open('/data/data/com.termux/files/home/.termux/termux.properties','w')\n control.write(key)\n control.close()\n sleep(3)\n print('\\x1b[0m[\\x1b[96;1m+\\x1b[0m] \\x1b[0mSukses')\n print()\n sleep(3)\n write('\\x1b[0m[\\x1b[97;1m!\\x1b[0m] \\x1b[77;1mMenyetel ...')\n sleep(3)\n print('\\x1b[0m[\\x1b[90;1m+\\x1b[0m] \\x1b[0mBerhasil Semua')\n os.system('termux-reload-settings')\n print()\n print()\n input('[ Tekan Enter ]')\n restart()\n\nos.system('clear')\nos.system('reset')\nsleep(1)\nprint()\nprint(logo)\nprint(example)\nprint()\nprint(\"\\033[0m[\\033[1;96;2m1\\033[0m] \\033[1;77mGunakan Exstrakey\")\nprint()\nprint(\"\\033[0m[\\033[93;1m&\\033[0m] LISENSI\")\nprint(\"\\033[0m[\\033[94;1m#\\033[0m] Informasi\")\nprint(\"\\033[0m[\\033[92;1m*\\033[0m] Perbarui\")\nprint(\"\\033[0m[\\033[91;1m-\\033[0m] Keluar\")\nprint()\noption = input(\"\\033[0m(\\033[105;77;1m/\\033[0m) \\033[1;77mMasukan opsi: \\033[0m\")\nif option.strip() in '1 gunakan'.split():\n write(\"\\n\\033[0m[\\033[32m●\\033[0m] \\033[77;1mSedang memproses ...\\033[0m\")\n sleep(1)\n usage()\nelif option.strip() in '& 2 lisensi'.split():\n print()\n os.system('nano LICENSE')\n print()\n restart()\nelif option.strip() in '# 3 info'.split():\n os.system('clear')\n print(example)\n os.system('toilet -f smslant ExtraKey')\n print(info)\n sleep(1)\n print()\n input('[ Tekan Enter ]')\n restart()\nelif option.strip() in '* 4 perbarui'.split():\n print()\n os.system('git pull origin master')\n print()\n input('\\033[0m[ \\033[32mTekan Enter \\033[0m]')\n restart()\nelif option.strip() in '- 0 keluar'.split():\n print(\"\\n\\033[0m[\\033[1;91m!\\033[0m] \\033[1;77mKeluar dari program!\")\n print()\n sys.exit(1)\nelse:\n print(\"\\n\\033[0m[=\\033[1;41;77m Pilihan Salah \\033[0m=]\")\n print()\n sleep(1)\n restart()\n","sub_path":"exstrakey.py","file_name":"exstrakey.py","file_ext":"py","file_size_in_byte":4581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"386606337","text":"# -*- coding: utf-8 -*- #\n# Copyright 2017 Google LLC. 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\"\"\"Flags for the compute instance groups managed commands.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import unicode_literals\n\nimport collections\n\nfrom googlecloudsdk.calliope import arg_parsers\nfrom googlecloudsdk.calliope import base\nfrom googlecloudsdk.calliope import exceptions\n\nDEFAULT_CREATE_OR_LIST_FORMAT = \"\"\"\\\n table(\n name,\n location():label=LOCATION,\n location_scope():label=SCOPE,\n baseInstanceName,\n size,\n targetSize,\n instanceTemplate.basename(),\n autoscaled\n )\n\"\"\"\n\n\ndef AddTypeArg(parser):\n parser.add_argument(\n '--type',\n choices={\n 'opportunistic': 'Do not proactively replace instances. Create new '\n 'instances and delete old on resizes of the group.',\n 'proactive': 'Replace instances proactively.',\n },\n default='proactive',\n category=base.COMMONLY_USED_FLAGS,\n help='Desired update type.')\n\n\ndef AddMaxSurgeArg(parser):\n parser.add_argument(\n '--max-surge',\n type=str,\n help=('Maximum additional number of instances that '\n 'can be created during the update process. '\n 'This can be a fixed number (e.g. 5) or '\n 'a percentage of size to the managed instance '\n 'group (e.g. 10%). Defaults to 0 if the managed '\n 'instance group has stateful configuration, or to '\n 'the number of zones in which it operates otherwise.'))\n\n\ndef AddMaxUnavailableArg(parser):\n parser.add_argument(\n '--max-unavailable',\n type=str,\n help=('Maximum number of instances that can be '\n 'unavailable during the update process. '\n 'This can be a fixed number (e.g. 5) or '\n 'a percentage of size to the managed instance '\n 'group (e.g. 10%). Defaults to the number of zones '\n 'in which the managed instance group operates.'))\n\n\ndef AddMinReadyArg(parser):\n parser.add_argument(\n '--min-ready',\n type=arg_parsers.Duration(lower_bound='0s'),\n help=('Minimum time for which a newly created instance '\n 'should be ready to be considered available. For example `10s` '\n 'for 10 seconds. See $ gcloud topic datetimes for information '\n 'on duration formats.'))\n\n\ndef AddReplacementMethodFlag(parser):\n parser.add_argument(\n '--replacement-method',\n choices={\n 'substitute':\n 'Delete old instances and create instances with new names.',\n 'recreate':\n 'Recreate instances and preserve the instance names. '\n 'The instance IDs and creation timestamps might change.',\n },\n help=\"Type of replacement method. Specifies what action will be taken \"\n \"to update instances. Defaults to ``recreate'' if the managed \"\n \"instance group has stateful configuration, or to ``substitute'' \"\n \"otherwise.\")\n\n\ndef AddForceArg(parser):\n parser.add_argument(\n '--force',\n action='store_true',\n help=('If set, accepts any original or new version '\n 'configurations without validation.'))\n\n\nINSTANCE_ACTION_CHOICES_WITHOUT_NONE = collections.OrderedDict([\n ('refresh', \"Apply the new configuration without stopping instances, \"\n \"if possible. For example, use ``refresh'' to apply changes \"\n \"that only affect metadata or additional disks.\"),\n ('restart', 'Apply the new configuration without replacing instances, '\n 'if possible. For example, stopping instances and starting '\n 'them again is sufficient to apply changes to machine type.'),\n ('replace', \"Replace old instances according to the \"\n \"``--replacement-method'' flag.\")\n])\n\n\ndef _CombineOrderedChoices(choices1, choices2):\n merged = collections.OrderedDict([])\n merged.update(choices1.items())\n merged.update(choices2.items())\n return merged\n\n\nINSTANCE_ACTION_CHOICES_WITH_NONE = _CombineOrderedChoices(\n {'none': 'No action'}, INSTANCE_ACTION_CHOICES_WITHOUT_NONE)\n\n\ndef AddMinimalActionArg(parser, choices_with_none=True, default=None):\n choices = (INSTANCE_ACTION_CHOICES_WITH_NONE if choices_with_none\n else INSTANCE_ACTION_CHOICES_WITHOUT_NONE)\n parser.add_argument(\n '--minimal-action',\n choices=choices,\n default=default,\n help='Perform at least this action on each instance while updating. '\n 'If the update requires a more disruptive action, then the more '\n 'disruptive action is performed.')\n\n\ndef AddMostDisruptiveActionArg(parser, choices_with_none=True, default=None):\n choices = (INSTANCE_ACTION_CHOICES_WITH_NONE if choices_with_none\n else INSTANCE_ACTION_CHOICES_WITHOUT_NONE)\n parser.add_argument(\n '--most-disruptive-allowed-action',\n choices=choices,\n default=default,\n help='Perform at most this action on each instance while updating. '\n 'If the update requires a more disruptive action than the one '\n 'specified here, then the update fails and no changes are made.')\n\n\ndef AddUpdateInstancesArgs(parser):\n \"\"\"Add args for the update-instances command.\"\"\"\n instance_selector_group = parser.add_group(required=True, mutex=True)\n instance_selector_group.add_argument(\n '--instances',\n type=arg_parsers.ArgList(min_length=1),\n metavar='INSTANCE',\n required=False,\n help='Names of instances to update.')\n instance_selector_group.add_argument(\n '--all-instances',\n required=False,\n action='store_true',\n help='Update all instances in the group.')\n AddMinimalActionArg(parser, True, 'none')\n AddMostDisruptiveActionArg(parser, True, 'replace')\n\n\ndef AddGracefulValidationArg(parser):\n help_text = \"\"\"Specifies whether the request should proceed even if the\n request includes instances that are not members of the group or that are\n already being deleted or abandoned. By default, if you omit this flag and\n such an instance is specified in the request, the operation fails. The\n operation always fails if the request contains a badly formatted instance\n name or a reference to an instance that exists in a zone or region other\n than the group's zone or region.\"\"\"\n parser.add_argument(\n '--skip-instances-on-validation-error',\n action='store_true',\n help=help_text)\n\n\ndef GetCommonPerInstanceCommandOutputFormat(with_validation_error=False):\n if with_validation_error:\n return \"\"\"\n table(project(),\n zone(),\n instanceName:label=INSTANCE,\n status,\n validationError:label=VALIDATION_ERROR)\"\"\"\n else:\n return \"\"\"\n table(project(),\n zone(),\n instanceName:label=INSTANCE,\n status)\"\"\"\n\n\nINSTANCE_REDISTRIBUTION_TYPES = ['NONE', 'PROACTIVE']\n\n\ndef AddMigInstanceRedistributionTypeFlag(parser):\n \"\"\"Add --instance-redistribution-type flag to the parser.\"\"\"\n parser.add_argument(\n '--instance-redistribution-type',\n metavar='TYPE',\n type=lambda x: x.upper(),\n choices=INSTANCE_REDISTRIBUTION_TYPES,\n help=\"\"\"\\\n Specifies the type of the instance redistribution policy. An instance\n redistribution type lets you enable or disable automatic instance\n redistribution across zones to meet the target distribution. The target\n distribution is a state of a regional managed instance group where all\n instances are spread out evenly across all target zones.\n\n An instance redistribution type can be specified only for a non-autoscaled\n regional managed instance group. By default it is set to PROACTIVE.\n\n The following types are available:\n\n * NONE - The managed instance group does not redistribute instances\n across zones.\n\n * PROACTIVE - The managed instance group proactively redistributes\n instances to meet its target distribution.\n \"\"\")\n\n\nDISTRIBUTION_POLICY_TARGET_SHAPE_CHOICES = {\n 'EVEN':\n 'The group schedules VM instance creation and deletion to achieve and '\n 'maintain an even number of managed instances across the selected '\n 'zones. The distribution is even when the number of managed instances '\n 'does not differ by more than 1 between any two zones. Recommended for'\n ' highly available serving workloads.',\n 'BALANCED':\n 'The group prioritizes acquisition of resources, scheduling VMs in '\n 'zones where resources are available while distributing VMs as evenly '\n 'as possible across selected zones to minimize the impact of zonal '\n 'failure. Recommended for highly available serving or batch workloads '\n 'that do not require autoscaling.',\n 'ANY': 'The group picks zones for creating VM instances to fulfill the '\n 'requested number of VMs within present resource constraints and to '\n 'maximize utilization of unused zonal reservations. Recommended for '\n 'batch workloads that do not require high availability.'\n}\n\n\ndef AddMigDistributionPolicyTargetShapeFlag(parser):\n \"\"\"Add --target-distribution-shape flag to the parser.\"\"\"\n help_text = \"\"\"\\\n Specifies how a regional managed instance group distributes its instances\n across zones within the region. The default shape is ``EVEN''.\n \"\"\"\n\n parser.add_argument(\n '--target-distribution-shape',\n metavar='SHAPE',\n type=lambda x: x.upper(),\n choices=DISTRIBUTION_POLICY_TARGET_SHAPE_CHOICES,\n help=help_text)\n\n\ndef ValidateRegionalMigFlagsUsage(args, regional_flags_dests, igm_ref):\n \"\"\"For zonal MIGs validate that user did not supply any RMIG-specific flags.\n\n Can be safely called from GA track for all flags, unknowns are ignored.\n\n Args:\n args: provided arguments.\n regional_flags_dests: list of RMIG-specific flag dests (names of the\n attributes used to store flag values in args).\n igm_ref: resource reference of the target IGM.\n \"\"\"\n if igm_ref.Collection() == 'compute.regionInstanceGroupManagers':\n return\n for dest in regional_flags_dests:\n if args.IsKnownAndSpecified(dest):\n flag_name = args.GetFlag(dest)\n error_message = ('Flag %s may be specified for regional managed instance '\n 'groups only.') % flag_name\n raise exceptions.InvalidArgumentException(\n parameter_name=flag_name, message=error_message)\n","sub_path":"google-cloud-sdk/lib/googlecloudsdk/command_lib/compute/instance_groups/managed/flags.py","file_name":"flags.py","file_ext":"py","file_size_in_byte":11080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"439440787","text":"\n\n#calss header\nclass _NICE():\n\tdef __init__(self,): \n\t\tself.name = \"NICE\"\n\t\tself.definitions = [u'pleasant, enjoyable, or satisfactory: ', u'pleasantly: ', u'kind, friendly, or polite: ', u'based on very slight differences: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'adjectives'\n\n\n\tdef run(self, obj1, obj2):\n\t\tself.jsondata[obj2] = {}\n\t\tself.jsondata[obj2]['properties'] = self.name.lower()\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/adjectives/_nice.py","file_name":"_nice.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"564218787","text":"import random\nimport argparse\nimport numpy as np\nimport pandas as pd\nimport time\n# from autoencoder import Autoencoder\nimport math \n\nimport LoadData as data\nfrom GNE import GNE\nimport pickle\n# Set random seeds\nfrom evaluation import evaluate_MAP\n\nSEED = 2016\nrandom.seed(SEED)\nnp.random.seed(SEED)\n\ndef parse_args():\n parser = argparse.ArgumentParser(description=\"Run GNE.\")\n parser.add_argument('--organism', nargs='?', default='ecoli', help='Input data path')\n parser.add_argument('--id_dim', type=int, default=64, help='Dimension for id_part.')\n parser.add_argument('--epoch', type=int, default=20, help='Number of epochs.')\n parser.add_argument('--n_neg_samples', type=int, default=64, help='Number of negative samples.')\n parser.add_argument('--attr_dim', type=int, default=64, help='Dimension for attr_part.')\n parser.add_argument('--batch_size', type=int, default=128, help='Batch size for training GNE.')\n parser.add_argument('--representation_size', type=int, default=128, help='Dimension of representation vector')\n parser.add_argument('--learning_rate', type=float, default=0.005, help='Learning rate')\n parser.add_argument('--hidden_layers', type=float, default=1, help='Number of hidden layers for joint transformation')\n return parser.parse_args()\n\n#################### Util functions ####################\n\n\ndef run_GNE(path, data, args):\n # alpha is a parameter that adjusts the effect of attributes in the model\n if args.organism == \"ecoli\":\n a = 1\n elif args.organism == \"yeast\":\n a = 0.8\n for alpha in [0.0, a]:\n t1 = time.time()\n model = GNE(path, data, id_embedding_size=args.id_dim, attr_embedding_size=args.attr_dim, \\\n batch_size=args.batch_size, alpha=alpha, epoch = args.epoch, representation_size=args.representation_size, learning_rate=args.learning_rate)\n embeddings, auroc = model.train( )\n t2 = time.time()\n print(\"time taken: \" + str(t2 - t1))\n return embeddings\n\nif __name__ == '__main__':\n args = parse_args()\n organism = args.organism\n path = './data/' + organism +'/'\n print(\"data_path: \", path)\n if args.organism == \"ecoli\":\n organism_id = 3\n elif args.organism == \"yeast\":\n organism_id = 4\n\n test_size = 0.2\n print(\"Test size: \", test_size)\n Data = data.LoadData( path , SEED, test_size, organism_id)\n data_file = open('output/ecoli/processedData_doublelinked.pkl', 'wb')\n pickle.dump(Data, data_file)\n data_file.close()\n\n # # load saved data file for 80/10/10 train/test/validation split\n # print(\"Preprocessed file: output/\"+ organism + \"/processedData_doublelinked.pkl\")\n # data_file = open('output/'+ organism + '/processedData_doublelinked.pkl', 'rb')\n # Data = pickle.load(data_file)\n # data_file.close()\n\n print(\"Total number of nodes: \", Data.id_N)\n print(\"Total number of attributes: \", Data.attr_M)\n\n k = args.representation_size\n id = math.sqrt(Data.id_N)\n attr = math.sqrt(Data.attr_M)\n\n x = args.hidden_layers * float(k)/float(id + attr)\n args.id_dim = round(id * x)\n args.attr_dim = round(attr * x)\n\n print(\"Total training links: \", len(Data.links))\n print(\"Total epoch: \", args.epoch)\n\n print('id_dim :', args.id_dim)\n print('attr_dim :', args.attr_dim)\n\n embeddings = run_GNE(path, Data, args)\n\n\n","sub_path":"GNE_runner.py","file_name":"GNE_runner.py","file_ext":"py","file_size_in_byte":3565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"231533250","text":"import yaml\nimport sys\nimport os\n\nfrom util.config import create_config\nfrom dotenv import load_dotenv\nfrom discord.ext.commands import Bot\n\nload_dotenv()\ncreate_config()\n\nwith open(\"cfg/config.yml\", 'r') as f:\n\n config_cfg = yaml.safe_load(f)\n\nwith open(\"cfg/cogs.yml\", 'r') as f:\n\n cog_cfg = yaml.safe_load(f)\n\n# Add cogs from cogs.yml file\ninitial_extensions = []\nfor c in cog_cfg:\n\n if cog_cfg[c]:\n\n initial_extensions.append(c)\n\nclient = Bot(command_prefix=config_cfg['Prefix'])\n\n# loading extensions/cogs for commands\nif __name__ == '__main__':\n\n for extension in initial_extensions:\n\n client.load_extension(extension)\n\n\n@client.event\nasync def on_ready():\n print(f'Logged in as {client.user.name}')\n\nclient.run(os.getenv('DISCORD_TOKEN'))\n","sub_path":"Run.py","file_name":"Run.py","file_ext":"py","file_size_in_byte":775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"632726633","text":"import socket\n\nclass Conn(object):\n\tdef __init__(self):\n\t\tself.s = None\n\t\t\n\tdef conn(self, url, req):\n\t\tself.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\n\t\tself.s.connect((url,80))\n\n\t\tself.s.send(req)\n\n\tdef close(self):\n\t\tself.s.close()\n\t\n\tdef recv(self):\n\t\treturn self.s.recv(1024)\n\nbaidu_url = 'www.baidu.com'\nbaidu_req = b'GET / HTTP/1.1\\r\\nHost:www.baidu.com\\r\\nConnection: keep-alive\\r\\n\\r\\n'\n\nsina_url = 'www.sina.com.cn'\nsina_req = b'GET / HTTP/1.1\\r\\nHost: www.sina.com.cn\\r\\nConnection: close\\r\\n\\r\\n'\n\nbaidu = Conn()\nbaidu.conn(baidu_url, baidu_req)\nsina = Conn()\nsina.conn(sina_url, sina_req)\ndef fun(s):\n\tbuffer = []\n\twhile True:\n\t\td = s.recv()\n\t\tif d:\n\t\t\t\n\t\t\tbuffer.append(d)\n\t\telse:\n\t\t\tbreak\n\ts.close()\n\treturn buffer\n\t\nheader, html = b''.join(fun(baidu)).split(b'\\r\\n\\r\\n',1)\nprint(header.decode('utf-8'))\n# print('sina\\n------------\\n--------------\\n-----------------\\n')\n# header, html = b''.join(fun(sina)).split(b'\\r\\n\\r\\n',1)\n# print(header.decode('utf-8'))\n# with open('sina.html','wb') as f:\n\t# f.write(html)","sub_path":"PyCode/web.py","file_name":"web.py","file_ext":"py","file_size_in_byte":1040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"654083687","text":"from context_processors import site_settings_processor\nfrom django.core.mail import send_mail, EmailMessage\nimport datetime, os\n\nfrom contact.forms import ContactForm\n\nis_production = os.environ.get('IS_PRODUCTION')\n\ndef admin_name():\n return site_settings_processor(None)['admin_name']\n\ndef ContactFormProcessor(request, context_dictionary):\n\tcontext_dictionary['first_name_placeholder'] = 'First Name'\n\tcontext_dictionary['email_placeholder'] = 'Email Address'\n\tcontext_dictionary['phone_placeholder'] = 'Phone Number (optional)'\n\tcontext_dictionary['message_placeholder'] = 'Extra Information (optional)'\n\tcontext_dictionary['first_name_value']=context_dictionary['email_value']=context_dictionary['phone_value']=context_dictionary['message_value'] = ''\n\tcontext_dictionary['error_fields'] = []\n\tif request.method == 'POST':\n\t\tif 'contact' in request.POST:\n\t\t\t# create a form instance and populate it with data from the request:\n\t\t\tcontact_form = ContactForm(request.POST)\n\t\t\t# check whether it's valid:\n\t\t\tif contact_form.is_valid():\n\t\t\t\tfirst_name = contact_form.cleaned_data['first_name']\n\t\t\t\tphone = contact_form.cleaned_data['phone']\n\t\t\t\tsender = contact_form.cleaned_data['email']\n\t\t\t\tinquiry_type = contact_form.cleaned_data['inquiry_type']\n\t\t\t\tmessage_body = contact_form.cleaned_data['message']\n\t\t\t\trecipients = [site_settings_processor(request)['site_email'],]\n\t\t\t\t# from_email = site_settings_processor(request)['site_email']\n\t\t\t\tfrom_email = sender\n\t\t\t\theader = 'First name,' + 'CF[Inquiry Type],' + 'Main Phone,' + 'Email,' + 'CF[Message]\\n'\n\t\t\t\t# fullemail = header + first_name + \",\" + ' - '.join(inquiry_type) + \",\" + phone + \",\" + sender + \",\" + message_body\n\t\t\t\tfullemail = first_name + \"\\n\" + ' - '.join(inquiry_type) + \"\\n\" + phone + \"\\n\" + sender + \"\\n\" + message_body\n\t\t\t\ttime_stamp = str(datetime.datetime.now())\n\t\t\t\t# email_object = EmailMessage(subject = 'Website Contact Form', body = message_body, from_email = from_email, to = recipients, attachments = [(time_stamp+'.txt',fullemail,),])\n\t\t\t\t# email_object = EmailMessage(subject = 'Website Contact Form', body = fullemail, from_email = from_email, to = recipients, attachments = [(time_stamp+'.txt',fullemail,),])\n\t\t\t\temail_object = EmailMessage(subject = 'New Website Contact', body = fullemail, from_email = from_email, to = recipients)\n\t\t\t\temail_object.send()\n\t\t\t\tcontext_dictionary['first_name'] = first_name\n\t\t\telse:\n\t\t\t\tcontext_dictionary['contact_form'] = contact_form\n\t\t\t\tfor field in contact_form:\n\t\t\t\t\tcontext_dictionary[field.name + \"_value\"] = contact_form[field.name].value\n\t\t\t\tfor field in contact_form.errors:\n\t\t\t\t\terror_message = contact_form.errors[field][0]\n\t\t\t\t\tcontext_dictionary[field + \"_placeholder\"] = error_message\n\t\t\t\t\tcontext_dictionary['error_fields'].append(field)\n\t\telse:\n\t\t\tpass\n\telse:\n\t\tcontact_form = ContactForm()\n\t\tcontext_dictionary['contact_form'] = contact_form\n\nfrom django.db.models import ImageField\nfrom django.forms import forms\nfrom django.template.defaultfilters import filesizeformat\nfrom django.utils.translation import ugettext_lazy as _\n\nclass ContentTypeRestrictedImageField(ImageField):\n\t\"\"\"\n\tSame as ImageField, but you can specify:\n\t* content_types - list containing allowed content_types. Example: ['application/pdf', 'image/jpeg']\n\t* max_upload_size - a number indicating the maximum file size allowed for upload.\n\t2.5MB - 2621440\n\t5MB - 5242880\n\t10MB - 10485760\n\t20MB - 20971520\n\t50MB - 5242880\n\t100MB 104857600\n\t250MB - 214958080\n\t500MB - 429916160\n\t\"\"\"\n\tdef __init__(self, *args, **kwargs):\n\t\t# self.content_types = kwargs.pop(\"content_types\")\n\t\tself.max_upload_size = kwargs.pop(\"max_upload_size\")\n\t\tsuper(ContentTypeRestrictedImageField, self).__init__(*args, **kwargs)\n\tdef clean(self, *args, **kwargs): \n\t\tdata = super(ContentTypeRestrictedImageField, self).clean(*args, **kwargs)\n\t\tfile = data.file\n\t\ttry:\n\t\t\t# content_type = file.content_type\n\t\t\t# if content_type in self.content_types:\n\t\t\t\tif file._size > self.max_upload_size:\n\t\t\t\t\traise forms.ValidationError(_('Please keep filesize under %s. Current filesize %s') % (filesizeformat(self.max_upload_size), filesizeformat(file._size)))\n\t\t\t# else:\n\t\t\t\t# raise forms.ValidationError(_('Filetype not supported.'))\n\t\texcept AttributeError:\n\t\t\tpass \n\n\t\treturn data\n\nfrom south.modelsinspector import add_introspection_rules\nadd_introspection_rules([\n\t(\n\t\t[ContentTypeRestrictedImageField], # Class(es) these apply to\n\t\t[], # Positional arguments (not used)\n\t\t{ # Keyword argument\n\t\t\t\"max_upload_size\": [\"max_upload_size\", {}],\n\t\t},\n\t),\n\t], [\"^utilities\\.ContentTypeRestrictedImageField\"])\n","sub_path":"utilities.py","file_name":"utilities.py","file_ext":"py","file_size_in_byte":4617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"438351824","text":"import unittest\nimport os\nimport time\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\n\nfrom app import app, db\nfrom app.models import Test, Request, SystemMetric, TestSchema\nfrom flask import Flask\n\nimport datetime\n\n#########################\n# Fields Setup #\n#########################\n\ndb_uri = 'postgresql://daltonteague@localhost/loadtest_db'\n\ntest_id = 1\ntest_config = \"Test Frontend Config \"\ntest_start = datetime.datetime.now()\ntest_end = datetime.datetime.now()\nnum_workers = 50000\n\nreq_time = test_end\nreq_type = \"request type\"\nreq_length = 200\nres_type = \"response type\"\nres_length = 300\nduration = 500\n\nmet_time = test_end\nmet_type = \"metric type\"\nmet_val = 150\n\n\nclass TestFrontend(unittest.TestCase):\n\n \"\"\"\n These tests use a Selenium driver to simulate user\n interaction with the server UI. This is unfinished\n until certain UI elements are more polished.\n \"\"\"\n\n #########################\n # Test Environment Setup #\n #########################\n\n def create_app(self):\n # pass in test configurations\n config_name = 'testing'\n app = create_app(config_name)\n app.config.update(\n SQLALCHEMY_DATABASE_URI=db_uri\n )\n return app\n\n def setUp(self):\n db.create_all()\n db.session.commit()\n chrome_options = Options()\n chrome_options.add_argument(\"--headless\")\n chrome_direc = f\"{os.getcwd()}/tests/chromedriver\"\n\n self.driver = webdriver.Chrome(\n chrome_options=chrome_options,\n executable_path=chrome_direc\n )\n self.driver.get('http://localhost:5000/tests/')\n\n def tearDown(self):\n\n db.session.remove()\n\n #########################\n # Test Start #\n #########################\n\n def test_1_view_test(self):\n \"\"\"\n Test visiting the /tests page by adding a test and\n asserting that it shows up in the table when the page\n is refreshed.\n \"\"\"\n\n print(\"creating test for frontend\")\n count = Test.query.count() + 1\n test = Test(\n config=test_config + str(count),\n start=test_start,\n end=test_end,\n workers=num_workers)\n\n db.session.add(test)\n db.session.commit()\n\n time.sleep(1)\n self.driver.refresh()\n # get_config = self.driver.find_element_by_id(str(count - 1) + \"-cfg\")\n # self.assertEqual(\n # get_config.text,\n # 'Test Frontend Config ' + str(count)\n # )\n\n def test_2_view_summary(self):\n \"\"\"\n Test viewing a specific test and its summary statistics\n \"\"\"\n\n count = Test.query.count() + 1\n print(str(count))\n test = Test(\n config=test_config + str(count),\n start=test_start,\n end=test_end,\n workers=num_workers)\n\n request = Request(\n test_id=count,\n time_sent=req_time,\n request_type=req_type,\n request_length=req_length,\n response_type=res_type,\n response_length=res_length,\n duration=duration)\n\n metric = SystemMetric(\n test_id=count,\n time=met_time,\n metric_type=met_type,\n metric_value=met_val)\n\n db.session.add(test)\n db.session.add(request)\n db.session.add(metric)\n db.session.commit()\n\n self.driver.get('http://localhost:5000/tests/' + str(count) + '/')\n self.driver.refresh()\n\n # TODO: requests and metrics aren't showing up for some reason\n # by time page is loaded\n\n # get_req = self.driver.execute_script(\n # 'return document.getElementById(\"req1\").text'\n # )\n # get_met = self.driver.execute_script(\n # 'return document.getElementById(\"met1\").text'\n # )\n # self.assertEqual(get_req, 'Request ID: ' + str(count))\n # self.assertEqual(get_met, 'Metric ID: ' + str(count))\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"nile_server/tests/test_frontend.py","file_name":"test_frontend.py","file_ext":"py","file_size_in_byte":4081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"454086548","text":"import os\nimport json\nimport re\nimport pandas as pd\n\ndef normalize_string_format(line):\n with open(os.path.join(\"data\", \"regex_string_formats.json\"), 'r') as file_content:\n string_formats_json = json.loads(file_content.read())\n for regex in string_formats_json:\n findings = re.findall(regex, line)\n if len(findings) > 0:\n for finding in findings:\n if \"{str_format}\" not in finding:\n line = line.replace(finding, \"{str_format}\")\n return line\n\n\ndef modify_and_output_histogram(input_histogram, file_name):\n output_histogram = sorted(input_histogram.items(), key=lambda kv: kv[1])\n output_histogram.reverse()\n\n df = pd.DataFrame(columns=[\"value\", \"appearances\"])\n\n for index, item in enumerate(output_histogram):\n if item[1] > 5: # delete words with less then 5 apperances\n df.loc[index] = [item[0], item[1]]\n\n df.to_csv(os.path.join(\"outputs\", file_name), index=False)\n\n\ndef build_log_string_histogram():\n word_histogram = {}\n line_histogram = {}\n with open(os.path.join(\"data\", \"logs_strings.txt\"), 'r') as file_content:\n for line in file_content:\n line = normalize_string_format(line)\n line = line.strip().lower().replace(' ', ' ')\n if len(line) > 200:\n continue\n words = line.split(' ')\n for word in words:\n if len(word) > 1: # remove single char words\n if word in word_histogram:\n word_histogram[word] += 1\n else:\n word_histogram[word] = 1\n if len(line) > 1: # remove single char lines\n if line in line_histogram:\n line_histogram[line] += 1\n else:\n line_histogram[line] = 1\n\n modify_and_output_histogram(word_histogram, file_name=\"logs_strings_word_histogram.csv\")\n modify_and_output_histogram(line_histogram, file_name=\"logs_strings_line_histogram.csv\")\n","sub_path":"libs/build_log_string_histogram.py","file_name":"build_log_string_histogram.py","file_ext":"py","file_size_in_byte":2039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"589468371","text":"\n'''\nCreated on Oct 20, 2015\n\n@author: Jose\n'''\n\nimport pyperclip\nimport pyautogui\nimport time\n\ndef buscar_boton_go():\n msg = ''\n pyautogui.PAUSE = 0.5\n pyautogui.FAILSAFE = False\n pyperclip.copy('')\n \n dondeEstaElBoton = pyautogui.locateOnScreen('go-button.png')\n if dondeEstaElBoton is None:\n msg = 'El boton de GO no fue encontrado'\n return (False, msg)\n \n else:\n botonPos = list(dondeEstaElBoton)\n #print botonPos\n \n centroBoton = pyautogui.center(botonPos) \n #print centroBoton\n \n pyautogui.moveTo(centroBoton)\n pyautogui.click()\n \n return (True, msg)\n\n#botonEncontrado = buscar_boton_go()\n#print botonEncontrado\n\n\n\n","sub_path":"buscar-boton-go.py","file_name":"buscar-boton-go.py","file_ext":"py","file_size_in_byte":713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"384968824","text":"import numpy as np\nimport cv2 \n\nimg1 = cv2.imread(\"assets/Chess_Board1.png\")\nimg = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)\n\nN = 100\ncorners = cv2.goodFeaturesToTrack(img,N,0.2,10)\ncorners = np.int0(corners)\n\nfor corner in corners:\n x,y = corner.ravel()\n cv2.circle(img1,(x,y),5,(255,0,0),-1)\n\nfor i in range(len(corners)): \n for j in range(len(corners)): \n corner1 = tuple(corners[i][0])\n corner2 = tuple(corners[j][0])\n #color = np.random.randint(0,255,size=3)\n cv2.line(img1,corner1,corner2,(0,0,0),1)\n\ncv2.imshow(\"frame\",img1)\ncv2.waitKey(0)\ncv2.destroyAllWindows()","sub_path":"corner_detection.py","file_name":"corner_detection.py","file_ext":"py","file_size_in_byte":604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"633936999","text":"import numpy as np\nimport pandas as pd\nimport statsmodels.formula.api as smf\nfrom common_func import *\nimport rospy\n\n# import rpy2\n# import rpy2.robjects as robjects\n# from rpy2.robjects.packages import importr\n# from rpy2.robjects import FloatVector, IntVector, StrVector\n\n# # import R's \"base\", \"utils\", \"stats\", and \"nlme\" packages\n# base = importr('base')\n# #utils = importr('utils')\n# #stats = importr('stats')\n# nlme = importr('nlme') # library('nlme')\n\ndef chopping(database,host_msg,RARE_MAX):\n tmp = WCStoVCS(host_msg.world_x, host_msg.world_y, host_msg.heading, database[['world_x']], database[['world_y']])\n idx = np.where(tmp[:,0] < 0)[0]\n drop_idx = np.where(np.sqrt(np.array(tmp[idx,0])**2+np.array(tmp[idx,1])**2) > RARE_MAX)[0]\n idx2 = np.where(tmp[:,0] > 0)[0]\n drop_idx2 = np.where(np.sqrt(np.array(tmp[idx2,0])**2+np.array(tmp[idx2,1])**2) > 250)[0]\n\n database = database.drop(database.index[idx[np.concatenate((drop_idx,drop_idx2))]])\n\n return(database)\n\ndef fit_road_shape_model(database):\n md = smf.mixedlm(formula = \"vcs_y ~ 1+vcs_x+I(vcs_x**2)+I(vcs_x**3)\", data=database, groups=database[\"ID\"])\n road_shape_model = md.fit()\n\n return(road_shape_model)\n\ndef estimate_road_shape(road_shape_model, database):\n # get unique trail vcs x position\n vcs_x = np.unique(database[['vcs_x']].values)\n \n # create a DataFrame\n newx = pd.DataFrame({'vcs_x':vcs_x})\n \n # predict the vcs y position by road shape model\n vcs_y = road_shape_model.predict(newx).values\n\n # combine the result and store in a list\n est_road_shape = {\"vcs_x\": vcs_x, \"vcs_y\": vcs_y}\n\n return(est_road_shape)\n\n# def fit_road_shape_model(database):\n# vid = StrVector(database[['ID']].values)\n# vcs_x = FloatVector(database[['vcs_x']].values)\n# vcs_y = FloatVector(database[['vcs_y']].values)\n\n# # assign data to R data.frame\n# df = {'VID':vid, 'VCS_X': vcs_x, 'VCS_Y': vcs_y}\n# Trails = robjects.DataFrame(df)\n\n# # fixs <- formul(VCS_Y ~ poly(VCS_X,3))\n# fixs = robjects.Formula('VCS_Y ~ poly(VCS_X,3)')\n\n# # ranefs <- formula(~1|VID)\n# ranefs = robjects.Formula('~1|VID')\n\n# # fit_road_shape <- lme(fixed=fixs, data=Trails, random=ranefs)\n# road_shape_model = nlme.lme(fixed=fixs, data=Trails, random=ranefs)\n\n# return(road_shape_model)\n\n\n# def estimate_road_shape(road_shape_model, database):\n# # get unique trail vcs x position\n# vcs_x = np.unique(database[['vcs_x']].values)\n# \n# # convert vcs x into R format\n# vcs_x_R = FloatVector(vcs_x)\n# \n# # create an R DataFrame\n# df = {'VCS_X':vcs_x_R}\n# newx = robjects.DataFrame(df)\n# \n# # predict the vcs y position by road shape model\n# vcs_y = robjects.r.predict(road_shape_model, newdata=newx, level=0)\n# \n# # combine the result and store in a list\n# pred_road_shape = {\"vcs_x\": vcs_x, \"vcs_y\": vcs_y}\n\n# return(pred_road_shape)\n","sub_path":"packages/ros_mixedmodel/scripts/trail_func.py","file_name":"trail_func.py","file_ext":"py","file_size_in_byte":3022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"66405756","text":"#!/usr/bin/env python3\r\n# Name: Andrew Zarzar (azarzar)\r\n# Group Members: None\r\n\r\nclass ProteinParam :\r\n \r\n '''\r\n This program is designed to take a protein sequence as an input. The protein sequence must be represented by single-letter \r\n amino acids. Many physical-chemical properties of the protein sequence will be calculated. The protein sequence will be \r\n read, and the program will print out:\r\n - The number of amino acids\r\n - The molecular weight\r\n - The molar extinction coefficient\r\n - The mass extinction coefficient\r\n - The theoretical isoelectic point\r\n - The amino acid composition\r\n \r\n Input: amino acid sequence (in one letter code)\r\n Output: The various physical-chemical properties outlined above. (Values will be labeled)\r\n '''\r\n \r\n# These tables are for calculating:\r\n\r\n # molecular weight (aa2mw)\r\n aa2mw = {\r\n 'A': 89.093, 'G': 75.067, 'M': 149.211, 'S': 105.093, 'C': 121.158,\r\n 'H': 155.155, 'N': 132.118, 'T': 119.119, 'D': 133.103, 'I': 131.173,\r\n 'P': 115.131, 'V': 117.146, 'E': 147.129, 'K': 146.188, 'Q': 146.145,\r\n 'W': 204.225, 'F': 165.189, 'L': 131.173, 'R': 174.201, 'Y': 181.189\r\n }\r\n # mol. weight of H2O (mwH2O)\r\n mwH2O = 18.015\r\n # absorbance at 280 nm (aa2abs280)\r\n aa2abs280= {'Y':1490, 'W': 5500, 'C': 125}\r\n # pKa of positively charged Amino Acids (aa2chargePos)\r\n aa2chargePos = {'K': 10.5, 'R':12.4, 'H':6}\r\n # pKa of negatively charged Amino acids (aa2chargeNeg)\r\n aa2chargeNeg = {'D': 3.86, 'E': 4.25, 'C': 8.33, 'Y': 10}\r\n # and the constants aaNterm and aaCterm for pKa of the respective terminis\r\n aaNterm = 9.69\r\n aaCterm = 2.34\r\n\r\n # becomes a dictionary of the number of each amino acid in the input after aaComposition method runs\r\n dictionary = {}\r\n # stringL becomes a string of the cleaned amino acid sequence after aaCount method runs\r\n stringL = \"\"\r\n \r\n \"\"\"Provides ProtienParam with the protein attribute. Passes protein to rest of class\"\"\"\r\n def __init__ (self, protein):\r\n self.protein = protein\r\n \r\n \"\"\"aaCount serves two functions. 1. to count the number of amino acids 2. to create a cleaned amino acid string\r\n It returns the number of amino acids, but it also cleans a protein list and joins it into a string at the same time.\r\n \"\"\" \r\n def aaCount (self):\r\n # list of allowed aa characters to count.\r\n allowedList = [\"A\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\", \"L\", \"K\", \"M\", \"N\", \"P\", \"Q\", \"R\", \"S\", \"T\", \"V\", \"Y\", \"W\"]\r\n protein = self.protein\r\n protein = protein.upper() # makes input letters uppercase in case of lower case input.\r\n l = list(protein) # creates a list of the uppercased protein input.\r\n count = 0\r\n aa = 0\r\n while count < len(protein): # loops through the whole protein sequence.\r\n c = l[count]\r\n if c not in allowedList: # if the character at that index in the list isn't an allowed amino acid. It is deleted.\r\n l[count] = \"\"\r\n count += 1\r\n else:\r\n aa+= 1 # amino acid count is increased by 1 if character at that index is in the list\r\n count += 1\r\n \r\n global stringL\r\n stringL = \"\".join(l) # joins the cleaned protein list into a string\r\n return aa # the amino acid count is returned\r\n \r\n \"\"\"pI uses binary search to find the isoelectric point. The precision can be set as a paramater, and affects the precision\r\n of the pH output to the decimal point. Each search calls the local method _charge_, which returns the net charge. The\r\n search algorithm tests a new pH in the _charge_ method until a charge of ~ 0 is returned.\r\n \"\"\"\r\n def pI (self, pP): \r\n first = 0 # possible pH's from 0 to 14\r\n last = (14)\r\n done = False # if true, the while loop below will break. (A suitable pH has been found, or the data has been exhausted)\r\n precision = pP # Sets precision to have a charge within ?+1 decimal places of zero and a pH accurate to ? decimal places\r\n p = float(\"0.\"+((precision)*\"0\")+(\"1\")) # translates the users wanted precision to something that can be used\r\n # if precision is 2, p will equal 0.001, which will result in a pH accurate to 0.01 after the search is completed\r\n while first <=last and not done:\r\n mid = (first + last)/2\r\n x = self._charge_(mid) # tests potential pH for a zero charge using _charge_ method\r\n if x == 0 or (x

-p): # if the pH results in a charge sufficiently close to zero (dependent on precision), loop is broken\r\n done = True\r\n elif x < 0:\r\n last = mid - p #if charge is less than 0, then potential pH must be more acidic. Changes test window.\r\n else: \r\n first = mid + p # if charge is greater than 0, then potential pH must be more basic. Changes test window.\r\n return mid\r\n \r\n \r\n \r\n \"\"\"\r\n **Old, Less efficient pI method. This method tests every possible pH range with a precision of 0.01. Testing potentially\r\n all 14,000 possible pH values. \r\n \r\n def pI (self):\r\n first = 0\r\n last = (14000)\r\n done = False\r\n\r\n while first <=last and not done:\r\n x = self._charge_(first/1000)\r\n if x == 0 or (x<0.01 and x>-0.01):\r\n done = True\r\n else: \r\n first += 1\r\n \r\n return first/1000\r\n \"\"\" \r\n \r\n \r\n \r\n \"\"\"aaCompositon tests each value of the allowed amino list against the cleaned protein input string.\r\n It loops through the list, and counts the instance of each amino acid in the list that are found in the string\r\n It updates the dictionary outputDict with the amino acid, and the count. Creates a globally available copy of the dictionary\r\n \"\"\"\r\n def aaComposition (self) :\r\n #list of allowed aa characters\r\n allowedList = [\"A\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\", \"L\", \"K\", \"M\", \"N\", \"P\", \"Q\", \"R\", \"S\", \"T\", \"V\", \"Y\", \"W\"]\r\n outputDict = {} # new Dictionary. Used to hold the number of each amino acid.\r\n count = 0\r\n while count < len(allowedList): #searches the cleaned string from aaCount for the number of every possible amino acid.\r\n index = allowedList[count] #loops through each character in the allowedList\r\n x = {index: stringL.count(index)} #sets up new dictionary entry with an amino acid key, and the number of it in the cleaned string\r\n outputDict.update(x) # updates the dictionary with entry x\r\n count+=1 # proceeds to the next allowed aa character\r\n global dictionary\r\n dictionary = outputDict #creates a copy of outputDict for use outside of the method.\r\n return (outputDict)\r\n \r\n \"\"\"_charge_ is a private method that is used by the method pI. It returns the net charge of the protein at a specific pH\r\n and takes a paramater for a pH value. The charge is calculated using an equation that factors the N and C termini, the pH,\r\n the number of charged and negative amino acids, and their respective pKas.\r\n \"\"\"\r\n def _charge_ (self, p):\r\n pH = p\r\n pos = [\"K\", \"R\", \"H\"] # list of positive aa\r\n neg = [\"D\", \"E\", \"C\", \"Y\"] # list of negative aa\r\n count1 = 0\r\n charge = 0\r\n while count1 < len(pos): # this loop calculates the positive part of the equation (not including the N terminus)\r\n index = pos[count1]\r\n x = 10**ProteinParam.aa2chargePos.get(index) # = 10 to the power of the aa pKa\r\n y = 10**pH # = 10 to the power of the pH\r\n z = dictionary.get(index) # the number of the respective aa\r\n charge +=((x/(x+y))*z) # equation that adds each iteration of the equation for each charged amino acid\r\n count1 += 1\r\n x = 10**ProteinParam.aaNterm\r\n y = 10**pH\r\n charge += (x/(x+y)) # used to add the N-terimus to the equation seperatly. It would interfere if implemented the same way above.\r\n \r\n count2 = 0 \r\n while count2 < len(neg):# this loop calculates the negative aa part of the equation (not including the C-terminus)\r\n index = neg[count2]\r\n x = 10**ProteinParam.aa2chargeNeg.get(index)\r\n y = 10**pH\r\n charge -= (y/(x+y))*dictionary.get(index) # equation differs slightly and is instead subtracted from the charge at each iteration\r\n count2 += 1\r\n x = 10**ProteinParam.aaCterm\r\n y = 10**pH\r\n charge -= (y/(x+y)) # seperate equation for the C-terminus\r\n return charge\r\n \r\n \"\"\"molarExtinction accepts a cystine paramater. It calculates the extintion coefficient of the protein by using the\r\n Gill and von Hippel method. It sorts throught the number of tyrosines, tryptophans, and cysteines.\r\n \"\"\"\r\n def molarExtinction (self, cys):\r\n cystine = cys\r\n x = 0\r\n if cystine is not False: cystine = True # under oxidizing conditions\r\n if cystine is False: x = 1 # if under reducing conditions, cystine doesn't form and cysteine doesn't contribute.\r\n allowedList = [\"Y\", \"W\", \"C\"] # amino acids required for calculations\r\n count = 0\r\n coeff = 0\r\n while count < (len(allowedList)-x): # finds the data associated with each amino acid, skips cysteine if cystine is False\r\n index = allowedList[count]\r\n coeff += (ProteinParam.aa2abs280.get(index)*dictionary.get(index)) # This adds up the number of each aa multiplied by their respective extintion coefficient\r\n count+=1\r\n return coeff # returns the protein extintion coefficient\r\n \r\n \"\"\"massExtinction returns the mass extinction coeffectient by using the molar extinction coeffeccient and dividing\r\n it by the molecular weight of the protein. It also has a cystine paramater. \r\n \"\"\"\r\n def massExtinction (self,cys):\r\n cystine = cys\r\n myMW = self.molecularWeight() # gets molecular weight\r\n return self.molarExtinction(cystine) / myMW if myMW else 0.0 # calls for extinction coefficient and divides it by the molecular weight.\r\n \r\n \"\"\"molecularWeight goes through the allowed list of amino acids, and gets the respective value of the molecular weight and the\r\n number of the amino acid in the input from 2 different dictionaries. It multiplies them together and adds up the weights\r\n for each amino acid to get the total molecular weight.\r\n \"\"\"\r\n def molecularWeight (self):\r\n # list of allowed aa characters\r\n allowedList = [\"A\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\", \"L\", \"K\", \"M\", \"N\", \"P\", \"Q\", \"R\", \"S\", \"T\", \"V\", \"Y\", \"W\"]\r\n count = 0\r\n weight = 0\r\n while count < len(allowedList):# loops through each amino acid in the allowed list.\r\n index = allowedList[count]\r\n weight += (ProteinParam.aa2mw.get(index)*dictionary.get(index)) # multiplies the number of each aa, and its MW.\r\n count+=1\r\n weight = weight - ((len(stringL)-1)*18.01528) # the adjusted weight subtracts the weight of the waters that are released in peptide bond formation\r\n return weight\r\n\r\n# Please do not modify any of the following. This will produce a standard output that can be parsed\r\n\r\n\"\"\"The main method creates a ProteinParam object using the input, and prints the useful output by calling the\r\ncorrect methods. The request for input loops until the program is terminated. \"\"\" \r\nimport sys\r\ndef main():\r\n inString = input('protein sequence?')\r\n while inString :\r\n myParamMaker = ProteinParam(inString)\r\n myAAnumber = myParamMaker.aaCount()\r\n myAAcomposition = myParamMaker.aaComposition() # was moved above since some of the methods below rely on its outputs in order to function \r\n print (\"Number of Amino Acids: {aaNum}\".format(aaNum = myAAnumber))\r\n print (\"Molecular Weight: {:.1f}\".format(myParamMaker.molecularWeight()))\r\n print (\"molar Extinction coefficient: {:.2f}\".format(myParamMaker.molarExtinction(True)))\r\n print (\"mass Extinction coefficient: {:.2f}\".format(myParamMaker.massExtinction(True)))\r\n print (\"Theoretical pI: {:.2f}\".format(myParamMaker.pI(2)))\r\n print (\"Amino acid composition:\")\r\n keys = list(myAAcomposition.keys())\r\n keys.sort()\r\n if myAAnumber == 0 : myAAnumber = 1 # handles the case where no AA are present \r\n for key in keys :\r\n print (\"\\t{} = {:.2%}\".format(key, myAAcomposition[key]/myAAnumber)) # formats the AAcomposition output\r\n inString = input('protein sequence?') # program will run until terminated\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n \r\n # Method pI based on http://interactivepython.org/runestone/static/pythonds/SortSearch/TheBinarySearch.html","sub_path":"ProteinParam.py","file_name":"ProteinParam.py","file_ext":"py","file_size_in_byte":12963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"65136678","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\nfrom data.clean_data import get_clean_data\nfrom core.config import clasif_folders, charts_folders, CHART_PAD_SIZE, CHART_TITLE_SIZE\n\ndef plot_users_charts(path):\n #Set variables\n df = get_clean_data()\n #Matplotlib\n plt.rcParams['font.family'] = \"serif\"\n users_colors = ['#ff9999','#66b3ff','#99ff99','#ffcc99'] \n\n #paths -- FIX\n barchart_path = path / clasif_folders[0] / charts_folders[0]\n piechart_path = path / clasif_folders[0] / charts_folders[1]\n \n grouped_month = df.groupby(['User','Month_year'],as_index=False)['Price'].sum()\n distinct_months = grouped_month['Month_year'].unique()\n for i in distinct_months:\n df_month = grouped_month.loc[grouped_month['Month_year'] == i]\n distinct_users = df_month['User'].unique()\n y_pos = np.arange(len(distinct_users))\n totalspent_peruser = df_month['Price']\n\n plot_users_barchart(y_pos, totalspent_peruser, distinct_users, barchart_path, users_colors, i )\n plot_users_piechart(totalspent_peruser, distinct_users, piechart_path, users_colors, i)\n return distinct_months\n\ndef plot_users_barchart(y_pos, totalspent_peruser, distinct_users, path, color, date):\n plt.bar(y_pos, totalspent_peruser, color = color)\n plt.xticks(y_pos, distinct_users)\n plt.ylabel('$ Pesos Argentinos')\n plt.title('Bugdet per person for month: ' + date.strftime('%m-%Y'), size = CHART_TITLE_SIZE, pad = CHART_PAD_SIZE)\n plt.savefig(f'{path}/{date}.jpg')\n plt.close()\n\ndef plot_users_piechart(totalspent_peruser, distinct_users, path, color, date,):\n #Donut pie chart\n fig1, ax1 = plt.subplots()\n ax1.pie(totalspent_peruser, colors=color, labels=distinct_users, autopct='%1.1f%%', \n startangle=90, pctdistance=0.85, radius=1)\n #draw circle\n centre_circle = plt.Circle((0,0),0.70,fc='white')\n fig = plt.gcf()\n fig.gca().add_artist(centre_circle)\n\n ax1.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.\n plt.title('Percentage per person for month: ' + date.strftime('%m-%Y'), size = CHART_TITLE_SIZE, pad = CHART_PAD_SIZE)\n plt.savefig(f'{path}/{date}.jpg')\n plt.close()\n\n","sub_path":"app/visualization/plot_users.py","file_name":"plot_users.py","file_ext":"py","file_size_in_byte":2212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"70105694","text":"# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution(object):\n def isBalanced(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: bool\n \"\"\"\n if root == None:\n return True\n l = self.depth(root.left)\n r = self.depth(root.right)\n return (\n (abs(l - r) < 2)\n and self.isBalanced(root.left)\n and self.isBalanced(root.right)\n )\n\n def depth(self, node):\n if node == None:\n return 0\n return max(self.depth(node.left), self.depth(node.right)) + 1\n","sub_path":"python/Jan22/110balancedbinaryt.py","file_name":"110balancedbinaryt.py","file_ext":"py","file_size_in_byte":727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"518128669","text":"# Task_4 Q_14:\n# Function Description\n# Complete the merge_the_tools function in the editor below.\n\n# merge_the_tools has the following parameters:\n# string s: the string to analyze\n# int k: the size of substrings to analyze\n\n# Prints\n# Print each subsequence on a new line. There will be n/k of them. No return value is expected.\n\n# Input Format\n# The first line contains a single string,s .\n# The second line contains an integer, k, the length of each substring.\n\ndef merge_the_tools(string, k):\n for i in range(0,len(string), k):\n line = string[i:i+k]\n seen = set()\n for i in line:\n if i not in seen:\n print(i,end=\"\")\n seen.add(i)\n print()\n\nif __name__ == '__main__':\n string, k = input(), int(input())\n merge_the_tools(string, k)","sub_path":"Task 4(Basic Python Strings)/14_Merge_Tools.py","file_name":"14_Merge_Tools.py","file_ext":"py","file_size_in_byte":811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"257151133","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\nimport ConfigParser\nfrom hermes_python.hermes import Hermes\nfrom hermes_python.ontology import *\nfrom snipsowm.snipsowm import SnipsOWM\nimport io\nimport math\nimport datetime as dt\nfrom dateutil.parser import parse\n\nCONFIGURATION_ENCODING_FORMAT = \"utf-8\"\nCONFIG_INI = \"config.ini\"\n\nclass SnipsConfigParser(ConfigParser.SafeConfigParser):\n def to_dict(self):\n return {section : {option_name : option for option_name, option in self.items(section)} for section in self.sections()}\n\n\ndef read_configuration_file(configuration_file):\n try:\n with io.open(configuration_file, encoding=CONFIGURATION_ENCODING_FORMAT) as f:\n conf_parser = SnipsConfigParser()\n conf_parser.readfp(f)\n return conf_parser.to_dict()\n except (IOError, ConfigParser.Error) as e:\n return dict()\n\ndef subscribe_intent_callback(hermes, intentMessage):\n conf = read_configuration_file(CONFIG_INI)\n action_wrapper(hermes, intentMessage, conf)\n\n\ndef action_wrapper(hermes, intentMessage, conf):\n \"\"\" Write the body of the function that will be executed once the intent is recognized. \n In your scope, you have the following objects : \n - intentMessage : an object that represents the recognized intent\n - hermes : an object with methods to communicate with the MQTT bus following the hermes protocol. \n - conf : a dictionary that holds the skills parameters you defined \n\n Refer to the documentation for further details. \n \"\"\" \n # Determine datetime\n datetime = None\n\n if intentMessage.slots.forecast_start_datetime:\n datetime = intentMessage.slots.forecast_start_datetime[0]\n if isinstance(datetime, snips.types.InstantTime):\n datetime = (datetime.datetime).replace(tzinfo=None)\n elif isinstance(datetime, snips.types.TimeInterval):\n datetime = (datetime.end).replace(tzinfo=None)\n\n\n # Determine granularity\n granularity = None\n if datetime: # We have an information about the date.\n now = dt.datetime.now().replace(tzinfo=None)\n delta_days = abs((datetime - now).days)\n if delta_days > 10: # There a week difference between today and the date we want the forecast.\n granularity = 2 # Give the day of the forecast date, plus the number of the day in the month.\n elif delta_days > 5: # There a 10-day difference between today and the date we want the forecast.\n granularity = 1 # Give the full date\n else:\n granularity = 0 # Just give the day of the week\n else:\n granularity = 0\n\n # Determine condition\n condition_name = None\n try:\n condition_name = intentMessage.slots.forecast_condition_name[0] if intentMessage.slots.forecast_condition_name else None\n except Exception:\n pass\n\n intentMessage.slots.forecast_locality = intentMessage.slots.forecast_locality[0] if intentMessage.slots.forecast_locality else None\n intentMessage.slots.forecast_region = intentMessage.slots.forecast_region[0] if intentMessage.slots.forecast_region else None\n intentMessage.slots.forecast_country = intentMessage.slots.forecast_country[0] if intentMessage.slots.forecast_country else None\n intentMessage.slots.forecast_geographical_poi = intentMessage.slots.forecast_geographical_poi[0] if intentMessage.slots.forecast_geographical_poi else None\n\n #print \"cond: {}, datetime: {}, Locality: {}, granularity: {}\".format(condition_name, datetime, snips.intent.forecast_locality, granularity)\n snipsowm.speak_condition(snips, condition_name, datetime, granularity=granularity, Locality=snips.intent.forecast_locality, Region=snips.intent.forecast_region, Country=snips.intent.forecast_country, POI=snips.intent.forecast_geographical_poi)\n\n current_session_id = intentMessage.session_id\n hermes.publish_end_session(current_session_id, result_sentence)\n\n\nif __name__ == \"__main__\":\n snipsowm= SnipsOWM(\"5459abd58e64fe7f121792fabe60fe5c\",\"France\",\"fr_FR\") \n with Hermes(\"localhost:1883\") as h:\n h.subscribe_intent(\"searchWeatherForecastCondition\", subscribe_intent_callback) \\\n.start()\n","sub_path":"action-searchWeatherForecastCondition-handler.py","file_name":"action-searchWeatherForecastCondition-handler.py","file_ext":"py","file_size_in_byte":4148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"379837799","text":"from selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nimport unittest # 需要引入 unittest、time、 等程式\nfrom selenium.webdriver.common.keys import Keys\nimport random\nimport time\nfrom .Keyword import *\n\nclass test_enquire(unittest.TestCase): # 測試項目\n def setUp(self):\n self.url=\"http://127.0.0.1:3000/\" # 要執行自動測試的網站\n\n def test_create_enquiry(self):\n test=webdriver.Chrome()\n test.get( self.url )\n test.maximize_window()\n go_to_login_page_subtab(test, 'contact' )\n # precondition\n input_field( test, 'name', \"GP\" )\n input_field( test, 'email', \"a5824384@gmail.com\" )\n input_field( test, 'phone', \"035824384\" )\n input_field( test, 'phone', \"0962010830\" )\n select_contact_dropdown_field( test, 'Just leaving a message' )\n exist = is_text_present( test, 'Just leaving a message' )\n self.assertTrue( exist )\n select_contact_dropdown_field( test, \"I've got a question\" )\n exist = is_text_present( test, \"I've got a question\" )\n self.assertTrue( exist )\n select_contact_dropdown_field( test, 'Something else...' )\n exist = is_text_present( test, 'Something else...' )\n self.assertTrue( exist )\n input_text_area( test, 'message', '!@#$%' )\n input_text_area( test, 'message', '12345' )\n input_text_area( test, 'message', 'Test1' )\n input_text_area( test, 'message', 'EDIT TEST' )\n submit( test )\n \n success = get_web_element( test, '//*[normalize-space() = \"Success!\"]' ).text\n self.assertEqual( success, 'Success!' )\n time.sleep(2)\n test.close()\n \n def test_delete_enquiry(self):\n test=webdriver.Chrome()\n test.get( self.url )\n test.maximize_window()\n login( test )\n sub_tab_go_to_page( test, 'enquiries' )\n # precondition\n get_web_element( test, '//*[contains(@class, \"ItemList__value\") and normalize-space() = \"GP\"]/../..//*[contains(@class,\"octicon octicon-trashcan\")]' ).click()\n get_web_element( test, '//*[normalize-space() = \"Delete\"]' ).click()\n exist = is_text_present( test, \"GP\" )\n self.assertFalse( exist )\n time.sleep(2)\n test.close()\n \ndef submit( _driver ):\n get_web_element( _driver, '//button[contains(normalize-space(), \"Submit\")]' ).click()\n\ndef select_contact_dropdown_field( _driver, text ):\n get_web_element( _driver, '//*[contains( @name, \"enquiryType\") ]' ).click()\n get_web_element( _driver, '//option[contains(normalize-space(), \"%s\")]' %text ).click()\n\ndef input_text_area( _driver, field, text ):\n get_web_element( _driver, '//textarea[contains( @name , \"%s\") ]' %field ).send_keys( Keys.CONTROL+'a' )\n get_web_element( _driver, '//textarea[contains( @name , \"%s\") ]' %field).send_keys( Keys.BACKSPACE )\n get_web_element( _driver, '//textarea[contains( @name , \"%s\") ]' %field ).send_keys( text )\n\nif __name__==\"__main__\":\n testsuite=unittest.TestSuite()\n testsuite.addTest(test_enquire(\"test_create_enquiry\"))\n testsuite.addTest(test_enquire(\"test_delete_enquiry\"))\n runner = unittest.TextTestRunner(verbosity=2)\n runner.run(testsuite)","sub_path":"Test/src/Test/Enquirie.py","file_name":"Enquirie.py","file_ext":"py","file_size_in_byte":3381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"529891894","text":"# NLP Pipeline using Luigi\nimport twint\nimport spacy\nimport csv\nfrom datetime import datetime, date\nimport os\nfrom luigi.parameter import DateParameter\nfrom luigi import Task, LocalTarget\nimport luigi\n\nnlp = spacy.load(\"en_core_web_sm\")\n\n# this is the earliest date we consider, CAUTION: processing takes ages if we use too many tweets\nEARLIEST_DATE = \"2020-10-01\"\n\n\nclass Scrape(Task):\n earliest_date = DateParameter(default=date.today())\n\n def run(self):\n output_filename = 'tweets_since_%s.csv' % self.earliest_date\n\n # remove old output file if it exists\n if os.path.exists(output_filename):\n os.remove(output_filename)\n\n # scrape tweets\n c = twint.Config()\n c.Username = \"realDonaldTrump\"\n c.Since = str(self.earliest_date)\n c.Store_csv = True\n c.Custom_csv = [\"tweet\"]\n # save the scraped tweets into this file\n c.Output = output_filename\n # run the actual twitter search\n twint.run.Search(c)\n\n def output(self):\n return LocalTarget('tweets_since_%s.csv' % self.earliest_date)\n\n\nclass Filter(Task):\n earliest_date = DateParameter(default=date.today())\n\n def requires(self):\n return Scrape(self.earliest_date)\n\n def run(self):\n # open the saved tweets\n with self.output().open('w') as output_file:\n with self.input().open('r') as input_file:\n records = csv.DictReader(input_file)\n for row in records:\n # filter out retweets (starting with 'RT')\n if not row['tweet'].startswith('RT'):\n output_file.write(row['tweet'])\n\n def output(self):\n return LocalTarget('tweets_filtered_since_%s.csv' % self.earliest_date)\n\n\nclass GetBidens(Task):\n earliest_date = DateParameter(default=date.today())\n\n def requires(self):\n return Filter(self.earliest_date)\n\n def run(self):\n with self.input().open('r') as file:\n doc = nlp(file.read())\n\n # print all mentioned persons\n for entity in doc.ents:\n if entity.label_ == 'PERSON':\n print(entity.text, entity.label_)\n\n # count the number of Bidens in the tweets\n num_bidens = len([e for e in doc.ents if\n e.label_ == 'PERSON' and ('biden' in e.text.lower() or 'joe' in e.text.lower())])\n print('Number of Bidens in Trump\\'s tweets since ' + str(EARLIEST_DATE) + ': ' + str(num_bidens))\n\n\nif __name__ == '__main__':\n luigi.build([GetBidens(earliest_date=datetime.strptime(EARLIEST_DATE, \"%Y-%m-%d\"))], local_scheduler=True)\n","sub_path":"7-1-luigi-pipelining/luigi_nlp.py","file_name":"luigi_nlp.py","file_ext":"py","file_size_in_byte":2673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"152798899","text":"import torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\nimport torch.nn.functional as F\nimport numpy as np\n\nclass ContrastiveLoss(torch.nn.Module):\n \"\"\"\n Contrastive loss function.\n Based on: http://yann.lecun.com/exdb/publis/pdf/hadsell-chopra-lecun-06.pdf\n \"\"\"\n def __init__(self, margin=1.0):\n super(ContrastiveLoss, self).__init__()\n self.margin = margin\n\n def forward(self, dist, label):\n dist = torch.squeeze(dist)\n #print(dist)\n loss = torch.mean((1-label) * torch.pow(dist, 2) +\n (label) * torch.pow(torch.clamp(self.margin - dist, min=0.0), 2))\n return loss\n\nclass VAMetric(nn.Module):\n\tdef __init__(self):\n\t\tsuper(VAMetric, self).__init__()\n\t\tself.conv1 = nn.Conv2d(1,300,(1,1152))\n\t\tself.lstm1 = nn.LSTMCell(300, 128)\n\t\tself.lstm2 = nn.LSTMCell(128, 128)\n\t\tself.fc1 = nn.Linear(128, 1)\n\n\tdef init_params(self):\n\t\tfor m in self.modules():\n\t\t\tif isinstance(m, nn.Linear):\n\t\t\t\tnn.init.xavier_uniform(m.weight)\n\t\t\t\tnn.init.constant(m.bias, 0)\n\n\tdef forward(self, vfeat, afeat):\n\t\t#vfeat 128*120*1024\n\t\t#afeat 128*120*128\n\t\tfeat = torch.cat((vfeat,afeat), 2) #128*120*1152\n\t\tfeat = torch.unsqueeze(feat, 1) #128*1*120*1152\n\t\t#print(feat.size())\n\n\t\tfeat1 = F.relu(self.conv1(feat)) #128*300*120*1\n\t\tfeat1 = torch.squeeze(feat1) #128*300*120\n\n\t\th_t1 = Variable(torch.zeros(feat1.size(0), 128).float(), requires_grad=False)\n\t\tc_t1 = Variable(torch.zeros(feat1.size(0), 128).float(), requires_grad=False)\n\t\th_t2 = Variable(torch.zeros(feat1.size(0), 128).float(), requires_grad=False)\n\t\tc_t2 = Variable(torch.zeros(feat1.size(0), 128).float(), requires_grad=False)\n\n\t\th_t1 = h_t1.cuda()\n\t\tc_t1 = c_t1.cuda()\n\t\th_t2 = h_t2.cuda()\n\t\tc_t2 = c_t2.cuda()\n\n\t\tfor _, feat_t in enumerate(feat1.chunk(feat1.size(2), dim=2)):\n\t\t\tfeat_t = torch.squeeze(feat_t)\n\t\t\th_t1, c_t1 = self.lstm1(feat_t, (h_t1, c_t1))\n\t\t\th_t2, c_t2 = self.lstm2(h_t1, (h_t2, c_t2))\n\n\t\t#print(h_t2.size())\n\t\tpair = F.relu(self.fc1(h_t2)) #128*1\n\t\treturn pair\n","sub_path":"proj_demo/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"69518919","text":"import argparse\nimport logging\nimport os\nimport random\n\nimport torch\nimport torch.nn as nn\nfrom torch.optim import Adam\nfrom torch.optim.lr_scheduler import LambdaLR\nfrom pytorch_pretrained_bert import BertModel\nimport numpy as np\n\nfrom data_loader import DataLoader\nimport utils\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--data_dir', default='data/task1', help=\"Directory containing the dataset\")\nparser.add_argument('--bert_model_dir', default='bert-base-uncased-pytorch', help=\"Directory containing the BERT model in PyTorch\")\nparser.add_argument('--model_dir', default='experiments/base_model', help=\"Directory containing params.json\")\nparser.add_argument('--seed', type=int, default=2019, help=\"random seed for initialization\")\nparser.add_argument('--restore_file', default=None,\n help=\"Optional, name of the file in --model_dir containing weights to reload before training\")\nparser.add_argument('--multi_gpu', default=False, action='store_true', help=\"Whether to use multiple GPUs if available\")\nparser.add_argument('--fp16', default=False, action='store_true', help=\"Whether to use 16-bit float precision instead of 32-bit\")\nparser.add_argument('--loss_scale', type=float, default=0,\n help=\"Loss scaling to improve fp16 numeric stability. Only used when fp16 set to True.\\n\"\n \"0 (default value): dynamic loss scaling.\\n\"\n \"Positive power of 2: static loss scaling value.\\n\")\n\n\n'''\nCode borrowed from https://pytorch.org/tutorials/beginner/nlp/advanced_tutorial.html\nand mixed with https://github.com/Louis-udm/NER-BERT-CRF/blob/master/NER_BERT_CRF.py#L804\nthen added to BERT code from https://github.com/pranav-ust/BERT-keyphrase-extraction\n'''\n\n\ndef argmax(vec):\n # return the argmax as a python int\n _, idx = torch.max(vec, 1)\n return idx.item()\n\n\ndef log_sum_exp_batch(log_Tensor, axis=-1): # shape (batch_size,n,m)\n return torch.max(log_Tensor, axis)[0]+torch.log(torch.exp(log_Tensor-torch.max(log_Tensor, axis)[0].view(log_Tensor.shape[0],-1,1)).sum(axis))\n\n\nclass BERT_CRF(nn.Module):\n\n def __init__(self, bert_model, vocab_size, tag_to_idx):\n super(BERT_CRF, self).__init__()\n self.hidden_size = 768\n self.vocab_size = vocab_size\n self.tag_to_idx = tag_to_idx\n self.num_labels = len(tag_to_idx)\n\n self.bert = bert_model\n self.dropout = torch.nn.Dropout(0.2)\n\n # Maps the output of BERT into tag space.\n self.hidden2tag = nn.Linear(self.hidden_size, self.num_labels)\n\n # Matrix of transition parameters. Entry i,j is the score of\n # transitioning *to* i *from* j.\n self.transitions = nn.Parameter(torch.randn(self.num_labels, self.num_labels))\n\n # These two statements enforce the constraint that we never transfer\n # to the start tag and we never transfer from the stop tag\n self.transitions.data[tag_to_idx[START_TAG], :] = -10000\n self.transitions.data[:, tag_to_idx[STOP_TAG]] = -10000\n\n nn.init.xavier_uniform_(self.hidden2tag.weight)\n nn.init.constant_(self.hidden2tag.bias, 0.0)\n\n def init_bert_weights(self, module):\n \"\"\" Initialize the weights.\n \"\"\"\n if isinstance(module, (nn.Linear, nn.Embedding)):\n # Slightly different from the TF version which uses truncated_normal for initialization\n # cf https://github.com/pytorch/pytorch/pull/5617\n module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)\n if isinstance(module, nn.Linear) and module.bias is not None:\n module.bias.data.zero_()\n\n def _forward_alg(self, feats):\n T = feats.shape[1]\n batch_size = feats.shape[0]\n\n # alpha_recursion,forward, alpha(zt)=p(zt,bar_x_1:t)\n log_alpha = torch.Tensor(batch_size, 1, self.num_labels).fill_(-10000.).to(params.device)\n # normal_alpha_0 : alpha[0]=Ot[0]*self.PIs\n # START TAG has all of the score. it is log,0 is p=1\n log_alpha[:, 0, self.tag_to_idx[START_TAG]] = 0\n\n # feats: sentances -> word embedding -> lstm -> MLP -> feats\n # feats is the probability of emission, feat.shape=(1,tag_size)\n for t in range(1, T):\n log_alpha = (log_sum_exp_batch(self.transitions + log_alpha, axis=-1) + feats[:, t]).unsqueeze(1)\n\n # log_prob of all barX\n log_prob_all_barX = log_sum_exp_batch(log_alpha)\n return log_prob_all_barX\n\n def _get_bert_features(self, sentence, sentence_mask):\n '''\n sentances -> word embedding -> bert -> MLP -> feats\n '''\n bert_seq_out, _ = self.bert(sentence, token_type_ids=None, attention_mask=sentence_mask,\n output_all_encoded_layers=False)\n bert_seq_out = self.dropout(bert_seq_out)\n bert_feats = self.hidden2tag(bert_seq_out)\n return bert_feats\n\n\n def _score_sentence(self, feats, tags):\n # Gives the score of a provided tag sequence\n score = torch.zeros(1).cuda()\n start = torch.tensor([self.tag_to_idx[START_TAG]], dtype=torch.long).cuda()\n tags = torch.cat([start, tags.flatten()])\n for i, feat in enumerate(feats):\n score = score + \\\n self.transitions[tags[i + 1], tags[i]] + feat[tags[i + 1]]\n score = score + self.transitions[self.tag_to_idx[STOP_TAG], tags[-1]]\n return score\n\n def _viterbi_decode(self, feats):\n T = feats.shape[1]\n batch_size = feats.shape[0]\n\n log_delta = torch.Tensor(batch_size, 1, self.num_labels).fill_(-10000.).to(params.device)\n log_delta[:, 0, self.tag_to_idx[START_TAG]] = 0\n\n # psi is for the vaule of the last latent that make P(this_latent) maximum.\n psi = torch.zeros((batch_size, T, self.num_labels), dtype=torch.long).to(params.device) # psi[0]=0000 useless\n for t in range(1, T):\n # delta[t][k]=max_z1:t-1( p(x1,x2,...,xt,z1,z2,...,zt-1,zt=k|theta) )\n # delta[t] is the max prob of the path from z_t-1 to z_t[k]\n log_delta, psi[:, t] = torch.max(self.transitions + log_delta, -1)\n # psi[t][k]=argmax_z1:t-1( p(x1,x2,...,xt,z1,z2,...,zt-1,zt=k|theta) )\n # psi[t][k] is the path choosed from z_t-1 to z_t[k],the value is the z_state(is k) index of z_t-1\n log_delta = (log_delta + feats[:, t]).unsqueeze(1)\n\n # trace back\n path = torch.zeros((batch_size, T), dtype=torch.long).to(params.device)\n\n # max p(z1:t,all_x|theta)\n max_logLL_allz_allx, path[:, -1] = torch.max(log_delta.squeeze(), -1)\n\n for t in range(T - 2, -1, -1):\n # choose the state of z_t according the state choosed of z_t+1.\n path[:, t] = psi[:, t + 1].gather(-1, path[:, t + 1].view(-1, 1)).squeeze()\n\n return max_logLL_allz_allx, path\n\n def neg_log_likelihood(self, sentence, tags, sentence_mask):\n feats = self._get_bert_features(sentence, sentence_mask)\n forward_score = self._forward_alg(feats)\n gold_score = self._score_sentence(feats, tags)\n return forward_score - gold_score\n\n def forward(self, sentence, sentence_mask): # dont confuse this with _forward_alg above.\n # Get the emission scores from BERT\n bert_feats = self._get_bert_features(sentence, sentence_mask)\n\n # Find the best path, given the features.\n score, tag_seq = self._viterbi_decode(bert_feats)\n return score, tag_seq\n\n\ndef train(model, train_data, val_data, optimizer, scheduler, params):\n print(\"***** Running Training *****\")\n for epoch in range(1, params.epoch_num + 1):\n print(\"Epoch: \", epoch)\n model.train()\n optimizer.zero_grad()\n\n # a running average object for loss\n loss_avg = utils.RunningAverage()\n\n train_data_iterator = data_loader.data_iterator(train_data, shuffle=True)\n for batch_data, batch_tags in train_data_iterator:\n # Run our forward pass.\n batch_masks = batch_data.gt(0)\n loss = model.neg_log_likelihood(batch_data, batch_tags, batch_masks).sum()\n\n if params.n_gpu > 1 and args.multi_gpu:\n loss = loss.mean() # mean() to average on multi-gpu\n\n model.zero_grad()\n if args.fp16:\n optimizer.backward(loss)\n else:\n loss.backward()\n\n # gradient clipping\n nn.utils.clip_grad_norm_(parameters=model.parameters(), max_norm=params.clip_grad)\n\n # Compute the loss, gradients, and update the parameters by\n # calling optimizer.step()\n optimizer.step()\n loss_avg.update(loss.item())\n\n scheduler.step()\n\n train_data_iterator = data_loader.data_iterator(train_data, shuffle=True)\n evaluate(model, train_data_iterator, \"Train Data\")\n print()\n val_data_iterator = data_loader.data_iterator(val_data, shuffle=True)\n evaluate(model, val_data_iterator, \"Val Data\")\n print('--------------------------------------------------------------')\n print()\n\n\n\ndef evaluate(model, data_iterator, dataset_name):\n model.eval()\n all_preds = []\n all_labels = []\n total = 0\n correct = 0\n with torch.no_grad():\n for batch_data, batch_tags in data_iterator:\n batch_masks = batch_data.gt(0)\n _, predicted_label_seq_ids = model(batch_data, batch_masks)\n valid_predicted = torch.masked_select(predicted_label_seq_ids, batch_masks)\n valid_label_ids = torch.masked_select(batch_tags, batch_masks)\n all_preds.extend(valid_predicted.tolist())\n all_labels.extend(valid_label_ids.tolist())\n total += len(valid_label_ids)\n correct += valid_predicted.eq(valid_label_ids).sum().item()\n\n test_acc = correct / total\n precision, recall, f1 = f1_score(np.array(all_labels), np.array(all_preds))\n print(dataset_name)\n print('Acc:%.2f, Precision: %.2f, Recall: %.2f, F1: %.2f' \\\n % (100. * test_acc, 100. * precision, 100. * recall, 100. * f1))\n return test_acc, f1\n\n\ndef f1_score(y_true, y_pred):\n '''\n 0,1,2,3 are I, O, [CLS], [SEP]\n or\n 0,1,2,3,4,5,6,7,8 are B-Task, I-Task, B-Material, I-Material, B-Process, I-Process, O, [CLS], [SEP]\n '''\n ignore_id = len(params.tag2idx) - 1\n\n num_proposed = len(y_pred[y_pred < ignore_id])\n num_correct = (np.logical_and(y_true == y_pred, y_true < ignore_id)).sum()\n num_gold = len(y_true[y_true < ignore_id])\n\n try:\n precision = num_correct / num_proposed\n except ZeroDivisionError:\n precision = 1.0\n\n try:\n recall = num_correct / num_gold\n except ZeroDivisionError:\n recall = 1.0\n\n try:\n f1 = 2 * precision * recall / (precision + recall)\n except ZeroDivisionError:\n if precision * recall == 0:\n f1 = 1.0\n else:\n f1 = 0\n\n return precision, recall, f1\n\n\ndef add_start_stop_idx(tag2idx, idx2tag):\n max_idx = max(list(tag2idx.values()))\n tag2idx[START_TAG] = max_idx + 1\n tag2idx[STOP_TAG] = max_idx + 2\n\n idx2tag[max_idx + 1] = START_TAG\n idx2tag[max_idx + 2] = STOP_TAG\n\n\nSTART_TAG = \"[CLS]\"\nSTOP_TAG = \"[SEP]\"\n\nif __name__ == '__main__':\n args = parser.parse_args()\n\n # Load the parameters from json file\n json_path = os.path.join(args.model_dir, 'params.json')\n assert os.path.isfile(json_path), \"No json configuration file found at {}\".format(json_path)\n params = utils.Params(json_path)\n\n # Use GPUs if available\n params.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n params.n_gpu = torch.cuda.device_count()\n params.multi_gpu = args.multi_gpu\n\n # Set the random seed for reproducible experiments\n random.seed(args.seed)\n torch.manual_seed(args.seed)\n if params.n_gpu > 0:\n torch.cuda.manual_seed_all(args.seed) # set random seed for all GPUs\n params.seed = args.seed\n\n # Set the logger\n utils.set_logger(os.path.join(args.model_dir, 'train.log'))\n logging.info(\"device: {}, n_gpu: {}, 16-bits training: {}\".format(params.device, params.n_gpu, args.fp16))\n\n # Create the input data pipeline\n logging.info(\"Loading the datasets...\")\n\n # Initialize the DataLoader\n data_loader = DataLoader(args.data_dir, args.bert_model_dir, params, token_pad_idx=0)\n\n # Load training data and test data\n train_data = data_loader.load_data('train')\n val_data = data_loader.load_data('val')\n test_data = data_loader.load_data('test')\n\n # Specify the training and validation dataset sizes\n params.train_size = train_data['size']\n params.val_size = val_data['size']\n params.test_size = test_data['size']\n\n # Add start and stop tag mappings\n add_start_stop_idx(params.tag2idx, params.idx2tag)\n\n # Prepare model\n bert_model = BertModel.from_pretrained(args.bert_model_dir)\n bert_model.to(params.device)\n crf_model = BERT_CRF(bert_model, params.train_size, params.tag2idx)\n crf_model.to(params.device)\n\n if args.fp16:\n crf_model.half()\n\n if params.n_gpu > 1 and args.multi_gpu:\n crf_model = torch.nn.DataParallel(crf_model)\n\n # Prepare optimizer\n if params.full_finetuning:\n param_optimizer = list(crf_model.named_parameters())\n no_decay = ['bias', 'LayerNorm.bias', 'LayerNorm.weight']\n # no_decay = ['bias', 'gamma', 'beta']\n optimizer_grouped_parameters = [\n {'params': [p for n, p in param_optimizer if not any(nd in n for nd in no_decay)],\n 'weight_decay_rate': 0.01},\n {'params': [p for n, p in param_optimizer if any(nd in n for nd in no_decay)],\n 'weight_decay_rate': 0.0}\n ]\n else:\n param_optimizer = list(crf_model.classifier.named_parameters())\n optimizer_grouped_parameters = [{'params': [p for n, p in param_optimizer]}]\n if args.fp16:\n try:\n from apex.optimizers import FP16_Optimizer\n from apex.optimizers import FusedAdam\n except ImportError:\n raise ImportError(\"Please install apex from https://www.github.com/nvidia/apex to use fp16 training.\")\n optimizer = FusedAdam(optimizer_grouped_parameters,\n lr=params.learning_rate,\n bias_correction=False,\n max_grad_norm=1.0)\n scheduler = LambdaLR(optimizer, lr_lambda=lambda epoch: 1/(1 + 0.05*epoch))\n if args.loss_scale == 0:\n optimizer = FP16_Optimizer(optimizer, dynamic_loss_scale=True)\n else:\n optimizer = FP16_Optimizer(optimizer, static_loss_scale=args.loss_scale)\n else:\n optimizer = Adam(optimizer_grouped_parameters, lr=params.learning_rate)\n scheduler = LambdaLR(optimizer, lr_lambda=lambda epoch: 1/(1 + 0.05*epoch))\n\n train(crf_model, train_data, val_data, optimizer, scheduler, params)\n test_data_iterator = data_loader.data_iterator(test_data, shuffle=True)\n print(\"***** Running prediction *****\")\n evaluate(crf_model, test_data_iterator, 'Test Data')\n","sub_path":"train_with_crf.py","file_name":"train_with_crf.py","file_ext":"py","file_size_in_byte":15167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"590030330","text":"import json\n\nfrom nose.tools import eq_\n\nimport amo\nfrom addons.models import AddonCategory, AddonDeviceType, Category\nfrom amo.tests import ESTestCase\nfrom mkt.api.tests.test_oauth import BaseOAuth, OAuthClient\nfrom mkt.search.forms import DEVICE_CHOICES_IDS\nfrom mkt.webapps.models import Webapp\n\n\nclass TestApi(BaseOAuth, ESTestCase):\n fixtures = ['webapps/337141-steamcube']\n\n def setUp(self):\n self.client = OAuthClient(None)\n self.list_url = ('api_dispatch_list', {'resource_name': 'search'})\n self.webapp = Webapp.objects.get(pk=337141)\n self.category = Category.objects.create(name='test',\n type=amo.ADDON_WEBAPP)\n self.webapp.save()\n self.refresh()\n\n def test_verbs(self):\n self._allowed_verbs(self.list_url, ['get'])\n\n def test_meta(self):\n res = self.client.get(self.list_url)\n eq_(res.status_code, 200)\n eq_(set(json.loads(res.content).keys()), set(['objects', 'meta']))\n\n def test_wrong_category(self):\n res = self.client.get(self.list_url + ({'cat': self.category.pk + 1},))\n eq_(res.status_code, 400)\n eq_(res['Content-Type'], 'application/json')\n\n def test_wrong_weight(self):\n self.category.update(weight=-1)\n res = self.client.get(self.list_url + ({'cat': self.category.pk},))\n eq_(res.status_code, 400)\n\n def test_wrong_sort(self):\n res = self.client.get(self.list_url + ({'sort': 'awesomeness'},))\n eq_(res.status_code, 400)\n\n def test_right_category(self):\n res = self.client.get(self.list_url + ({'cat': self.category.pk},))\n eq_(res.status_code, 200)\n eq_(json.loads(res.content)['objects'], [])\n\n def create(self):\n AddonCategory.objects.create(addon=self.webapp, category=self.category)\n self.webapp.save()\n self.refresh()\n\n def test_right_category_present(self):\n self.create()\n res = self.client.get(self.list_url + ({'cat': self.category.pk},))\n eq_(res.status_code, 200)\n objs = json.loads(res.content)['objects']\n eq_(len(objs), 1)\n\n def test_dehydrate(self):\n self.create()\n res = self.client.get(self.list_url + ({'cat': self.category.pk},))\n eq_(res.status_code, 200)\n obj = json.loads(res.content)['objects'][0]\n eq_(obj['app_slug'], self.webapp.app_slug)\n eq_(obj['icon_url_128'], self.webapp.get_icon_url(128))\n eq_(obj['absolute_url'], self.webapp.get_absolute_url())\n eq_(obj['resource_uri'], None)\n\n def test_q(self):\n res = self.client.get(self.list_url + ({'q': 'something'},))\n eq_(res.status_code, 200)\n obj = json.loads(res.content)['objects'][0]\n eq_(obj['app_slug'], self.webapp.app_slug)\n\n def test_device(self):\n AddonDeviceType.objects.create(\n addon=self.webapp, device_type=DEVICE_CHOICES_IDS['desktop'])\n self.webapp.save()\n self.refresh()\n res = self.client.get(self.list_url + ({'device': 'desktop'},))\n eq_(res.status_code, 200)\n obj = json.loads(res.content)['objects'][0]\n eq_(obj['app_slug'], self.webapp.app_slug)\n\n def test_premium_types(self):\n res = self.client.get(self.list_url + (\n {'premium_types': 'free'},))\n eq_(res.status_code, 200)\n obj = json.loads(res.content)['objects'][0]\n eq_(obj['app_slug'], self.webapp.app_slug)\n\n def test_premium_types_empty(self):\n res = self.client.get(self.list_url + (\n {'premium_types': 'premium'},))\n eq_(res.status_code, 200)\n objs = json.loads(res.content)['objects']\n eq_(len(objs), 0)\n\n def test_multiple_premium_types(self):\n res = self.client.get(self.list_url + (\n {'premium_types': 'free'},\n {'premium_types': 'premium'}))\n eq_(res.status_code, 200)\n obj = json.loads(res.content)['objects'][0]\n eq_(obj['app_slug'], self.webapp.app_slug)\n","sub_path":"mkt/search/tests/test_api.py","file_name":"test_api.py","file_ext":"py","file_size_in_byte":4021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"641780610","text":"from __future__ import print_function\nimport sys\n\nfrom jobqueue_features.clusters import CustomSLURMCluster\nfrom jobqueue_features.decorators import on_cluster, mpi_task\nfrom jobqueue_features.mpi_wrapper import SRUN\n\n# import logging\n\n# logging.basicConfig(format=\"%(levelname)s:%(message)s\", level=logging.DEBUG)\n\ncustom_cluster = CustomSLURMCluster(\n name=\"mpiCluster\", walltime=\"00:03:00\", nodes=2, mpi_mode=True, mpi_launcher=SRUN\n)\n\n\n@mpi_task(cluster_id=\"mpiCluster\")\ndef task1(task_name):\n from mpi4py import MPI\n\n comm = MPI.COMM_WORLD\n size = comm.Get_size()\n name = MPI.Get_processor_name()\n all_nodes = comm.gather(name, root=0)\n if all_nodes:\n all_nodes = set(all_nodes)\n else:\n all_nodes = []\n # Since it is a return value it will only get printed by root\n return_string = \"Running %d tasks of type %s on nodes %s.\" % (\n size,\n task_name,\n all_nodes,\n )\n # The flush is required to ensure that the print statements appear in the job log\n # files\n print(return_string)\n sys.stdout.flush()\n return return_string\n\n\n@mpi_task(cluster_id=\"mpiCluster\")\ndef task2(name, task_name=\"default\"):\n from mpi4py import MPI\n\n comm = MPI.COMM_WORLD\n rank = comm.Get_rank()\n # This only appears in the slurm job output\n return_string = \"Hi %s, my rank is %d for task of type %s\" % (name, rank, task_name)\n # The flush is required to ensure that the print statements appear in the job log\n # files\n print(return_string)\n sys.stdout.flush()\n return return_string\n\n\n@on_cluster(cluster=custom_cluster, cluster_id=\"mpiCluster\")\ndef main():\n t1 = task1(\"task1\")\n t2 = task1(\"task1, 2nd iteration\")\n t3 = task2(\"Alan\", task_name=\"Task 2\")\n print(t1.result())\n print(t2.result())\n print(t3.result())\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"examples/mpi_tasks_srun.py","file_name":"mpi_tasks_srun.py","file_ext":"py","file_size_in_byte":1862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"514242224","text":"import os\nimport asyncio\nimport typing\nimport logging\nimport binascii\nfrom lbrynet.extras.daemon.mime_types import guess_media_type\nfrom lbrynet.stream.downloader import StreamDownloader\nfrom lbrynet.stream.descriptor import StreamDescriptor\nfrom lbrynet.stream.reflector.client import StreamReflectorClient\nfrom lbrynet.extras.daemon.storage import StoredStreamClaim\nif typing.TYPE_CHECKING:\n from lbrynet.schema.claim import ClaimDict\n from lbrynet.blob.blob_manager import BlobFileManager\n from lbrynet.dht.node import Node\n\nlog = logging.getLogger(__name__)\n\n\nclass ManagedStream:\n STATUS_RUNNING = \"running\"\n STATUS_STOPPED = \"stopped\"\n STATUS_FINISHED = \"finished\"\n\n def __init__(self, loop: asyncio.BaseEventLoop, blob_manager: 'BlobFileManager', descriptor: 'StreamDescriptor',\n download_directory: str, file_name: str, downloader: typing.Optional[StreamDownloader] = None,\n status: typing.Optional[str] = STATUS_STOPPED, claim: typing.Optional[StoredStreamClaim] = None):\n self.loop = loop\n self.blob_manager = blob_manager\n self.download_directory = download_directory\n self.file_name = file_name\n self.descriptor = descriptor\n self.downloader = downloader\n self.stream_hash = descriptor.stream_hash\n self.stream_claim_info = claim\n self._status = status\n self.fully_reflected = asyncio.Event(loop=self.loop)\n\n @property\n def status(self) -> str:\n return self._status\n\n def update_status(self, status: str):\n assert status in [self.STATUS_RUNNING, self.STATUS_STOPPED, self.STATUS_FINISHED]\n self._status = status\n\n @property\n def finished(self) -> bool:\n return self.status == self.STATUS_FINISHED\n\n @property\n def running(self) -> bool:\n return self.status == self.STATUS_RUNNING\n\n @property\n def claim_id(self) -> typing.Optional[str]:\n return None if not self.stream_claim_info else self.stream_claim_info.claim_id\n\n @property\n def txid(self) -> typing.Optional[str]:\n return None if not self.stream_claim_info else self.stream_claim_info.txid\n\n @property\n def nout(self) -> typing.Optional[int]:\n return None if not self.stream_claim_info else self.stream_claim_info.nout\n\n @property\n def outpoint(self) -> typing.Optional[str]:\n return None if not self.stream_claim_info else self.stream_claim_info.outpoint\n\n @property\n def claim_height(self) -> typing.Optional[int]:\n return None if not self.stream_claim_info else self.stream_claim_info.height\n\n @property\n def channel_claim_id(self) -> typing.Optional[str]:\n return None if not self.stream_claim_info else self.stream_claim_info.channel_claim_id\n\n @property\n def channel_name(self) -> typing.Optional[str]:\n return None if not self.stream_claim_info else self.stream_claim_info.channel_name\n\n @property\n def claim_name(self) -> typing.Optional[str]:\n return None if not self.stream_claim_info else self.stream_claim_info.claim_name\n\n @property\n def metadata(self) ->typing.Optional[typing.Dict]:\n return None if not self.stream_claim_info else self.stream_claim_info.claim.claim_dict['stream']['metadata']\n\n @property\n def blobs_completed(self) -> int:\n return sum([1 if self.blob_manager.get_blob(b.blob_hash).get_is_verified() else 0\n for b in self.descriptor.blobs[:-1]])\n\n @property\n def blobs_in_stream(self) -> int:\n return len(self.descriptor.blobs) - 1\n\n @property\n def sd_hash(self):\n return self.descriptor.sd_hash\n\n @property\n def blobs_remaining(self) -> int:\n return self.blobs_in_stream - self.blobs_completed\n\n def as_dict(self) -> typing.Dict:\n full_path = os.path.join(self.download_directory, self.file_name)\n if not os.path.isfile(full_path):\n full_path = None\n mime_type = guess_media_type(os.path.basename(self.file_name))\n\n if self.downloader and self.downloader.written_bytes:\n written_bytes = self.downloader.written_bytes\n elif full_path:\n written_bytes = os.stat(full_path).st_size\n else:\n written_bytes = None\n return {\n 'completed': self.finished,\n 'file_name': self.file_name,\n 'download_directory': self.download_directory,\n 'points_paid': 0.0,\n 'stopped': not self.running,\n 'stream_hash': self.stream_hash,\n 'stream_name': self.descriptor.stream_name,\n 'suggested_file_name': self.descriptor.suggested_file_name,\n 'sd_hash': self.descriptor.sd_hash,\n 'download_path': full_path,\n 'mime_type': mime_type,\n 'key': self.descriptor.key,\n 'total_bytes_lower_bound': self.descriptor.lower_bound_decrypted_length(),\n 'total_bytes': self.descriptor.upper_bound_decrypted_length(),\n 'written_bytes': written_bytes,\n 'blobs_completed': self.blobs_completed,\n 'blobs_in_stream': self.blobs_in_stream,\n 'blobs_remaining': self.blobs_remaining,\n 'status': self.status,\n 'claim_id': self.claim_id,\n 'txid': self.txid,\n 'nout': self.nout,\n 'outpoint': self.outpoint,\n 'metadata': self.metadata,\n 'channel_claim_id': self.channel_claim_id,\n 'channel_name': self.channel_name,\n 'claim_name': self.claim_name\n }\n\n @classmethod\n async def create(cls, loop: asyncio.BaseEventLoop, blob_manager: 'BlobFileManager',\n file_path: str, key: typing.Optional[bytes] = None,\n iv_generator: typing.Optional[typing.Generator[bytes, None, None]] = None) -> 'ManagedStream':\n descriptor = await StreamDescriptor.create_stream(\n loop, blob_manager.blob_dir, file_path, key=key, iv_generator=iv_generator\n )\n sd_blob = blob_manager.get_blob(descriptor.sd_hash)\n await blob_manager.storage.store_stream(\n blob_manager.get_blob(descriptor.sd_hash), descriptor\n )\n await blob_manager.blob_completed(sd_blob)\n for blob in descriptor.blobs[:-1]:\n await blob_manager.blob_completed(blob_manager.get_blob(blob.blob_hash, blob.length))\n await blob_manager.set_should_announce(sd_blob.blob_hash, 1)\n await blob_manager.set_should_announce(descriptor.blobs[0].blob_hash, 1)\n return cls(loop, blob_manager, descriptor, os.path.dirname(file_path), os.path.basename(file_path),\n status=cls.STATUS_FINISHED)\n\n def start_download(self, node: typing.Optional['Node']):\n self.downloader.download(node)\n self.update_status(self.STATUS_RUNNING)\n\n def stop_download(self):\n if self.downloader:\n self.downloader.stop()\n if not self.finished:\n self.update_status(self.STATUS_STOPPED)\n\n async def upload_to_reflector(self, host: str, port: int) -> typing.List[str]:\n sent = []\n protocol = StreamReflectorClient(self.blob_manager, self.descriptor)\n try:\n await self.loop.create_connection(lambda: protocol, host, port)\n await protocol.send_handshake()\n sent_sd, needed = await protocol.send_descriptor()\n if sent_sd:\n sent.append(self.sd_hash)\n if not sent_sd and not needed:\n if not self.fully_reflected.is_set():\n self.fully_reflected.set()\n await self.blob_manager.storage.update_reflected_stream(self.sd_hash, f\"{host}:{port}\")\n return []\n we_have = [blob_hash for blob_hash in needed if blob_hash in self.blob_manager.completed_blob_hashes]\n for blob_hash in we_have:\n await protocol.send_blob(blob_hash)\n sent.append(blob_hash)\n except (asyncio.CancelledError, asyncio.TimeoutError, ValueError):\n return sent\n except ConnectionRefusedError:\n return sent\n finally:\n if protocol.transport:\n protocol.transport.close()\n if not self.fully_reflected.is_set():\n self.fully_reflected.set()\n await self.blob_manager.storage.update_reflected_stream(self.sd_hash, f\"{host}:{port}\")\n return sent\n\n def set_claim(self, claim_info: typing.Dict, claim: 'ClaimDict'):\n self.stream_claim_info = StoredStreamClaim(\n self.stream_hash, f\"{claim_info['txid']}:{claim_info['nout']}\", claim_info['claim_id'],\n claim_info['name'], claim_info['amount'], claim_info['height'],\n binascii.hexlify(claim.serialized).decode(), claim.certificate_id, claim_info['address'],\n claim_info['claim_sequence'], claim_info.get('channel_name')\n )\n","sub_path":"lbrynet/stream/managed_stream.py","file_name":"managed_stream.py","file_ext":"py","file_size_in_byte":8932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"83660998","text":"from data.portalSpawn import portal_spawn\nfrom data.portal import Portal\nimport random\nfrom data.skullclass import SkullBadGuy\nfrom data.ogreclass import OgreBadGuy\n\n\ndef portal_collision(player, shots, portal, portals, bones, skeletons, hearts, ogres):\n if player.collision(portal):\n collide = True\n if portal.wall == \"up\":\n portals.remove(portal)\n player.rect.y = 350\n player.rect.x = 382.5\n portals.clear()\n shots.clear()\n portal_spawn(portals)\n portal = Portal(\"down\")\n portal.goto(3)\n portals.append(portal)\n collided = True\n elif portal.wall == \"down\":\n portals.remove(portal)\n player.rect.y = 110\n player.rect.x = 382.5\n portals.clear()\n shots.clear()\n portal_spawn(portals)\n portal = Portal(\"up\")\n portal.goto(1)\n portals.append(portal)\n collided = True\n elif portal.wall == \"left\":\n portals.remove(portal)\n player.rect.x = 120\n player.rect.y = 227\n portals.clear()\n shots.clear()\n portal_spawn(portals)\n portal = Portal(\"right\")\n portal.goto(2)\n portals.append(portal)\n collided = True\n elif portal.wall == \"right\":\n portals.remove(portal)\n player.rect.x = 650\n player.rect.y = 227\n portal_spawn(portals)\n portal = Portal(\"left\")\n portal.goto(4)\n portals.append(portal)\n collided = True\n else:\n collided = False\n if collided:\n shots.clear()\n bones.clear()\n hearts.clear()\n\n loops = random.randint(1, 3)\n for i in range(loops):\n skeleton = SkullBadGuy()\n skeletons.append(skeleton)\n\n loops = random.randint(1, 2)\n for i in range(loops):\n ogre = OgreBadGuy()\n ogres.append(ogre)\n\n if collide:\n return True\n else:\n return False\n","sub_path":"data/portalCollision.py","file_name":"portalCollision.py","file_ext":"py","file_size_in_byte":2188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"329943272","text":"import os\nfrom dataclasses import dataclass, field\nfrom typing import Dict, Iterable, List, Optional, Tuple\n\nimport pydantic\nfrom azure.storage.filedatalake import FileSystemClient, PathProperties\nfrom iceberg.core.filesystem.abfss_filesystem import AbfssFileSystem\nfrom iceberg.core.filesystem.filesystem_tables import FilesystemTables\nfrom pydantic import Field, root_validator\n\nfrom datahub.configuration.common import (\n AllowDenyPattern,\n ConfigModel,\n ConfigurationError,\n)\nfrom datahub.configuration.source_common import DatasetSourceConfigMixin\nfrom datahub.ingestion.source.azure.azure_common import AdlsSourceConfig\nfrom datahub.ingestion.source.state.stale_entity_removal_handler import (\n StaleEntityRemovalSourceReport,\n StatefulStaleMetadataRemovalConfig,\n)\nfrom datahub.ingestion.source.state.stateful_ingestion_base import (\n StatefulIngestionConfigBase,\n)\nfrom datahub.ingestion.source_config.operation_config import (\n OperationConfig,\n is_profiling_enabled,\n)\n\n\nclass IcebergProfilingConfig(ConfigModel):\n enabled: bool = Field(\n default=False,\n description=\"Whether profiling should be done.\",\n )\n include_field_null_count: bool = Field(\n default=True,\n description=\"Whether to profile for the number of nulls for each column.\",\n )\n include_field_min_value: bool = Field(\n default=True,\n description=\"Whether to profile for the min value of numeric columns.\",\n )\n include_field_max_value: bool = Field(\n default=True,\n description=\"Whether to profile for the max value of numeric columns.\",\n )\n operation_config: OperationConfig = Field(\n default_factory=OperationConfig,\n description=\"Experimental feature. To specify operation configs.\",\n )\n # Stats we cannot compute without looking at data\n # include_field_mean_value: bool = True\n # include_field_median_value: bool = True\n # include_field_stddev_value: bool = True\n # include_field_quantiles: bool = False\n # include_field_distinct_value_frequencies: bool = False\n # include_field_histogram: bool = False\n # include_field_sample_values: bool = True\n\n\nclass IcebergSourceConfig(StatefulIngestionConfigBase, DatasetSourceConfigMixin):\n # Override the stateful_ingestion config param with the Iceberg custom stateful ingestion config in the IcebergSourceConfig\n stateful_ingestion: Optional[StatefulStaleMetadataRemovalConfig] = pydantic.Field(\n default=None, description=\"Iceberg Stateful Ingestion Config.\"\n )\n adls: Optional[AdlsSourceConfig] = Field(\n default=None,\n description=\"[Azure Data Lake Storage](https://docs.microsoft.com/en-us/azure/storage/blobs/data-lake-storage-introduction) to crawl for Iceberg tables. This is one filesystem type supported by this source and **only one can be configured**.\",\n )\n localfs: Optional[str] = Field(\n default=None,\n description=\"Local path to crawl for Iceberg tables. This is one filesystem type supported by this source and **only one can be configured**.\",\n )\n max_path_depth: int = Field(\n default=2,\n description=\"Maximum folder depth to crawl for Iceberg tables. Folders deeper than this value will be silently ignored.\",\n )\n table_pattern: AllowDenyPattern = Field(\n default=AllowDenyPattern.allow_all(),\n description=\"Regex patterns for tables to filter in ingestion.\",\n )\n user_ownership_property: Optional[str] = Field(\n default=\"owner\",\n description=\"Iceberg table property to look for a `CorpUser` owner. Can only hold a single user value. If property has no value, no owner information will be emitted.\",\n )\n group_ownership_property: Optional[str] = Field(\n default=None,\n description=\"Iceberg table property to look for a `CorpGroup` owner. Can only hold a single group value. If property has no value, no owner information will be emitted.\",\n )\n profiling: IcebergProfilingConfig = IcebergProfilingConfig()\n\n def is_profiling_enabled(self) -> bool:\n return self.profiling.enabled and is_profiling_enabled(\n self.profiling.operation_config\n )\n\n @root_validator()\n def _ensure_one_filesystem_is_configured(\n cls: \"IcebergSourceConfig\", values: Dict\n ) -> Dict:\n if values.get(\"adls\") and values.get(\"localfs\"):\n raise ConfigurationError(\n \"Only one filesystem can be configured: adls or localfs\"\n )\n elif not values.get(\"adls\") and not values.get(\"localfs\"):\n raise ConfigurationError(\n \"One filesystem (adls or localfs) needs to be configured.\"\n )\n return values\n\n @property\n def adls_filesystem_client(self) -> FileSystemClient:\n \"\"\"Azure Filesystem client if configured.\n\n Raises:\n ConfigurationError: If ADLS is not configured.\n\n Returns:\n FileSystemClient: Azure Filesystem client instance to access storage account files and folders.\n \"\"\"\n if self.adls: # TODO Use local imports for abfss\n AbfssFileSystem.get_instance().set_conf(self.adls.dict())\n return self.adls.get_filesystem_client()\n raise ConfigurationError(\"No ADLS filesystem client configured\")\n\n @property\n def filesystem_tables(self) -> FilesystemTables:\n \"\"\"Iceberg FilesystemTables abstraction to access tables on a filesystem.\n Currently supporting ADLS (Azure Storage Account) and local filesystem.\n\n Raises:\n ConfigurationError: If no filesystem was configured.\n\n Returns:\n FilesystemTables: An Iceberg FilesystemTables abstraction instance to access tables on a filesystem\n \"\"\"\n if self.adls:\n return FilesystemTables(self.adls.dict())\n elif self.localfs:\n return FilesystemTables()\n raise ConfigurationError(\"No filesystem client configured\")\n\n def _get_adls_paths(self, root_path: str, depth: int) -> Iterable[Tuple[str, str]]:\n if self.adls and depth < self.max_path_depth:\n sub_paths = self.adls_filesystem_client.get_paths(\n path=root_path, recursive=False\n )\n sub_path: PathProperties\n for sub_path in sub_paths:\n if sub_path.is_directory:\n dataset_name = \".\".join(\n sub_path.name[len(self.adls.base_path) + 1 :].split(\"/\")\n )\n yield self.adls.get_abfss_url(sub_path.name), dataset_name\n yield from self._get_adls_paths(sub_path.name, depth + 1)\n\n def _get_localfs_paths(\n self, root_path: str, depth: int\n ) -> Iterable[Tuple[str, str]]:\n if self.localfs and depth < self.max_path_depth:\n for f in os.scandir(root_path):\n if f.is_dir():\n dataset_name = \".\".join(f.path[len(self.localfs) + 1 :].split(\"/\"))\n yield f.path, dataset_name\n yield from self._get_localfs_paths(f.path, depth + 1)\n\n def get_paths(self) -> Iterable[Tuple[str, str]]:\n \"\"\"Generates a sequence of data paths and dataset names.\n\n Raises:\n ConfigurationError: If no filesystem configured.\n\n Yields:\n Iterator[Iterable[Tuple[str, str]]]: A sequence of tuples where the first item is the location of the dataset\n and the second item is the associated dataset name.\n \"\"\"\n if self.adls:\n yield from self._get_adls_paths(self.adls.base_path, 0)\n elif self.localfs:\n yield from self._get_localfs_paths(self.localfs, 0)\n else:\n raise ConfigurationError(\"No filesystem client configured\")\n\n\n@dataclass\nclass IcebergSourceReport(StaleEntityRemovalSourceReport):\n tables_scanned: int = 0\n entities_profiled: int = 0\n filtered: List[str] = field(default_factory=list)\n\n def report_table_scanned(self, name: str) -> None:\n self.tables_scanned += 1\n\n def report_dropped(self, ent_name: str) -> None:\n self.filtered.append(ent_name)\n","sub_path":"metadata-ingestion/src/datahub/ingestion/source/iceberg/iceberg_common.py","file_name":"iceberg_common.py","file_ext":"py","file_size_in_byte":8173,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"310092476","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\n@author: erigara\n\nModule provide postprocessing functions\n\"\"\"\n\ndef truncate_rating(data, lower_bound, upper_bound):\n \"\"\"\n Set values in column predictions so that every value lower_bound <= value <= upper_bound\n \n data : RatingData\n rating data\n \n lower_bound : float\n smallest possible rating\n \n upper_bound : float\n biggest possible rating\n \n return : RatingData\n return RatingData where every rating in col prediction\n = rating if lower_bound <= rating <= upper_bound\n = lower_bound if lower_bound > rating\n = upper_bound if rating > upper_bound\n \"\"\"\n ratings = data.df[data.prediction_col_name].to_numpy()\n lower = ratings < lower_bound\n ratings[lower] = lower_bound\n higher = ratings > upper_bound\n ratings[higher] = upper_bound\n data.df[data.prediction_col_name] = ratings\n return data","sub_path":"utils/postprocessing.py","file_name":"postprocessing.py","file_ext":"py","file_size_in_byte":1207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"375989896","text":"def caesar_cipher(s, k):\n # String to shift\n #s = sys.argv[1]\n # By value\n #k = int(sys.argv[2])\n\n if k < 0 or k > 100:\n print(\"Invalid rotation integer. Please enter a number between 0 and 100\")\n exit()\n\n if k >= 26:\n k = k % 26\n\n newString = ''\n\n for i in s:\n if not i.isalpha():\n newString = newString + i\n else:\n letterChar = ord(i)\n\n shift = letterChar + k\n\n if shift > 122:\n shift = shift - 26\n\n newString = newString + chr(shift)\n\n return newString\n","sub_path":"caesar_cipher.py","file_name":"caesar_cipher.py","file_ext":"py","file_size_in_byte":588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"74249462","text":"class Tickets:\n def __init__(self, id, event_id, name, price, data ):\n self.id = id\n self.event_id = event_id\n self.name = name\n self.price = price\n self.data = data\n\nclass Events:\n def __init__(self, id, image, name, category, data, time):\n self.id = id\n self.image = image\n self.name = name\n self.category = category\n self.data = data\n self.time = time\n","sub_path":"app/domain.py","file_name":"domain.py","file_ext":"py","file_size_in_byte":438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"160311274","text":"import pickle\nimport cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nimport glob\nimport os\n\ndef cal_undistort(img, objpoints, imgpoints):\n ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, img.shape[1:], None, None)\n undist = cv2.undistort(img, mtx, dist, None, mtx)\n return undist\n\n\nif __name__ == '__main__':\n # prepare object points\n nx = 9 # number of inside corners in x\n ny = 6 # number of inside corners in y\n objpoints = []\n objp = np.zeros((nx*ny, 3), np.float32)\n objp[:,:2] = np.mgrid[0:nx, 0:ny].T.reshape(-1,2)\n objpoints.append(objp)\n\n # Make a list of calibration images\n images = glob.glob('camera_cal/calibration3.jpg')\n for idx, image in enumerate(images):\n imgpoints = []\n img = cv2.imread(image)\n # Convert to grayscale\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\n # # Find the chessboard corners\n ret, corners = cv2.findChessboardCorners(gray, (nx, ny), None)\n\n # # If found, draw corners\n if ret == True:\n # Draw and display the corners\n imgpoints.append(corners)\n # cv2.drawChessboardCorners(img, (nx, ny), corners, ret)\n undistorted = cal_undistort(img, objpoints, imgpoints)\n f, (ax1, ax2) = plt.subplots(1, 2, figsize=(24, 9))\n f.tight_layout()\n ax1.imshow(img)\n ax1.set_title('Original Image', fontsize=50)\n # ax1.show()\n ax2.imshow(undistorted)\n ax2.set_title('Undistorted Image', fontsize=50)\n # ax2.show()\n plt.subplots_adjust(left=0., right=1, top=0.9, bottom=0.)\n plt.show()\n print(\"../output_images/chess_{}\".format(os.path.basename(image)))\n plt.savefig(\"../output_images/chess_{}\".format(os.path.basename(image)))\n else:\n print(\"Ret: False\", image)","sub_path":"first_calib.py","file_name":"first_calib.py","file_ext":"py","file_size_in_byte":1938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"485175209","text":"import os\nimport tempfile\nfrom pathlib import Path\n\nfrom homework9.task3 import universal_file_counter\n\n\ndef test_universal_file_counter_three_parameters():\n \"\"\"checks operation with three parameters\"\"\"\n with tempfile.TemporaryDirectory() as dir:\n for i in range(4):\n with open(os.path.join(dir, \"tmp\" + str(i) + \".txt\"), \"w\") as file:\n file.write(\"fg dfg dfg df\")\n cur_dir = Path(dir)\n assert universal_file_counter(cur_dir, \"txt\", str.split) == 16\n\n\ndef test_universal_file_counter_two_parameters():\n \"\"\"checks operation with two parameters\"\"\"\n with tempfile.TemporaryDirectory() as dir:\n for i in range(4):\n with open(os.path.join(dir, \"tmp\" + str(i) + \".txt\"), \"w\") as file:\n file.write(\"fg \\ndfg dfg df\\n\")\n cur_dir = Path(dir)\n assert universal_file_counter(cur_dir, \"txt\") == 8\n\n\ndef test_universal_file_counter_without_extension():\n \"\"\"a negative test checks that when working with files of another extension, zero is returned\"\"\"\n with tempfile.TemporaryDirectory() as dir:\n with open(os.path.join(dir, \"tmp\"), \"w\") as file:\n file.write(\"fg \\ndfg dfg df\\n\")\n cur_dir = Path(dir)\n assert not universal_file_counter(cur_dir, \"txt\") == 8\n","sub_path":"tests/homework9/test_hw9_task3.py","file_name":"test_hw9_task3.py","file_ext":"py","file_size_in_byte":1287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"447131512","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Mar 20 11:54:56 2021\n\n@author: dof\n\"\"\"\n\nimport math\n\nimport colour\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom matplotlib.colors import ListedColormap\nfrom scipy import ndimage\nfrom scipy.signal import savgol_filter\n\n\n'''\nJ = lightness\nC = chroma\nh = hue\n'''\n\n# Resolution of colorspace\nJ_RES = 100000\nC_RES = 256\n\n# NAME = 'So normal'\n# ANGLE = np.pi * 2 * 0.7\n# OFFSET = np.pi * 2 * 0.64\n# CCW = False\n# SMOOTH = 1/3\n\n# NAME = 'Wow unique'\n# ANGLE = np.pi * 2 * 1.0\n# OFFSET = np.pi * 2 * 0.275\n# CCW = True\n# SMOOTH = 1/2\n\n# NAME = 'Viridis-like (red bg)'\n# ANGLE = np.pi * 2 * 1.0\n# OFFSET = np.pi * 2 * 0.1\n# CCW = True\n# SMOOTH = 1/4\n\n# NAME = 'Viridis-like (purple bg)'\n# ANGLE = np.pi * 2 * 0.9\n# OFFSET = np.pi * 2 * 0.1\n# CCW = True\n# SMOOTH = 1/5\n\nNAME = 'AudaSpec1+'\nANGLE = np.pi * 2 * 0.875\nOFFSET = np.pi * 2 * 0.5\nCCW = False\nSMOOTH = 1/3\n\nDESATURATE = 0.9\n\n\ndef cam16_to_srgb(jab):\n xyz = colour.CAM16UCS_to_XYZ(jab)\n rgb = colour.XYZ_to_sRGB(xyz)\n return rgb\n\n\ndef srgb_to_cam16(rgb):\n xyz = colour.sRGB_to_XYZ(rgb)\n jab = colour.XYZ_to_CAM16UCS(xyz)\n return jab\n\n\n# Generate CAM02-UCS(Jp, ap, bp) colorspace\nj_space = np.linspace(0.1, 99, J_RES)\nc_space = np.linspace(0, 50, C_RES)\n\nif CCW:\n h_ = np.linspace(ANGLE+OFFSET, OFFSET, J_RES)\nelse:\n h_ = np.linspace(OFFSET, ANGLE+OFFSET, J_RES)\nh_ = np.degrees(h_)\n\njch = np.zeros([C_RES, J_RES, 3])\njch[..., 0] = j_space\njch[..., 1] = np.expand_dims(c_space, 1)\njch[..., 2] = h_\njpapbp = colour.models.JCh_to_Jab(jch)\n\n# Convert to sRGB\nrgb = cam16_to_srgb(jpapbp)\n\n\n# Get chroma limit of sRGB\nc_limit = np.zeros_like(j_space)\nfor jdx in range(J_RES):\n max_cdx = 0\n for cdx in range(1, C_RES):\n if np.any(rgb[cdx, jdx] <= 0) or np.any(1 < rgb[cdx, jdx]):\n max_cdx = cdx - 1\n break\n \n c_limit[jdx] = max_cdx\n\n\n# Smooth chroma limit contour\nc_smoothed = np.concatenate([-c_limit[::-1][:-1], c_limit, -c_limit[::-1][1:]])\n\nc_smoothed = savgol_filter(c_smoothed, math.ceil(J_RES*SMOOTH*1.5/2)*2 - 1, 3)\nc_smoothed = ndimage.uniform_filter1d(c_smoothed, int(J_RES*SMOOTH*1.5/2)) * DESATURATE\n\nc_smoothed = c_smoothed[J_RES:2*J_RES]\n\nc_selected = c_smoothed.clip(min=0).astype(int)\n\n\n# Generate and plot gaumt\ngamut_image = np.copy(rgb)\ngamut_image[gamut_image<=0] = 1\ngamut_image[1>> crx_list = DownloadCRXList(download_url)\n >>> for crx_id in crx_list:\n ... print(crx_id)\n\n The list of CRXs will be downloaded just prior to when the first item is\n generated. In other words, instantiating this class doesn't start the\n download, iterating over the instance starts the download. This is\n significant given that downloading the list is quite time consuming.\n \"\"\"\n\n # Namespace tag used by the downloaded list (XML file)\n _ns = '{http://www.sitemaps.org/schemas/sitemap/0.9}'\n list_list_url = 'https://chrome.google.com/webstore/sitemap'\n\n def __init__(self, ext_url, *, return_count=False, session=None):\n \"\"\"\n :param str ext_url: Specially crafted URL that will let us download the\n list of extensions.\n :param bool return_count: When True, will return a tuple of the form:\n ``(crx_id, job_number)``, where ``job_number`` is the index of the\n ID plus 1. This way, the job number of the last ID returned will be\n the same as ``len(DownloadCRXList)``.\n :param requests.Session session: Session object to use when downloading\n the list. If None, a new :class:`requests.Session` object is\n created.\n \"\"\"\n self.ext_url = ext_url\n self.session = session if isinstance(session, requests.Session) else requests.Session()\n self._downloaded_list = False\n self.ret_tup = return_count # Return a tuple (CRX ID, num)\n self._id_list = []\n self._next_id_index = 0\n self.sitemap_dir = None\n\n def __iter__(self):\n if not self._downloaded_list:\n self.download_ids()\n # Reset the \"next ID\" index\n self._next_id_index = 0\n return self\n\n def __next__(self):\n try:\n crx_id = self._id_list[self._next_id_index]\n except IndexError:\n raise StopIteration\n\n self._next_id_index += 1\n return crx_id, self._next_id_index if self.ret_tup else crx_id\n\n def download_ids(self):\n \"\"\"Starting point for downloading all CRX IDs.\n\n This function actually creates an event loop and starts the downloads\n asynchronously.\n\n :rtype: None\n \"\"\"\n loop = asyncio.get_event_loop_policy().new_event_loop()\n with TemporaryDirectory() as self.sitemap_dir:\n loop.run_until_complete(self._async_download_lists())\n self._downloaded_list = True\n\n async def _async_download_lists(self):\n \"\"\"Download, loop through the list of lists, combine IDs from each.\n\n :rtype: None\n \"\"\"\n logging.info('Downloading the list of extension lists from Google.')\n\n # Download the first list\n resp = _http_get(self.list_list_url, self.session, stream=False, headers=make_download_headers())\n if resp is None:\n logging.critical('Failed to download list of extensions.')\n raise ListDownloadFailedError('Unable to download list of extensions.')\n\n # Save the list\n local_sitemap = TemporaryFile(dir=self.sitemap_dir)\n for chunk in resp.iter_content(chunk_size=None):\n local_sitemap.write(chunk)\n resp.close()\n\n # Go through the list, extracting list URLs\n ids = set()\n local_sitemap.seek(0)\n xml_tree = etree.parse(local_sitemap)\n num_lists = 0\n duplicate_count = 0\n for url_tag in xml_tree.iterfind('*/' + self._ns + 'loc'):\n # Download the URL, get the IDs from it and add them to the set of IDs\n try:\n _ids = await self._dl_parse_id_list(url_tag.text)\n except ListDownloadFailedError:\n # TODO: How to handle this?\n raise\n else:\n x = len(_ids)\n y = len(ids)\n ids |= _ids\n duplicate_count += (y + x) - len(ids)\n num_lists += 1\n\n logging.info('Done downloading. Doing some cleanup...')\n\n # Close (and delete) the temporary file where the list was stored\n local_sitemap.close()\n\n # Convert IDs to a list, then sort it\n self._id_list = list(ids)\n self._id_list.sort()\n if TESTING: # Truncate the list\n self._id_list = self._id_list[:TESTING]\n\n logging.warning('There were {} duplicate IDs from the {} lists.'.format(duplicate_count - len(self), num_lists))\n\n async def _dl_parse_id_list(self, list_url):\n \"\"\"Download the extension list at the given URL, return set of IDs.\n\n :param str list_url: URL of an individual extension list.\n :return: Set of CRX IDs.\n :rtype: set\n \"\"\"\n # Get info from the list URL to indicate our progress in the log message\n url_data = parse_qs(urlparse(list_url).query)\n numshards = url_data['numshards'][0]\n shard = int(url_data['shard'][0]) + 1\n log = logging.info if not shard % 100 or shard == int(numshards) else logging.debug\n shard = ('{:0' + str(len(numshards)) + '}').format(shard)\n _hl = hl = url_data.get('hl', '')\n if isinstance(_hl, list):\n hl = ' (language: {})'.format(_hl[0])\n _hl = '_{}'.format(_hl[0])\n list_id = '{} of {}{}'.format(shard, numshards, hl)\n sitemap = TemporaryFile(prefix='sitemap{}_{}_{}'.format(_hl, shard, numshards), suffix='.xml',\n dir=self.sitemap_dir)\n\n # Download the IDs list\n resp = _http_get(list_url, self.session, stream=False, headers=make_download_headers())\n if resp is None:\n msg = 'Failed to download extension list {}.'.format(list_id)\n logging.critical(msg)\n raise ListDownloadFailedError(msg)\n\n # Save the list\n for chunk in resp.iter_content(chunk_size=None):\n sitemap.write(chunk)\n resp.close()\n\n # Extract the IDs\n ids = set()\n sitemap.seek(0)\n xml_tree = etree.parse(sitemap)\n for url_tag in xml_tree.iterfind('*/' + self._ns + 'loc'):\n # Get just the URL path (strips the scheme, netloc, params, query, and fragment segments)\n crx_id = urlparse(url_tag.text).path\n # Get the ID (strips everything from the path except the last part)\n crx_id = path.basename(crx_id)\n ids.add(crx_id)\n log('Downloaded extension list {}. Qty: {}'.format(list_id, len(ids)))\n sitemap.close()\n\n return ids\n\n def __len__(self):\n return len(self._id_list)\n\n\ndef save_crx(crx_obj, download_url, save_path=None, session=None):\n \"\"\"Download the CRX, save in the ``save_path`` directory.\n\n The saved file will have the format: ``_.crx``\n\n If ``save_path`` isn't given, this will default to a directory called\n \"downloads\" in the CWD.\n\n Adds the following keys to ``crx_obj``:\n\n - ``version``: Version number of the extension, as obtained from the final\n URL of the download. This may differ from the version listed in the\n extension's manifest.\n - ``filename``: The basename of the CRX file (not the full path)\n - ``full_path``: The location (full path) of the downloaded CRX file\n\n :param crx_obj: Previously collected information about the extension.\n :type crx_obj: munch.Munch\n :param download_url: The URL template that already contains the correct\n Chrome version information and ``{}`` where the ID goes.\n :type download_url: str\n :param save_path: Directory where the CRX should be saved.\n :type save_path: str or None\n :param session: Optional :class:`~requests.Session` object to use for HTTP requests.\n :type session: requests.Session or None\n :return: Updated version of ``crx_obj`` with ``version``, ``filename``, and\n ``full_path`` information added. If the download wasn't successful, not\n all of these may have been added, depending on when it failed.\n :rtype: munch.Munch\n \"\"\"\n\n # Check that the ID has a valid form\n validate_crx_id(crx_obj.id)\n\n # Ensure the extension is still available in the Web Store\n url = CRX_URL % crx_obj.id\n resp = _http_get(url, session)\n _ensure_redirect(resp)\n resp.close()\n\n # If the URL we got back was the same one we requested, the download failed\n if url == resp.url:\n raise BadDownloadURL\n\n # Make the new request to actually download the extension\n resp = _http_get(download_url.format(crx_obj.id), session, stream=True)\n\n try:\n crx_obj.version = get_crx_version(resp.url.rsplit('extension', 1)[-1])\n except IndexError:\n raise VersionExtractError('{} Problem with extracting CRX version from URL\\n URL: {}\\n Split URL: {}'.\n format(crx_obj.id, resp.url, resp.url.rsplit('extension', 1)[-1]))\n crx_obj.filename = '{}_{}.crx'.format(crx_obj.id, crx_obj.version) # _\n\n if save_path is None:\n save_path = path.join('.', 'downloads')\n crx_obj.full_path = path.abspath(path.join(save_path, crx_obj.filename))\n\n if path.exists(crx_obj.full_path):\n err = FileExistsError()\n err.errno = ''\n err.strerror = 'Cannot save CRX to path that already exists'\n err.filename = crx_obj.full_path\n raise err\n\n with open(crx_obj.full_path, 'wb') as fout:\n # Write the binary response to the file 512 bytes at a time\n for chunk in resp.iter_content(chunk_size=512):\n fout.write(chunk)\n resp.close()\n\n return crx_obj\n\n\ndef _ensure_redirect(resp):\n \"\"\"Check that a redirect occurred.\n\n :param resp: The response object from GET-ting the extension's URL.\n :type resp: requests.Response\n :return: None\n :rtype: None\n \"\"\"\n if not len(resp.history):\n raise ExtensionUnavailable('No redirect occurred while fetching URL %s' % resp.url)\n\n\nclass RetryRequest:\n \"\"\"Wraps functions that make HTTP requests, retries on failure.\"\"\"\n\n def __init__(self, f):\n self.f = f\n\n def __call__(self, *args, **kwargs):\n resp = None\n for i in range(NUM_HTTP_RETIRES):\n try:\n resp = self.f(*args, **kwargs)\n resp.raise_for_status() # If there was an HTTP error, raise it\n except (ChunkedEncodingError, ConnectionError, HTTPError):\n # TODO: Are there other errors we could get that we want to retry after?\n logging.debug('Encountered error while downloading. Attempting to sleep and retry ({} of {} retries)'.\n format(i+1, NUM_HTTP_RETIRES))\n sleep(10 * (i+1))\n else:\n break\n return resp\n\n\n@RetryRequest\ndef _http_get(url, session=None, stream=True, **kwargs):\n \"\"\"Make a GET request with the URL.\n\n Any errors from the HTTP request (non 200 codes) will raise an HTTPError.\n\n :param url: The URL to GET.\n :type url: str\n :param session: Optional :class:`~requests.Session` object to use to make\n the GET request.\n :type session: requests.Session or None\n :param stream: If `False`, the response content will be immediately\n downloaded.\n :type stream: bool\n :param kwargs: Optional arguments that :func:`requests.get` takes.\n :type kwargs: dict\n :return: The :class:`~requests.Response` object containing the server's\n response to the HTTP request.\n :rtype: requests.Response\n \"\"\"\n if isinstance(session, requests.Session):\n return session.get(url, stream=stream, **kwargs)\n else:\n return requests.get(url, stream=stream, **kwargs)\n","sub_path":"crawl/webstore_iface.py","file_name":"webstore_iface.py","file_ext":"py","file_size_in_byte":13336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"229470609","text":"import cv2\r\nimport numpy as np\r\nimport face_recognition\r\nimport os\r\nimport pickle\r\nfrom tkinter import messagebox,simpledialog\r\n\r\n\r\npath=\"staticnew\"\r\nmyimages=[]\r\nnewlist=[]\r\n\r\nnewclassname=[]\r\nmylist=os.listdir(path)\r\nmessagebox.showinfo(\"model training detected\",\"model is updating ,please wait for completion\")\r\nwith open('classname.dat', 'rb') as f:\r\n oldclassname = pickle.load(f)\r\nprint(\"updating classnames.....\")\r\nfor fn in mylist:\r\n extlist=[\"jpg\",\"jpeg\"]\r\n cl=fn.split(\".\")[0]\r\n ext=fn.split(\".\")[1]\r\n if (cl not in oldclassname) and ext in extlist:\r\n newlist.append(fn)\r\nprint(\"getting new cv_images.......\")\r\nfor cl in newlist:\r\n curimg=cv2.imread(f\"{path}/{cl}\")\r\n myimages.append(curimg)\r\n newclassname.append(cl.split(\".\")[0])\r\n\r\ndef findencodings(images):\r\n encodelist=[]\r\n for img in images:\r\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\r\n encode=face_recognition.face_encodings(img)[0]\r\n encodelist.append(encode)\r\n\r\n return encodelist\r\nprint(\"Finding encodings.......\")\r\nnewknown = findencodings(myimages)\r\nprint(\"encoding done.......\")\r\nprint(\"updating datas.......\")\r\nwith open('dataset_faces.dat', 'rb') as f:\r\n oldknown = pickle.load(f)\r\nfor en in newknown:\r\n oldknown.append(en)\r\nfor ncl in newclassname:\r\n oldclassname.append(ncl)\r\n\r\nprint(\"uploaing updates.......\")\r\nwith open('classname.dat', 'wb') as f:\r\n pickle.dump(oldclassname, f)\r\nwith open('dataset_faces.dat', 'wb') as f:\r\n pickle.dump(oldknown, f)\r\nprint(\"Successfully data updated.......\")\r\nprint(len(oldclassname), len(oldknown))\r\nprint(\"newly added faces : \", len(newclassname), newclassname)\r\nmessagebox.showinfo(\"model updated\",\"sucessfully model updated.\\n \"+str(len(newclassname))+\" Face added\\n Newly added faces\"+str(newclassname))\r\n\r\n\r\n","sub_path":"GUI/update_model.py","file_name":"update_model.py","file_ext":"py","file_size_in_byte":1807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"508610801","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nimport os\n\nos.chdir(\"C:\\\\Users\\\\Lenovo\\\\Documents\\\\Python\\\\Tugas Regresi (weatherww2)\")\n\n\n# In[2]:\n\n\n#import data\ndf = pd.read_csv(\"Summary of Weather.csv\")\ndf.head()\n\n\n# In[3]:\n\n\ndf=df.drop(['FT','FB','FTI','ITH','SD3','RHX','RHN','RVG','WTE'], axis=1)\ndf=df.drop(['WindGustSpd','PoorWeather','DR','SPD','SND','PGT','TSHDSBRSGF'], axis=1)\ndf= df.drop(['STA','Date','YR','MO','DA'], axis=1)\n\n\n# In[4]:\n\n\ndf.isnull().sum()\n\n\n# In[5]:\n\n\nimport numpy as np\n\n\n# In[6]:\n\n\ndf['Precip']= df['Precip'].replace('T', np.nan)\ndf['PRCP']= df['PRCP'].replace('T', np.nan)\ndf['SNF']= df['SNF'].replace('T', np.nan)\ndf['Snowfall']= df['Snowfall'].replace('#VALUE!', np.nan)\n\n\n# In[7]:\n\n\ndf.isnull().sum()\n\n\n# In[8]:\n\n\ndf.info()\n\n\n# In[9]:\n\n\ndf['Precip']=df['Precip'].astype('float')\ndf['PRCP']=df['PRCP'].astype('float')\ndf['SNF']=df['SNF'].astype('float')\ndf['Snowfall']=df['Snowfall'].astype('float')\n\n\n# ## Fillna diganti dengan Median\n\n# In[10]:\n\n\ndf['Precip'] = df['Precip'].fillna((df['Precip'].median()))\ndf['Snowfall'] = df['Snowfall'].fillna((df['Snowfall'].median()))\ndf['PRCP'] = df['PRCP'].fillna((df['PRCP'].median()))\ndf['MAX'] = df['MAX'].fillna((df['MAX'].median()))\ndf['MIN'] = df['MIN'].fillna((df['MIN'].median()))\ndf['MEA'] = df['MEA'].fillna((df['MEA'].median()))\ndf['SNF'] = df['SNF'].fillna((df['SNF'].median()))\n\n\n# In[11]:\n\n\nprint(df.shape)\ndf.head()\n\n\n# In[12]:\n\n\nPrecip = df['Precip'].values\nMaxTemp = df['MaxTemp'].values\nMinTemp = df['MinTemp'].values\nMeanTemp = df['MeanTemp'].values\nSnowfall = df['Snowfall'].values\nPRCP = df['PRCP'].values\nMAX = df['MAX'].values\nMIN = df['MIN'].values\nMEA = df['MEA'].values\nSNF = df['SNF'].values\n\n\n# In[13]:\n\n\nm = len(MaxTemp)\nx0 = np.ones(m)\nX = np.array([x0, MaxTemp, MinTemp, MeanTemp, Snowfall, PRCP, MAX, MIN, MEA, SNF]).T\n# Initial Coefficients\nB = np.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])\nY = np.array(Precip)\nalpha = 0.0001\n\n\n# In[14]:\n\n\ndef cost_function(X, Y, B):\n m = len(Y)\n J = np.sum((X.dot(B) - Y) ** 2)/(2 * m)\n return J\n\n\n# In[15]:\n\n\ninital_cost = cost_function(X, Y, B)\nprint(inital_cost)\n\n\n# In[16]:\n\n\ndef gradient_descent(X, Y, B, alpha, iterations):\n cost_history = [0] * iterations\n m = len(Y)\n \n for iteration in range(iterations):\n # Hypothesis Values\n h = X.dot(B)\n # Difference b/w Hypothesis and Actual Y\n loss = h - Y\n # Gradient Calculation\n gradient = X.T.dot(loss) / m\n # Changing Values of B using Gradient\n B = B - alpha * gradient\n # New Cost Value\n cost = cost_function(X, Y, B)\n cost_history[iteration] = cost\n \n return B, cost_history\n\n\n# In[17]:\n\n\n# 100000 Iterations\nnewB, cost_history = gradient_descent(X, Y, B, alpha, 100000)\n\n# New Values of B\nprint(newB)\n\n# Final Cost of new B\nprint(cost_history[-1])\n\n\n# In[18]:\n\n\n# Model Evaluation - RMSE\ndef rmse(Y, Y_pred):\n rmse = np.sqrt(sum((Y - Y_pred) ** 2) / len(Y))\n return rmse\n\n# Model Evaluation - R2 Score\ndef r2_score(Y, Y_pred):\n mean_y = np.mean(Y)\n ss_tot = sum((Y - mean_y) ** 2)\n ss_res = sum((Y - Y_pred) ** 2)\n r2 = 1 - (ss_res / ss_tot)\n return r2\n\nY_pred = X.dot(newB)\n\nprint(rmse(Y, Y_pred))\nprint(r2_score(Y, Y_pred))\n\n\n# ## Perbandingan dengan menggunakan Scikit Learn\n\n# In[19]:\n\n\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.metrics import mean_squared_error\n\n# X and Y Values\nX2 = np.array([MaxTemp, MinTemp, MeanTemp, Snowfall, PRCP, MAX, MIN, MEA, SNF ]).T\nY2 = np.array(Precip)\n\n# Model Intialization\nreg = LinearRegression()\n# Data Fitting\nreg = reg.fit(X2, Y2)\n# Y Prediction\nY_pred = reg.predict(X2)\n\n# Model Evaluation\nrmse = np.sqrt(mean_squared_error(Y2, Y_pred))\nr2 = reg.score(X2, Y2)\n\nprint(rmse)\nprint(r2)\n\n","sub_path":"nyong/Multiple Linear Regression replace median.py","file_name":"Multiple Linear Regression replace median.py","file_ext":"py","file_size_in_byte":3891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"157890877","text":"class Solution(object):\n def fourSum(self, nums, target):\n \"\"\"\n :type nums: List[int]\n :type target: int\n :rtype: List[List[int]]\n \"\"\"\n result = []\n sum_of_2_d = {}\n\n nums.sort()\n\n for i in range(0, len(nums)):\n for j in range(i + 1, len(nums)):\n sum2 = nums[i] + nums[j]\n\n if sum2 in sum_of_2_d:\n sum_of_2_d[sum2].append([i, j])\n else:\n sum_of_2_d[sum2] = [[i, j]]\n\n\n for i in range(0, len(nums)):\n for j in range(len(nums) - 1, i + 1, -1):\n sum2 = nums[i] + nums[j]\n left = target - sum2\n\n if left in sum_of_2_d:\n for item in sum_of_2_d[left]:\n if (item[0] > i and item[1] < j):\n temp = [nums[item[0]], nums[item[1]], nums[i], nums[j]]\n if temp not in result:\n result.append(temp)\n return result\n\nSolution().fourSum([-3,-2,-1,0,0,1,2,3], 0)\n","sub_path":"n18.py","file_name":"n18.py","file_ext":"py","file_size_in_byte":1100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"581279170","text":"#coding utf-8\n\nfrom tkinter import *\nimport tkinter.simpledialog as sr\nimport tkinter.messagebox as xx\n\nroot = Tk()\na = Label(root,text = \"叫什么游戏好呢?\")\na.pack()\nxx.showinfo(\"弹个小窗口\",\"然后告诉你,欢迎来到王者荣耀游戏大本营!\")\n\nid = 821 \t\t\t\t #设置被猜数值\nnum = 10 \t\t\t\t #程序循环次数\nfor i in range(1,num + 1): #for的循环,每次都将i值输出,告诉用户现在的次数\n\toutput = (\"总共10次机会,你现在是第\" + str(i) + \"次机会\")\n\txx.showinfo(\"警告,bibo\",output)\n\twhile True: #将while值设置为true,一直执行while语句,直到跳出\n\t\ttry: #对用户输入的值进行判断,如果用户输入数非整数则执行except\n\t\t\tuser = sr.askinteger('这是游戏,请认真对待。',\"请输入你认为正确的值(整数噢!)\")\n\t\t\tbreak\n\t\texcept values:\n\t\t\toutput = (\"叫你输入数字,你就好好输!!!\")\n\t\t\txx.showinfo(\"警告!\",output)\n\tif user == id: #输入值与被猜数字进行比较,然后输出相应的结果\n\t\toutput = (\"哎哟喂。你是天才么,居然猜中了,可惜没有奖励哈!\")\n\t\txx.showinfo(\"恭喜\",output)\n\t\tbreak\n\telif user > id:\n\t\toutput = (\"你输入的值太big_big_big了,请重输!\")\n\t\txx.showinfo(\"呆子\",output)\n\telse:\n\t\toutput = (\"你输入的值太小了,请重输!\")\n\t\txx.showinfo(\"呆子\",output)\noutput = (\"游戏结束\")\nxx.showinfo(\"bibo!\",output)\n","sub_path":"Other/tkinter.py","file_name":"tkinter.py","file_ext":"py","file_size_in_byte":1611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"166363506","text":"#Electrical BS7671 Formula classes\r\n#BS7671:2018\r\n#Author: David Wigley\r\n#Version: 1.0 draft\r\nfrom math import sqrt, cos, sin, radians\r\n#import math\r\nclass CableCalc():\r\n\t\"\"\"Cable calculations for me\"\"\"\r\n\t\r\n\r\n\tdef __init__(self, n = 1, tp = 1,\r\n\t\t\t\t\tca = 1, cs = 1, cd = 1, \r\n\t\t\t\t\tib = 1, it = 1, ifun = 1, \r\n\t\t\t\t\th3 = 1, h5 = 1, h7 = 1, \r\n\t\t\t\t\th9 = 1, ci = 1, cf = 1,\r\n\t\t\t\t\tcc =1, inom = 1, pf = 1,\r\n\t\t\t\t\tmvamr = 0, mvamx = 0\r\n\t\t\t\t):\r\n\t\t\"\"\"Initialize cable variables\"\"\"\r\n\t\t\r\n\t\t\r\n\t\tself.n = n \r\n\t\tself.Cg = 1\r\n\t\tself.Tp = tp\r\n\t\tself.Ca = ca\r\n\t\tself.Cs = cs\r\n\t\tself.Cd = cd\r\n\t\tself.Ides = ib\r\n\t\tself.It = it\r\n\t\tself.Ct = 1\r\n\t\tself.Ch = 1\r\n\t\tself.Ifun = ifun\r\n\t\tself.h3 = h3\r\n\t\tself.h5 = h5\r\n\t\tself.h7 = h7\r\n\t\tself.h9 = h9\r\n\t\tself.Ci = ci\r\n\t\tself.Cf = cf\r\n\t\tself.Cc = cc\r\n\t\tself.In = inom\r\n\t\tself.Eq2 = 1\r\n\t\tself.Eq3 = 1\r\n\t\tself.Eq4 = 1\r\n\t\tself.Pf = pf\r\n\t\tself.mVAmr = mvamr\r\n\t\tself.mVAmx = mvamx\r\n\t\tself.mVAmz = 1\r\n\t\t\r\n\tdef cg(self):\r\n\t\t\"\"\"Number of circuits in the group Clause 2.3.3.1 Page 375 Groups in conduit Systems, cable trunking systems or cable ducting systems\"\"\"\t\r\n\t\tself.Cg = 1/sqrt(self.n)\r\n\t\treturn self.Cg\r\n\t\t\r\n\tdef it_single_ccts(self):\r\n\t\t\"\"\"Clause 5.1.1 page 377 determination of the size of cable to be used for single circuits\"\"\"\r\n\t\tself.It = self.In/(self.Ca * self.Cs * self.Cd * self.Ci * self.Cf * self.Cc)\r\n\t\treturn self.It\r\n\t\t\r\n\tdef it_groups(self):\r\n\t\t\"\"\"Clause 5.1.2 page 378 determination of the size of cable to be used for groups of circuits\"\"\"\r\n\t\t\t\t\r\n\t\tself.Eq2 = self.In/(self.Cg * self.Ca * self.Cs * self.Cd * self.Ci * self.Cf * self.Cc)\r\n\t\t\r\n\t\tself.Eq3 = self.Ides/(self.Cg * self.Ca * self.Cs * self.Cd * self.Ci * self.Cf * self.Cc)\r\n\r\n\t\tself.Eq4 = (1/(self.Ca * self.Cs * self.Cd * self.Ci )) * (sqrt((self.In/(self.Cf * self.Cc))**2 + 0.48 * self.Ides**2 * ((1 - self.Cg**2)/self.Cg**2)) )\r\n\t\t\r\n\t\t# Which equation gives the highest result\r\n\t\tself.It = max(self.Eq2, self.Eq3, self.Eq4)\r\n\t\treturn self.It\r\n\t\t\r\n\tdef it_no_overload(self):\r\n\t\t\"\"\"Clause 5.2 Page 378 Where no overload protection is required\"\"\"\r\n\t\tself.It = self.Ides / (self.Cg * self.Ca * self.Cs * self.Cd * self.Ci * self.Cc)\r\n\t\treturn self.It\r\n\t\t\r\n\tdef ch(self):\r\n\t\t\"\"\"Clause 5.6 Page 381 Harmonic currents in line conductors\"\"\"\r\n\t\tself.Ch = sqrt((self.Ifun**2 + self.h3**2 + self.h5**2 + self.h7**2 + self.h9**2)/self.Ifun**2)\r\n\t\treturn self.Ch\r\n\t\t\r\n\tdef ct(self):\r\n\t\t\"\"\"Clause 6.1 Page 382 Correction for operating temperature\"\"\"\r\n\t\t\r\n\t\tself.Ct = (230 + self.Tp - (self.Ca**2 * self.Cg**2 * self.Cs**2 * self.Cd**2 - self.Ides**2 / self.It**2) * (self.Tp - 30)) / (230 + self.Tp)\r\n\t\t\t\t\r\n\t\t#Here I am checking for a negative Ct and if it finds it return a 1\r\n\t\tCt = str(self.Ct)\r\n\t\t\r\n\t\tif Ct[0] =='-':\r\n\t\t\tself.Ct = 1\r\n\t\t\treturn self.Ct\r\n\t\telse:\r\n\t\t\treturn self.Ct\r\n\t\r\n\tdef mvam(self):\r\n\t\t\"\"\"Clause 6.2 Page 382 Correction for load power factor\"\"\"\r\n\t\tself.mVAmz = (cos(radians(self.Pf))*self.mVAmr) + (sin(radians(self.Pf))*self.mVAmx)\r\n\t\treturn self.mVAmz\r\n\t\t\r\n\tdef ctpf(self):\r\n\t\t\"\"\"\"Clause 6.3 Page 382 Correction for operating temperature and power factor\"\"\"\r\n\t\t\r\n\t\tCt = self.Ct\r\n\t\t\r\n\t\tif self.mVAmx == 0:\r\n\t\t\tself.mVAmz = Ct * cos(radians(self.Pf)) * self.mVAmr\r\n\t\t\treturn self.mVAmz\r\n\t\telse:\r\n\t\t\tself.mVAmz = Ct * cos(radians(self.Pf)) * self.mVAmr + sin(radians(self.Pf)) * self.mVAmx\r\n\t\t\treturn self.mVAmz\r\n\t\t\r\n#calling the class\t\t\r\nmy_cable = CableCalc(n=9, tp=70, ca=1, \r\n\t\t\t\t\tcs=1, cd=1, ib=80, \r\n\t\t\t\t\tit=300, ifun=10, h3=3, \r\n\t\t\t\t\th5=5, h7=2, h9=2, \r\n\t\t\t\t\tci = 1, cf = 1, cc =1, \r\n\t\t\t\t\tinom = 100, pf = 0.8, \r\n\t\t\t\t\tmvamr = 11, mvamx = 13)\r\n\r\n\r\n#printing out values for checking\r\nprint(\"\\nYour Cg factor is \" + str(my_cable.cg()))\r\n\r\nprint(\"\\nYour Ct Factor is \" + str(my_cable.ct()))\r\n\r\nprint(\"\\nYour Ch factor is \" + str(my_cable.ch()))\r\n\r\nprint(\"\\nYour single It should be equal or greater than \" + str(my_cable.it_single_ccts()))\r\n\r\nprint(\"\\nYour group It should be equal or greater than \" + str(my_cable.it_groups()))\r\n\r\nprint(\"\\nEquation 2 \" + str(my_cable.Eq2) + \" Equation 3 \" + str(my_cable.Eq3) + \" Equation 4 \" + str(my_cable.Eq4))\r\n\r\nprint(\"\\nYour It where overload protection is not required \" + str(my_cable.it_no_overload()))\r\n\r\nprint(\"\\nYour mVAmz is \" + str(my_cable.mvam()))\r\n\r\nprint(\"\\nYour CT * Pf * mV/A/m is \" + str(my_cable.ctpf()))","sub_path":"CableCalc-1.0.py","file_name":"CableCalc-1.0.py","file_ext":"py","file_size_in_byte":4275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"503833767","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom matplotlib.pyplot import show\nimport statsmodels.api as sm\nfrom sklearn.utils.extmath import cartesian\nfrom sklearn.svm import SVC\nfrom sklearn import preprocessing\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import classification_report, confusion_matrix\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.impute import SimpleImputer\nimport joblib\n\nstats = pd.read_csv(\"Seasons_Stats.csv\")\nall_nba = pd.read_csv(\"All.NBA.1984-2018.csv\")\n\n# Create new column Year\n\nall_nba = all_nba.iloc[1:]\nall_nba[\"Unnamed: 2\"] = all_nba[\"Unnamed: 2\"].str[0:4]\nall_nba[\"Year\"] = all_nba[\"Unnamed: 2\"].astype(int) + 1\n\n# Filter both dataframes to only contain data from 1998 onwards\n\nmodern_stats = stats[stats[\"Year\"] >= 1998.0]\nmodern_allnba = all_nba[all_nba[\"Year\"] >= 1998]\n\n# Remove players with NaN values in categories except 'blank' and 'blank2'\n# Remove columns with all NaN values, then remove rows with NaN values\n\nmodern_stats = modern_stats.dropna(axis=1, how=\"all\")\n\n# Find location where players are double counted due to trades\n\nidx_stats = modern_stats.index[modern_stats[\"Tm\"] == \"TOT\"]\nidx_allnba = modern_allnba.index[modern_allnba[\"Unnamed: 4\"] == \"TOT\"]\n\n# Remove instances in 'modern_stats' dataframe with \"TOT\" as team\n\nmodern_stats = modern_stats[modern_stats.Tm != \"TOT\"]\n\n# Change \"TOT\" in 'modern_allnba' dataframe to team that player played majority of games with\n\nmodern_allnba.at[315, \"Unnamed: 4\"] = \"DEN\"\nmodern_allnba.at[413, \"Unnamed: 4\"] = \"ATL\"\n\n# Need to get per game stats for each player in 'modern_stats'\n# Divide specific categories by number of games a player played in a certain season\n\ncolumns = [\"FG\", \"FGA\", \"3P\", \"3PA\", \"2P\", \"2PA\", \"FT\", \"FTA\", \"ORB\", \"DRB\", \"TRB\", \"AST\",\n \"STL\", \"BLK\", \"TOV\", \"PF\", \"PTS\"]\nmodern_stats[columns] = modern_stats[columns].div(modern_stats[\"G\"].values, axis=0)\n\n# Remove outliers in the modern_stats dataset - do not want players who have played less than 15 minutes per game\n# or less than 10 games\n\nmodern_stats = modern_stats[modern_stats.MP > 15]\nmodern_stats = modern_stats[modern_stats.G > 10]\n\n# Create new column in 'modern_stats' dataframe with values 0 or 1 to indicate whether player was an All NBA player\n# Create new column in both datasets that combines name and year to determine which players in 'modern_stats' dataframe\n# were All NBA players\n\nmodern_allnba[\"Identifier\"] = modern_allnba[\"Unnamed: 1\"] + modern_allnba[\"Year\"].astype(str) \\\n + modern_allnba[\"Unnamed: 4\"].astype(str) \\\n + modern_allnba[\"Unnamed: 3\"].astype(int).astype(str)\nmodern_stats[\"Identifier\"] = modern_stats[\"Player\"] + modern_stats[\"Year\"].astype(int).astype(str) \\\n + modern_stats[\"Tm\"].astype(str) + modern_stats[\"Age\"].astype(int).astype(str)\n\n\ndef all_nba_label(row):\n if modern_allnba[\"Identifier\"].str.contains(row[\"Identifier\"]).any():\n return 1\n else:\n return 0\n\n\nmodern_stats[\"AllNBA\"] = modern_stats.apply(all_nba_label, axis=1)\n\n# Check if there are only 15 All NBA players for each year\n\nmodern_stats[\"Year\"] = modern_stats[\"Year\"].astype(int)\n\ncount = modern_stats[modern_stats.AllNBA == 1].groupby(\"Year\").size()\nprint(count)\n\n# Only 14 players in 2004 had the All NBA identifier -- Metta World Peace was part of the 2003-2004 All NBA team, but\n# is not included in the 'modern_stats' dataframe\n\nprint(modern_stats[modern_stats[\"Year\"] == 2004][modern_stats[\"AllNBA\"] == 1])\nprint(modern_allnba[modern_allnba[\"Year\"] == 2004])\nprint(modern_stats[modern_stats[\"Player\"] == \"Metta World Peace\"])\n\nmodern_stats = modern_stats.fillna(0)\n\n# Use support vector machines to predict All NBA selections; normalize data\n\ntraining = modern_stats[modern_stats[\"Year\"] < 2012]\ntest = modern_stats[modern_stats[\"Year\"] >= 2013]\n\ny_train = np.array(training[\"AllNBA\"])\nx_train = training.drop([\"Unnamed: 0\", \"Year\", \"Player\", \"Pos\", \"Age\", \"Tm\", \"G\", \"GS\", \"MP\", \"Identifier\", \"AllNBA\"], axis=1)\n\nx_test = test.drop([\"Unnamed: 0\", \"Year\", \"Player\", \"Pos\", \"Age\", \"Tm\", \"G\", \"GS\", \"MP\", \"Identifier\", \"AllNBA\"], axis=1).values\ny_test = test[\"AllNBA\"].values\n\n# use grid search to determine parameters\nparameters = [{'kernel': ['linear', 'rbf', 'poly'], 'C': [0.01, 0.1, 1, 10, 100, 1000]}]\nscores = ['precision', 'recall']\n\nfor score in scores:\n clf = GridSearchCV(SVC(C=1), parameters, cv=5, scoring=score)\n clf.fit(x_train, y_train)\n\n print(\"Best parameters set:\")\n print(clf.best_estimator_)\n print(\"Grid Scores:\")\n print(clf.cv_results_)\n print(\"Classification Report: \")\n y_true, y_pred = y_test, clf.predict(x_test)\n print(classification_report(y_true, y_pred))\n\n\nsv_classifier = SVC(kernel=\"linear\", C=0.01)\nsv_classifier.fit(x_train, y_train)\n\njoblib.dump(sv_classifier, \"./sv_classifier.joblib\", compress=True)\n\ny_predicted = sv_classifier.predict(x_test)\n\ntarget_names = [\"Not All NBA\", \"All NBA\"]\n\nprint(accuracy_score(y_test, y_predicted))\nprint(classification_report(y_test, y_predicted, target_names=target_names))\nprint(confusion_matrix(y_test, y_predicted))\n\nprint(sv_classifier.coef_.ravel())\n\n\ndef plot_feature_weights(svm, names):\n coef = svm.coef_.ravel()[0:42]\n pos = np.argsort(coef)[-18:]\n neg = np.argsort(coef)[:24]\n coefficients = np.hstack([neg, pos])\n plt.figure(figsize=(15, 5))\n colors = ['blue' if c < 0 else 'red' for c in coef[coefficients]]\n plt.bar(np.arange(42), coef[coefficients], color=colors, width=0.6, align='center')\n feature_names = np.array(names)\n plt.title(\"Feature Weights\")\n plt.xticks(range(42), feature_names[coefficients], rotation=60, ha='right', fontsize=9)\n plt.show(block=False)\n\n\nfeatures = ['PER', 'TS%', '3PAr', 'FTr', 'ORB%', 'DRB%', 'TRB%', 'AST%', 'STL%', 'BLK%', 'TOV%', 'USG%', 'OWS', 'DWS',\n 'WS', 'WS/48', 'OBPM', 'DBPM', 'BPM', 'VORP', 'FG', 'FGA', 'FG%', '3P', '3PA', '3P%', '2P', '2PA', '2P%',\n 'eFG%', 'FT', 'FTA', 'FT%', 'ORB', 'DRB', 'TRB', 'AST', 'STL', 'BLK', 'TOV', 'PF', 'PTS']\n\nplot_feature_weights(sv_classifier, features)\n\n# some stats had high magnitude of feature weight that were unexpected\n\nstat_list = ['FTA', 'STL%', 'TOV%', '3PA', 'BPM', 'WS']\n\ndummy_list = []\nfor stat in stat_list:\n stat_values = np.linspace(modern_stats[stat].min(), modern_stats[stat].max(), 20)\n dummy_list.append(stat_values)\n\npredictions = pd.DataFrame(cartesian(dummy_list))\npredictions.columns = stat_list\n\nfor stat in stat_list:\n logit = sm.Logit(modern_stats['AllNBA'], modern_stats[stat])\n result = logit.fit()\n print(np.exp(result.params))","sub_path":"research/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":6794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"231286790","text":"#!/usr/bin/env python\n#\n# quotes.futures.py\n# \n# Copyright 2010 JPS\n\nimport os\nimport re\nimport urllib\n\nimport qtrade_csv\nimport qtrade_config\nfrom qtrade_market import compute_country, market2currency\n\nfuturesurl = {\n 'stocks' : 2721,\n 'indices' : 46175,\n 'stir' : 46174,\n 'commodities' : 46171,\n }\n\n \ndef main():\n \n market = 'NYSE Liffe'\n \n for underlying in futuresurl.keys():\n futures = []\n baseurl = 'http://www.euronext.com/trader/priceslistsderivatives/derivativespriceslists-%d-EN.html?&pageIndex='%futuresurl[underlying]\n if underlying == 'stocks':\n for i in range(1,3):\n url = baseurl + '%d'%i\n u = urllib.urlopen(url).read()\n future = re.findall(r'\\n\\t{3}([\\w ]+)[\\W.]+\\w+[\\W.]+\\w+[\\W.]+\\w+[\\W.]+[\\w \\\n ;\"=:-]+[\\W.]+\\w+>(\\w+)[\\W.]+\\w+[\\W.]+[\\w ;\"=:-]+[\\W.]+\\w+>(\\w+)',u)\n for tuple in future:\n (name, place, symbol) = tuple\n futures.append(';%s;%s;%s;%s;%s;%s'%(name,symbol,market,market2currency(market),place,compute_country(None,market,place)))\n qtrade_csv.write(None,os.path.join(qtrade_config.dirSymbData,'stocks.futures.txt'),futures)\n else:\n url = baseurl + '1'\n u = urllib.urlopen(url).read().split('Options - All NYSE Liffe')\n future = re.findall(r'\\n\\t{3}([\\w \\(\\)-\\\\]+)[\\W.]+\\w+[\\W.]+\\w+[\\W.]+\\w+[\\W.]+[\\w \\\n ;\"=:-]+[\\W.]+\\w+>(\\w+)[\\W.]+\\w+[\\W.]+[\\w ;\"=:-]+[\\W.]+\\w+>(\\w+)',u[0])\n for tuple in future:\n (name, place, symbol) = tuple\n futures.append(';%s;%s;%s;%s;%s;%s'%(name,symbol,market,market2currency(market),place,compute_country(None,market,place)))\n #~ print re.findall(r'\\n\\t{3}([\\w ]+)|([a-zA-Z ]+)',u)\n qtrade_csv.write(None,os.path.join(qtrade_config.dirSymbData,'%s.futures.txt'%underlying),futures)\n \n \n \n return 0\n\nif __name__ == '__main__':\n main()\n","sub_path":"symbols/quotes.futures.py","file_name":"quotes.futures.py","file_ext":"py","file_size_in_byte":2101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"503352734","text":"from django.test import TestCase\nfrom django.core.exceptions import ValidationError\n\nfrom lists.models import Item,List\n\n# Create your tests here.\n\nclass ItemModelTest(TestCase):\n def test_default_text(self):\n item=Item()\n self.assertEqual(item.text,'')\n\n def test_string_representation(self):\n item=Item(text='some text')\n self.assertEqual(str(item),'some text')\n \n\nclass ListAndItemModelTest(TestCase):\n\n\n def test_item_is_related_to_list(self):\n list_=List.objects.create()\n item=Item()\n item.list=list_\n item.save()\n self.assertIn(item,list_.item_set.all())\n\n def test_saving_and_retrieving_items(self):\n list_ = List()\n list_.save()\n\n first_item = Item()\n first_item.text = 'The first (ever) list item'\n first_item.list=list_\n first_item.save()\n\n second_item = Item()\n second_item.text = 'Item the second'\n second_item.list=list_\n second_item.save()\n\n saved_list = List.objects.first()\n self.assertEqual(saved_list,list_)\n\n save_items = Item.objects.all()\n self.assertEqual(save_items.count(),2)\n\n first_saved_item=save_items[0]\n second_saved_item=save_items[1]\n self.assertEqual(first_saved_item.text,'The first (ever) list item')\n self.assertEqual(first_saved_item.list,list_)\n self.assertEqual(second_saved_item.text,'Item the second')\n self.assertEqual(second_saved_item.list,list_)\n\n def test_cannot_save_empyt_list_items(self):\n list_ = List.objects.create()\n item=Item(list=list_,text='')\n with self.assertRaises(ValidationError):\n item.save()\n item.full_clean()\n\n def test_get_absolute_url(self):\n list_=List.objects.create();\n self.assertEqual(list_.get_absolute_url(),'/lists/%d/' % (list_.id,))\n\n def test_duplicate_items_are_invalid(self):\n list_=List.objects.create()\n Item.objects.create(list=list_,text='bla')\n with self.assertRaises(ValidationError):\n item=Item(list=list_,text='bla')\n item.full_clean()\n\n def teat_CAN_save_same_item_to_different_lists(self):\n list1=List.objects.create()\n list2=List.objects.create()\n Item.objects.create(list=list1,text='bla')\n item=Item(list=list2,text='bla')\n item.full_clean()\n\n\n def test_list_ordering(self):\n list1=List.objects.create()\n item1 = Item.objects.create(list=list1,text='i1')\n item2 = Item.objects.create(list=list1,text='item 2')\n item3 = Item.objects.create(list=list1,text='3')\n self.assertEqual(list(Item.objects.all()),[item1,item2,item3])\n","sub_path":"lists/tests/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":2722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"40614361","text":"import itertools\nimport json\nimport sys\n\npython_versions = (\"3.4\", \"3.5\", \"3.6\")\nlatest_python = \"3.6\"\n\ncfg = {}\n\ncfg['sudo'] = True\ncfg['dist'] = 'trusty'\ncfg['language'] = 'python'\ncfg['cache'] = 'pip'\n\ncfg['git'] = {\n 'submodules': False\n}\n\ncfg['branches'] = {\n 'only': ['auto', 'master']\n}\n\ncfg['install'] = \"\"\"\n. scripts/travis-install.sh\npip install -U pip setuptools\npip install wheel\nmake -e install-dev\nmake -e install-$BUILD\n\"\"\".strip().splitlines()\n\ncfg['script'] = [\"make -e $BUILD\"]\n\nmatrix = []\ncfg['matrix'] = {'include': matrix, 'fast_finish': True}\n\nmatrix.append({\n 'python': latest_python,\n 'env': 'BUILD=style'\n})\n\n\nfor python, requirements in itertools.product(python_versions,\n (\"devel\", \"release\", \"minimal\")):\n dav_servers = (\"radicale\", \"xandikos\")\n\n if python == latest_python and requirements == \"release\":\n dav_servers += (\"owncloud\", \"nextcloud\", \"baikal\", \"davical\", \"icloud\",\n \"fastmail\")\n\n for dav_server in dav_servers:\n job = {\n 'python': python,\n 'env': (\"BUILD=test \"\n \"DAV_SERVER={dav_server} \"\n \"REQUIREMENTS={requirements} \"\n .format(dav_server=dav_server,\n requirements=requirements))\n }\n\n build_prs = dav_server not in (\"fastmail\", \"davical\", \"icloud\")\n if not build_prs:\n job['if'] = 'NOT (type IN (pull_request))'\n\n matrix.append(job)\n\nmatrix.append({\n 'python': latest_python,\n 'env': (\"BUILD=test \"\n \"ETESYNC_TESTS=true \"\n \"REQUIREMENTS=latest\")\n})\n\nmatrix.append({\n 'language': 'generic',\n 'os': 'osx',\n 'env': 'BUILD=test'\n})\n\njson.dump(cfg, sys.stdout, sort_keys=True, indent=2)\n","sub_path":"scripts/make_travisconf.py","file_name":"make_travisconf.py","file_ext":"py","file_size_in_byte":1812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"88051547","text":"# file.py\nimport os\nimport multiprocessing as mp\n\n\ndef cp1(f, num1):\n try:\n f1 = open('./test1.txt', 'r+b')\n s = f.read(num1)\n f1.write(s)\n finally:\n f1.close()\n\n\ndef cp2(f, num1, num2):\n try:\n f1 = open('./test1.txt', 'r+b')\n f.seek(num1)\n s = f.read(num2)\n f1.seek(num1)\n f1.write(s)\n finally:\n f1.close()\n\n\ndef main():\n f = open('./test.txt', 'r+b')\n num = os.path.getsize('./test.txt')\n num1 = num // 2\n num2 = num - num1\n p1 = mp.Process(target=cp1, args=(f, num1))\n p2 = mp.Process(target=cp2, args=(f, num1, num2))\n p1.start()\n p2.start()\n f.close()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"2-第二阶段/4-PyNET/2-thread/day31multiprocessing/ex/file.py","file_name":"file.py","file_ext":"py","file_size_in_byte":706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"408345936","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n#****************************************************************************************************************************************************\n# Copyright 2017 NXP\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#\n# * Redistributions of source code must retain the above copyright notice,\n# this list of conditions and the following disclaimer.\n#\n# * 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#\n# * Neither the name of the NXP. nor the names of\n# its contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n# IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\n# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n#\n#****************************************************************************************************************************************************\n\nfrom FslBuildGen.Log import Log\nfrom FslBuildGen.Location.ResolvedPath import ResolvedPath\nfrom FslBuildGen.Vars.VariableProcessor import VariableProcessor\n\nclass PathBuilder(object):\n def __init__(self, log: Log, variableProcessor: VariableProcessor, platformName: str) -> None:\n super().__init__()\n\n self.__Log = log # type: Log\n self.__VariableProcessor = variableProcessor # type: VariableProcessor\n\n\n def ResolveFilePath(self, sourcePath: str) -> ResolvedPath:\n if sourcePath.find('..') != -1:\n raise Exception(\"'..' is now allowed in file paths ('{0}')\".format(sourcePath))\n if sourcePath.find('\\\\') != -1:\n raise Exception(\"'\\\\' is now allowed in file paths ('{0}')\".format(sourcePath))\n\n resolvedPath = self.__VariableProcessor.ResolveAbsolutePathWithLeadingEnvironmentVariablePathAsFile(sourcePath)\n return ResolvedPath(sourcePath, resolvedPath)\n\n\n def ResolveDirectoryPath(self, sourcePath: str, checkExists: bool = True) -> ResolvedPath:\n if sourcePath.find('..') != -1:\n raise Exception(\"'..' is now allowed in directory paths ('{0}')\".format(sourcePath))\n if sourcePath.find('\\\\') != -1:\n raise Exception(\"'\\\\' is now allowed in directory paths ('{0}')\".format(sourcePath))\n\n resolvedPath = self.__VariableProcessor.ResolveAbsolutePathWithLeadingEnvironmentVariablePathAsDir(sourcePath, checkExists=checkExists)\n return ResolvedPath(sourcePath, resolvedPath)\n\n\n def ResolveFilenameWithVariables(self, sourcePath: str) -> str:\n if sourcePath.find('..') != -1:\n raise Exception(\"'..' is now allowed in directory paths ('{0}')\".format(sourcePath))\n if sourcePath.find('\\\\') != -1:\n raise Exception(\"'\\\\' is now allowed in directory paths ('{0}')\".format(sourcePath))\n if sourcePath.find('$') == -1:\n return sourcePath\n resolvedPath = self.__VariableProcessor.ResolveFilenameWithVariables(sourcePath)\n return resolvedPath\n\n","sub_path":".Config/FslBuildGen/Location/PathBuilder.py","file_name":"PathBuilder.py","file_ext":"py","file_size_in_byte":3948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"363917635","text":"#!/usr/bin/python\n\n\nfrom process_functions import *\n\n# Variable assignment of the process name we wish to determine is in state running.\n\nsome_process = \"rsyslogd\"\n\n# Testing to determine if the process identified within the variable process_name is running.\n\nif (test_process(some_process) == 1):\n print(\"The process: \" +some_process+ \" is not in state running\") \nelse:\n print(\"The process: \" +some_process+ \" is in state running\")\n\n","sub_path":"Process Check/process_check.py","file_name":"process_check.py","file_ext":"py","file_size_in_byte":440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"603109702","text":"#!/usr/bin/python\n\ndevise = str(input(\"Saisir la devise 'E' ou '$' à convertir:\"))\nTAUX_DOL_TO_EUR=0.83\nTAUX_EUR_TO_DOL=1.20\nif devise == 'E':\n montant = str(input(\"Saisir le montant en Euro à convertir en Dollars:\"))\n calcul= int(montant) * float(TAUX_DOL_TO_EUR)\n print(\"Le montant en Dollars est:\", calcul)\nelif devise == '$':\n montant = str(input(\"Saisir le montant en Dollars à convertir en Euro:\"))\n calcul= int(montant) * float(TAUX_EUR_TO_DOL)\n print(\"Le montant en Dollars est:\", calcul)\nelse:\n print(\"Saisir E ou $ \")","sub_path":"exercice5_test_condition_convertir.py","file_name":"exercice5_test_condition_convertir.py","file_ext":"py","file_size_in_byte":551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"537447909","text":"from django.core.mail import EmailMessage\n\nfrom django.conf import settings\n\nsettings.configure(\n DEBUG=True,\n ROOT_URLCONF=__name__,\n MIDDLEWARE_CLASSES=(\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n ),\n EMAIL_HOST='smtp.gmail.com',\n EMAIL_HOST_USER='your email',\n EMAIL_HOST_PASSWORD='your password',\n EMAIL_PORT=587,\n EMAIL_USE_TLS=True,\n)\n\n\nclass EmailSender:\n email = EmailMessage()\n\n def __init__(self, subject, to_address, body, from_email=None):\n self.email.subject = subject\n self.email.from_email = from_email or 'osnaiderluis94@mail.com'\n self.email.to = [to_address]\n self.email.body = body\n\n def send(self):\n try:\n self.email.send(fail_silently=True)\n print('Mensaje enviado satisfactoriamente...')\n except Exception as ex:\n print(f'Ha ocurrido el siguente error: {ex}.')\n","sub_path":"Activity 2/email_send.py","file_name":"email_send.py","file_ext":"py","file_size_in_byte":1024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"205752714","text":"#用类和面向对象的思想,“描述”生活中任意接触到的东西(比如动物、小说里面的人物,不做限制,随意发挥),数量为5个\n\nclass DaXia:\n #定义属性\n yanzhi=100\n power=100\n #定义绝学\n def juexue(self,jxmc):\n self.jxmc = jxmc\n print(f\"看招,{self.jxmc}\")\n#实例化类\nQianFeng=DaXia()\nQianFeng.juexue(\"降龙十八掌\")\n\nLuXiaoFeng=DaXia()\nLuXiaoFeng.juexue(\"灵犀一指\")\n\nclass People:\n def zhiye(self,zy):\n if zy ==\"说书人\":\n print(\"九河下梢天津卫,三道浮桥两道关\")\n if zy ==\"相声演员\":\n print(\"桃叶尖上尖,柳叶遮满了天,在其位那个明啊公,细听我来言~\")\n if zy ==\"影视演员\":\n print(\"其实我想做个好人\")\n#实例化类\npeople=People()\npeople.zhiye(\"相声演员\")\n\nclass DLDL:\n hunhuan = 0\n huanli = 10\n def huobai(self,name):\n print(f\"我的伙伴是{name}\")\nTanSan=DLDL()\nTanSan.huobai(\"史莱克七怪\")\n","sub_path":"practice2/work1.py","file_name":"work1.py","file_ext":"py","file_size_in_byte":1023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"217843826","text":"from simcore import *\nfrom net.tinyos.sim.event import RadioMsgSentEvent\n\npursuer1 = sim.__driver.pluginManager.getPlugin(\"1Plugin\")\n#evader = sim.__driver.pluginManager.getPlugin(\"EvaderPlugin\")\n\nif not pursuer1.isRegistered():\n sim.loadPlugin(\"Pursuer1Plugin\")\n\n#if not evader.isRegistered():\n# sim.loadPlugin(\"EvaderPlugin\")\n\n#xelabel = evader.parameterPane.getComponent(1)\n#yelabel = evader.parameterPane.getComponent(3)\n#xelabel.setText(\"5\")\n#yelabel.setText(\"95\")\n#evader.parameterPane.getComponent(10).setSelected(0)\n#evader.update()\nxplabel = pursuer1.parameterPane.getComponent(1)\nyplabel = pursuer1.parameterPane.getComponent(3)\nxplabel.setText(\"20\")\nyplabel.setText(\"80\")\npursuer1.parameterPane.getComponent(10).setSelected(0)\npursuer1.update()\n\npf = open('p1path', 'w')\ntime = 0\n\ndef position(event):\n global time\n xp = pursuer1.getXPosition()\n yp = pursuer1.getYPosition()\n newtime = event.getTime()\n if newtime != time:\n pf.write(str(newtime) + ',' + str(xp) + ',' + str(yp) + \"\\n\")\n pf.flush()\n time = newtime;\n\np1pg = interp.addEventHandler(position, RadioMsgSentEvent)\n\ndef start(event):\n global pursuer1\n time = event.getTime()\n if (time >= 20 * 4000 * 1000):\n pursuer1.parameterPane.getComponent(5).setText(\"0.5\")\n pursuer1.parameterPane.getComponent(10).setSelected(1)\n pursuer1.update()\n interp.removeEventHandler(p1pgs)\n\np1pgs = interp.addEventHandler(start, RadioMsgSentEvent)\n","sub_path":"tinyos-1.x/contrib/ucb/apps/MutationRouting/Pursuer1PathGen.py","file_name":"Pursuer1PathGen.py","file_ext":"py","file_size_in_byte":1479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"513714929","text":"\"\"\"\nP018 Maximum path sum I\n\n\nBy starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23.\n\n 3\n 7 4\n 2 4 6\n8 5 9 3\n\nThat is, 3 + 7 + 4 + 9 = 23.\n\nFind the maximum total from top to bottom of the triangle below:\n 75\n 95 64\n 17 47 82\n 18 35 87 10\n 20 04 82 47 65\n 19 01 23 75 03 34\n 88 02 77 73 07 63 67\n 99 65 04 28 06 16 70 92\n 41 41 26 56 83 40 80 70 33\n 41 48 72 33 47 32 37 16 94 29\n 53 71 44 65 25 43 91 52 97 51 14\n 70 11 33 28 77 73 17 78 39 68 17 57\n 91 71 52 38 17 14 91 43 58 50 27 29 48\n 63 66 04 68 89 53 67 30 73 16 69 87 40 31\n04 62 98 27 23 09 70 98 73 93 38 53 60 04 23\n\nNOTE: As there are only 16384 routes, it is possible to solve this problem by trying every route. However, Problem 67, is the same challenge with a triangle containing one-hundred rows; it cannot be solved by brute force, and requires a clever method! ;o)\n\"\"\"\n\n# process the data first\ndef process(data):\n with open(data) as f_obj:\n content = f_obj.readlines()\n result = []\n for i in content:\n temp = i.strip().split(\" \")\n temp = [int(j) for j in temp]\n result.append(temp)\n return result\n\n\n# Brutal force\ndef coor_value(coor, grid):\n \"\"\"coor is coordinate of the grid in the form of (x, y)\"\"\"\n return grid[coor[0]][coor[1]]\n\ndef max_path_sum_i(T):\n \"\"\"calculate the max sum of a route in triangle\n\n T as triangle: a nested list as triangle grid\n return: the max sum of the numbers in one route of the triangle grid\n \"\"\"\n row, depth = 1, len(T)\n current = [(0,0)]\n possible_path = [current]\n\n while row < depth:\n temp = []\n for coor in current:\n temp += [(coor[0] + 1, coor[1]), (coor[0] + 1, coor[1] + 1)]\n current = temp[:]\n possible_routes_temp = []\n for i in possible_path:\n possible_routes_temp += [i[:], i[:]]\n possible_path = possible_routes_temp[:]\n\n for idx in range(len(temp)):\n possible_path[idx].append(temp[idx])\n\n row += 1\n\n # for print the result, first translate coor to value\n path_in_value = []\n for i in possible_path:\n values = [coor_value(j, T) for j in i]\n path_in_value.append(values)\n\n # for i in path_in_value:\n # print(i)\n\n print(\"total path number\", len(path_in_value))\n return sum(max(path_in_value, key=sum))\n\n\n\n\nif __name__ == \"__main__\":\n print(max_path_sum_i(process(\"p018_data_test.txt\")))\n # >>> 20 (from 1,3,6,10)\n print(max_path_sum_i(process(\"p018_data.txt\")))\n # >>> 1074\n # passed\n","sub_path":"AlgorithmTraining/ProjectEuler/p018_maximum_paths_sum_i.py","file_name":"p018_maximum_paths_sum_i.py","file_ext":"py","file_size_in_byte":2900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"514399550","text":"from flask import Flask, g\nfrom flask.ext.sqlalchemy import SQLAlchemy\nfrom flask.ext.babel import Babel\nfrom config import getConfig\nimport jinja2\nimport os\nimport os.path\nfrom pprint import pprint\n\nclass MyApp(Flask):\n \n def __init__(self):\n Flask.__init__(self, __name__)\n self.jinja_loader = jinja2.ChoiceLoader([\n self.jinja_loader,\n jinja2.PrefixLoader({}, delimiter = \".\")\n ])\n \n def create_global_jinja_loader(self):\n return self.jinja_loader\n\n def register_blueprint(self, bp, url_prefix):\n Flask.register_blueprint(self, bp, url_prefix)\n self.jinja_loader.loaders[1].mapping[bp.name] = bp.jinja_loader\n \n\n#App ROOT \nAPP_ROOT = os.path.dirname(os.path.abspath(__file__)) # refers to application_top\nAPP_ROOT = os.path.abspath(os.path.join(APP_ROOT, os.pardir))\n\napp = Flask(__name__, static_folder=APP_ROOT + '/static', template_folder=APP_ROOT + '/templates')\napp.root_path = APP_ROOT \napp.config.from_object(getConfig())\n\n#deal with babel localization here\nbabel = Babel(app)\napp.secret_key = 'thisismyverystrongsecret'\n\n@babel.localeselector\ndef get_local():\n\tuser = getattr(g, 'user', None)\n\tif user is not None:\n\t\tlocal = getattr(user, 'local', None)\n\tif local is not None:\n\t\treturn local\n\telse:\n\t\treturn 'fr'\n\t\t\n\t\t\n\n\n\n\n# load prod settings\ndb = SQLAlchemy(app)\n\nfrom main.main_app import main_app\nfrom rest import api_mod\nfrom auth.mod_auth import auth_mod\nfrom mail import mail_mod\napp.register_blueprint(main_app)\napp.register_blueprint(api_mod)\napp.register_blueprint(mail_mod)\n\n","sub_path":"app/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"44865213","text":"from cluster import Cluster\nfrom loader import Loader\nfrom helper import read_config_file\nimport readline, glob, sys\n\n\ndef main(config_file):\n \"\"\"Main function.\n This will orchestrate the measurement\n \"\"\"\n\n # read the given config file and store values\n config = read_config_file(config_file)\n\n k8s = Cluster(config[\"cluster_name\"], config)\n \n print(\"Cluster: \", str(k8s))\n\n lo = Loader(k8s, config)\n\n # k8s.helm_uninstall_all()\n\n\nif __name__ == '__main__':\n try:\n # check if all ready to launch\n if len(sys.argv) != 2:\n # if config file is not given\n print(\"Please give (one and only one) configuration yaml file\")\n\n # get config file (on runtime) with autocomplete \n def complete(text, state):\n return (glob.glob(text+'*')+[None])[state]\n\n readline.set_completer_delims(' \\t\\n;')\n readline.parse_and_bind(\"tab: complete\")\n readline.set_completer(complete)\n\n config_file = input(\"Config file: \")\n\n main(config_file)\n elif(False):\n pass\n else:\n main(str(sys.argv[1]))\n finally:\n print(\"Program exited\")\n","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"299251025","text":"import os\nimport xlsxwriter\nfrom os.path import expanduser\n\ndef findFailingTests(rootDir ,worksheet):\n\tcount = 0\n\trow = 1\n\tcol = 0\n\ttemp = \"\"\n\ttempmult = \"\"\n\tfor dirName, subdirList, fileList in os.walk(rootDir):\n\t\tfor fname in fileList:\n\t\t\tif '.ini' in fname and fname != '__dir__.ini':\n\t\t\t\tcount+=1\n\t\t\t\tworksheet.write(row,col,count)\n\t\t\t\tworksheet.write(row,col+1,fname)\n\t\t\t\t#worksheet.write(row,col+2,dirName.strip(expanduser(\"~\")))\n\t\t\t\trow+=1\n\treturn count\n\ndef findCountofTests(rootDir):\n\tcount = 0\n\trootDir = rootDir.replace('/meta/','/tests/')\n\tfor dirName, subdirList, fileList in os.walk(rootDir):\n\t\tfor fname in fileList:\n\t\t\tif '.html' in fname or '.htm' in fname:\n\t\t\t\tcount+=1\n\treturn count\nhome = expanduser(\"~\")\nrootDir = home+'/src/mozilla-central/testing/web-platform/meta/'\nrequiredSubdirList = ['content-security-policy','mixed-content','subresource-integrity','cors','x-frame-options','referrer-policy','webauthn','feature-policy','credential-management']\nworkbook = xlsxwriter.Workbook('failing_wpt_tests.xlsx')\nbold = workbook.add_format({'bold': True})\nfor dirName, subdirList, fileList in os.walk(rootDir,workbook):\n\tmidtemp = dirName\n\ttestcount = 0\n\tfailcount = 0\n\tif midtemp.replace(rootDir,'') in requiredSubdirList:\n\t\ttestcount = findCountofTests(dirName)\n\t\tworksheet = workbook.add_worksheet(midtemp.replace(rootDir,''))\n\t\tfailcount = findFailingTests(dirName,worksheet)\n\t\tworksheet.write(0,0,midtemp.replace(rootDir,'')+'(failing '+str(failcount)+'/total '+str(testcount)+')',bold)\nworkbook.close()\n\n\n\n\n\n\n","sub_path":"find_failing_wpt_tests.py","file_name":"find_failing_wpt_tests.py","file_ext":"py","file_size_in_byte":1533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"394013166","text":"import sys \nsys.setrecursionlimit(1000000)\nm,n,k = map(int,raw_input().strip().split())\nnum = 1\ntmp = [0,0]\nsearched = [[False] * n for _ in range(m)]\nsearched[0][0] = True\n\ndef dt(x,y):\n\tnum = 0\n\twhile x > 0:\n\t\tnum += x%10\n\t\tx /= 10\n\twhile y > 0:\n\t\tnum += y%10\n\t\ty /= 10\t\n\treturn num\ndef dfs(tmp,searched):\n\tglobal num\n\ty,x = tmp\n\tif y-1 >= 0 and searched[y-1][x] == False and dt(x,y-1) <= k:\n\t\tnum += 1\n\t\tsearched[y-1][x] = True\n\t\tdfs([y,x],searched)\n\tif x-1 >= 0 and searched[y][x-1] == False and dt(x-1,y) <= k:\n\t\tnum += 1\n\t\tsearched[y][x-1] = True\n\t\tdfs([y,x-1],searched)\n\tif x+1 < n and searched[y][x+1] == False and dt(x+1,y) <= k:\n\t\tnum += 1\n\t\tsearched[y][x+1] = True\n\t\tdfs([y,x+1],searched)\n\tif y+1 < m and searched[y+1][x] == False and dt(x,y+1) <= k:\n\t\tnum += 1\n\t\tsearched[y+1][x] = True\n\t\tdfs([y+1,x],searched)\n\ndfs([0,0],searched)\nprint(num)\n\n\n\n","sub_path":"niuke/164.py","file_name":"164.py","file_ext":"py","file_size_in_byte":859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"26556960","text":"import os\nfrom typing import Any, Callable\n\nfrom kolas.config.casters import cast as _cast\nfrom kolas.config.exceptions import ConfigurationError\nfrom starlette.config import undefined\n\n\ndef env(\n name: str, default=undefined, cast: Callable = None\n) -> Any:\n value = os.environ.get(name, default)\n if value == undefined and default == undefined:\n raise ConfigurationError(\n f\"Environment variable `{name}` is required but was not found \"\n f\"and has no default value.\"\n )\n\n if cast is not None and value != default:\n return _cast(cast, value)\n\n return value\n","sub_path":"kolas/kolas/config/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"111878623","text":"import sys\nassert sys.version_info >= (3, 5) # make sure we have Python 3.5+\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom pyspark.sql import SparkSession, SQLContext, functions, types\nfrom pyspark.sql.functions import *\nfrom pyspark.ml.feature import VectorAssembler\nfrom pyspark.ml.clustering import KMeans\nfrom pyspark.ml.evaluation import ClusteringEvaluator\nspark = SparkSession.builder.appName('new stations').getOrCreate()\nassert spark.version >= '2.4' # make sure we have Spark 2.4+\nspark.sparkContext.setLogLevel('WARN')\nsc = spark.sparkContext\nsqlContext = SQLContext(sc)\n\n# data prepare & clean\ntaxi_data = spark.read.csv(\"taxi_traffic.csv\", inferSchema=True, header=True)\ndf = taxi_data.filter(taxi_data['trip_distance'] < 10.0)\n\ndf = df.where(df['pickup_latitude'] < '40.817894').where(df['pickup_latitude'] > '40.674611').where(\n df['pickup_longitude'] > '-74.104557').where(df['pickup_longitude'] < '-73.92718')\ndf = df.na.drop()\n\n# pickup cluster\ncoord_assembler = VectorAssembler(inputCols=['pickup_latitude', 'pickup_longitude'], outputCol='features')\nnew_df = coord_assembler.transform(df)\n\ndef cluster(num):\n kmeans = KMeans(k=num, seed=1)\n model = kmeans.fit(new_df.select('features'))\n df = model.transform(new_df)\n centers = model.clusterCenters()\n lst = []\n for center in centers:\n lst.append(list(center))\n coord = []\n for i in lst:\n if i != [0.0, 0.0]:\n coord.append(i)\n return coord\n\n\n# kmeans cluster\nkmeans = KMeans(k=10, seed=1)\nmodel = kmeans.fit(new_df.select('features'))\ndf = model.transform(new_df)\ndf = df.withColumnRenamed('prediction', 'pickup_cluster')\ndf = df.drop('features')\n\npd_df = df.toPandas()\npd_df = pd_df.sample(frac=0.1)\nsns.set_style('whitegrid')\nsns.lmplot(x='pickup_latitude', y='pickup_longitude', data = pd_df[pd_df['pickup_latitude'] != 0.0],\n fit_reg=False, hue='pickup_cluster', height=10, scatter_kws={'s':100}).fig.suptitle('Pickup Cluster')\n#plt.show()\n\n\n# dropoff cluster\ncoord_assembler = VectorAssembler(inputCols=['dropoff_latitude', 'dropoff_longitude'], outputCol='features')\nnew_df1 = coord_assembler.transform(df)\n# kmeans cluster\nkmeans = KMeans(k=10, seed=1)\nmodel = kmeans.fit(new_df1.select('features'))\ndf1 = model.transform(new_df1)\ndf1 = df1.withColumnRenamed('prediction', 'dropoff_cluster')\ndf1 = df1.drop('features')\n\npd_df = df1.toPandas()\npd_df = pd_df.sample(frac=0.1)\nsns.set_style('whitegrid')\nsns.lmplot(x='dropoff_latitude', y='dropoff_longitude', data = pd_df[pd_df['dropoff_latitude'] != 0.0],\n fit_reg=False, hue='dropoff_cluster', height=10, scatter_kws={'s':100}).fig.suptitle('Dropoff Cluster')\n#plt.show()\n\n\n\nimport pandas as pd\n\nten = cluster(10)\nfif = cluster(50)\nhun = cluster(100)\ndata = [['ten',[ten]],['fif',[fif]], ['hun',[hun]]]\n#f=pd.DataFrame(data).to_csv(\"data/q3_data/new_station.csv\")\ndata.toPandas().to_csv(\"data/q3_data/new_station.csv\",header=True)\n#print(df)","sub_path":"spark/taxi_ml_cluster.py","file_name":"taxi_ml_cluster.py","file_ext":"py","file_size_in_byte":2974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"64848389","text":"# -*- coding: utf-8 -*-\n\"\"\"\n flaskbb.utils\n ~~~~~~~~~~~~~~~~~~~~\n\n A few utils that are used by flaskbb\n\n :copyright: (c) 2013 by the FlaskBB Team.\n :license: BSD, see LICENSE for more details.\n\"\"\"\nimport time\nfrom datetime import datetime, timedelta\n\nfrom flask import current_app\nfrom sqlalchemy import types\nfrom sqlalchemy.ext.mutable import Mutable\nfrom wtforms.widgets.core import Select, HTMLString, html_params\nfrom postmarkup import render_bbcode\n\nfrom flaskbb.extensions import redis\n\n\ndef mark_online(user_id, guest=False):\n \"\"\"\n Source: http://flask.pocoo.org/snippets/71/\n \"\"\"\n now = int(time.time())\n expires = now + (current_app.config['ONLINE_LAST_MINUTES'] * 60) + 10\n if guest:\n all_users_key = 'online-guests/%d' % (now // 60)\n user_key = 'guest-activity/%s' % user_id\n else:\n all_users_key = 'online-users/%d' % (now // 60)\n user_key = 'user-activity/%s' % user_id\n p = redis.pipeline()\n p.sadd(all_users_key, user_id)\n p.set(user_key, now)\n p.expireat(all_users_key, expires)\n p.expireat(user_key, expires)\n p.execute()\n\n\ndef get_last_user_activity(user_id, guest=False):\n if guest:\n last_active = redis.get('guest-activity/%s' % user_id)\n else:\n last_active = redis.get('user-activity/%s' % user_id)\n\n if last_active is None:\n return None\n return datetime.utcfromtimestamp(int(last_active))\n\n\ndef get_online_users(guest=False):\n current = int(time.time()) // 60\n minutes = xrange(current_app.config['ONLINE_LAST_MINUTES'])\n if guest:\n return redis.sunion(['online-guests/%d' % (current - x)\n for x in minutes])\n return redis.sunion(['online-users/%d' % (current - x)\n for x in minutes])\n\n\ndef check_perm(user, perm, forum, post_user_id=None):\n \"\"\"\n Checks if the `user` has a specified `perm` in the `forum`\n If post_user_id is provided, it will also check if the user\n has created the post\n \"\"\"\n if can_moderate(user, forum):\n return True\n if post_user_id and user.is_authenticated():\n return user.permissions[perm] and user.id == post_user_id\n return user.permissions[perm]\n\n\ndef can_moderate(user, forum):\n \"\"\"\n Checks if a user can moderate a forum\n He needs to be super moderator or a moderator of the\n specified `forum`\n \"\"\"\n if user.permissions['mod'] and user.id in forum.moderators:\n return True\n return user.permissions['super_mod'] or user.permissions['admin']\n\n\ndef perm_edit_post(user, post_user_id, forum):\n \"\"\"\n Check if the post can be edited by the user\n \"\"\"\n return check_perm(user=user, perm='editpost', forum=forum,\n post_user_id=post_user_id)\n\n\ndef perm_delete_post(user, post_user_id, forum):\n \"\"\"\n Check if the post can be deleted by the user\n \"\"\"\n return check_perm(user=user, perm='deletepost', forum=forum,\n post_user_id=post_user_id)\n\n\ndef perm_delete_topic(user, post_user_id, forum):\n \"\"\"\n Check if the topic can be deleted by the user\n \"\"\"\n return check_perm(user=user, perm='deletetopic', forum=forum,\n post_user_id=post_user_id)\n\n\ndef perm_post_reply(user, forum):\n \"\"\"\n Check if the user is allowed to post in the forum\n \"\"\"\n return check_perm(user=user, perm='postreply', forum=forum)\n\n\ndef perm_post_topic(user, forum):\n \"\"\"\n Check if the user is allowed to create a new topic in the forum\n \"\"\"\n return check_perm(user=user, perm='posttopic', forum=forum)\n\n\ndef crop_title(title):\n \"\"\"\n Crops the title to a specified length\n \"\"\"\n length = current_app.config['TITLE_LENGTH']\n if len(title) > length:\n return title[:length] + \"...\"\n return title\n\n\ndef render_markup(text):\n return render_bbcode(text)\n\n\ndef is_online(user):\n return user.lastseen >= time_diff()\n\n\ndef time_diff():\n now = datetime.utcnow()\n diff = now - timedelta(minutes=current_app.config['ONLINE_LAST_MINUTES'])\n return diff\n\n\ndef format_date(value, format='%Y-%m-%d'):\n \"\"\"\n Returns a formatted time string\n \"\"\"\n return value.strftime(format)\n\n\ndef time_since(value):\n return time_delta_format(value)\n\n\ndef time_delta_format(dt, default=None):\n \"\"\"\n Returns string representing \"time since\" e.g.\n 3 days ago, 5 hours ago etc.\n Ref: https://bitbucket.org/danjac/newsmeme/src/a281babb9ca3/newsmeme/\n \"\"\"\n\n if default is None:\n default = 'just now'\n\n now = datetime.utcnow()\n diff = now - dt\n\n periods = (\n (diff.days / 365, 'year', 'years'),\n (diff.days / 30, 'month', 'months'),\n (diff.days / 7, 'week', 'weeks'),\n (diff.days, 'day', 'days'),\n (diff.seconds / 3600, 'hour', 'hours'),\n (diff.seconds / 60, 'minute', 'minutes'),\n (diff.seconds, 'second', 'seconds'),\n )\n\n for period, singular, plural in periods:\n\n if not period:\n continue\n\n if period == 1:\n return u'%d %s ago' % (period, singular)\n else:\n return u'%d %s ago' % (period, plural)\n\n return default\n\n\nclass DenormalizedText(Mutable, types.TypeDecorator):\n \"\"\"\n Stores denormalized primary keys that can be\n accessed as a set.\n\n :param coerce: coercion function that ensures correct\n type is returned\n\n :param separator: separator character\n\n Source: https://github.com/imwilsonxu/fbone/blob/master/fbone/user/models.py#L13-L45\n \"\"\"\n\n impl = types.Text\n\n def __init__(self, coerce=int, separator=\" \", **kwargs):\n\n self.coerce = coerce\n self.separator = separator\n\n super(DenormalizedText, self).__init__(**kwargs)\n\n def process_bind_param(self, value, dialect):\n if value is not None:\n items = [str(item).strip() for item in value]\n value = self.separator.join(item for item in items if item)\n return value\n\n def process_result_value(self, value, dialect):\n if not value:\n return set()\n return set(self.coerce(item) for item in value.split(self.separator))\n\n def copy_value(self, value):\n return set(value)\n\n\nclass SelectDateWidget(object):\n \"\"\"\n Renders a DateTime field with 3 selects.\n For more information see: http://stackoverflow.com/a/14664504\n \"\"\"\n FORMAT_CHOICES = {\n '%d': [(x, str(x)) for x in range(1, 32)],\n '%m': [(x, str(x)) for x in range(1, 13)]\n }\n\n FORMAT_CLASSES = {\n '%d': 'select_date_day',\n '%m': 'select_date_month',\n '%Y': 'select_date_year'\n }\n\n def __init__(self, years=range(1930, datetime.utcnow().year+1)):\n super(SelectDateWidget, self).__init__()\n self.FORMAT_CHOICES['%Y'] = [(x, str(x)) for x in years]\n\n def __call__(self, field, **kwargs):\n field_id = kwargs.pop('id', field.id)\n html = []\n allowed_format = ['%d', '%m', '%Y']\n\n for format in field.format.split():\n if (format in allowed_format):\n choices = self.FORMAT_CHOICES[format]\n id_suffix = format.replace('%', '-')\n id_current = field_id + id_suffix\n\n kwargs['class'] = self.FORMAT_CLASSES[format]\n try:\n del kwargs['placeholder']\n except:\n pass\n\n html.append('')\n else:\n html.append(format)\n html.append(\n \"\"\"\"\"\".format(\n html_params(name=field.name, id=id_current, **kwargs)))\n\n html.append(' ')\n\n return HTMLString(''.join(html))\n","sub_path":"flaskbb/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":8302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"240273348","text":"from rest_framework import serializers\n\nfrom .models import *\n\n\nclass CardSerializer(serializers.ModelSerializer):\n value = serializers.SerializerMethodField()\n\n class Meta:\n model = Card\n fields = ['value']\n\n def get_value(self, obj):\n return str(obj)\n\n\nclass HandSerializer(serializers.ModelSerializer):\n card_list = CardSerializer(many=True)\n\n class Meta:\n model = Hand\n fields = ('id', 'card_list')\n\n\nclass PackSerializer(serializers.ModelSerializer):\n card_list = CardSerializer(many=True)\n\n class Meta:\n model = Pack\n fields = ('id', 'card_list')\n\n\nclass CardInPackSerializer(serializers.ModelSerializer):\n card = CardSerializer()\n\n class Meta:\n model = CardInPack\n fields = ('id', 'card', 'is_draw')\n\n\nclass BoardSerializer(serializers.ModelSerializer):\n card_list = CardInPackSerializer(many=True)\n\n class Meta:\n model = Board\n fields = ('id', 'card_list')\n\n\nclass UserSerializer(serializers.ModelSerializer):\n class Meta:\n model = User\n fields = ('id', 'name', 'money', 'online')\n\n\nclass UserInGamePublicSerializer(serializers.ModelSerializer):\n user = UserSerializer()\n\n class Meta:\n model = UserInGame\n fields = ('id', 'user', 'game', 'bet', 'in_game', 'is_dealer', 'is_turn')\n\n\nclass PokerGamePublicSerializer(serializers.ModelSerializer):\n board = BoardSerializer()\n useringame_set = UserInGamePublicSerializer(many=True)\n state = serializers.SerializerMethodField()\n\n class Meta:\n model = PokerGame\n fields = ('id','useringame_set', 'board', 'pot', 'blind', 'state', 'game_round')\n\n def get_state(self, obj):\n return list(filter(lambda dict : dict[0]==obj.state, PokerGame.POKER_GAME_STATE))[0][1]\n\n\nclass UserInGamePrivateSerializer(serializers.ModelSerializer):\n hand = HandSerializer()\n user = UserSerializer()\n game = PokerGamePublicSerializer()\n\n class Meta:\n model = UserInGame\n fields = ('id', 'user', 'hand', 'bet', 'in_game', 'is_dealer', 'is_turn', 'game')\n\n\nclass PokerGameLightSerializer(serializers.ModelSerializer):\n user_number = serializers.SerializerMethodField()\n\n class Meta:\n model = PokerGame\n fields = ('id', 'user_number', 'game_round')\n\n def get_user_number(self, obj):\n return obj.user_list.count()\n\n\n","sub_path":"poker_api/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":2379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"478861112","text":"# Input: 문자열\n# 생산 순서에 따라 Ex) SSSBSMMMBMMMMM\n# units\n# S: SCV 20\n# M: Marine 24\n#\n# buildings\n# C: Command Center 120\n# U: Supply Depot 40\n# B: Barracks 80\n#\n# 시간 단위는 Normal Gamespeed 기준에서 second 단위.\n# Fastest 는 30% 빠름\nimport simpy\nimport pandas as pd\nclass CommandCenter(object):\n def __init__(self, env, mineral_container, supply_container):\n self.building_no = 0\n self.building_type = 'c'\n self.unit_build_time = 22\n self.unit_number = 4\n self.env = env\n self.price = 400\n self.mineral_container = mineral_container\n self.supply_container = supply_container\n self.end_time = float('inf')\n self.build_slot = simpy.Resource(self.env, capacity=1)\n\n self.mining_number = self.unit_number\n\n def build_unit(self):\n yield self.env.timeout(self.unit_build_time)\n self.end_time = self.env.now\n self.unit_number += 1\n self.mining_number += 1\n\n\nclass Barracks(object):\n def __init__(self, env, mineral_container, supply_container, barracks_store):\n self.building_no = -1\n self.build_time = 60\n self.unit_build_time = 24\n self.building_type = 'b'\n self.env = env\n self.price = 150\n self.mineral_container = mineral_container\n self.supply_container = supply_container\n self.barracks_store = barracks_store\n self.end_time = env.now\n self.build_slot = simpy.Resource(self.env, capacity=1)\n\n self.unit_number = 0\n\n def build_unit(self):\n yield self.env.timeout(self.unit_build_time)\n self.end_time = self.env.now\n self.barracks_store.put(self.building_no)\n self.unit_number += 1\n\n\nclass SupplyDepot(object):\n def __init__(self, env, mineral_container):\n self.building_no = -1\n self.env = env\n self.building_type = 'u'\n self.price = 100\n self.build_time = 40\n self.mineral_container = mineral_container\n self.end_time = float('inf')\n self.unit_number = 0\n self.build_slot = simpy.Resource(self.env, capacity=1)\n\n#data_logs = pd.DataFrame(columns=['time',\n # 'current_mineral', 'mining_scv_number', 'total_scv_number',\n # 'supply_depot_number', 'supply_count', 'supply_capacity',\n # 'barracks_number', 'total_marine_number'])\n# gantt_chart = pd.DataFrame()\n\ndef mining_rate(scv_number):\n mining_rate_per_scv_min = [0, 65.0, 65.0, 65.0, 65.0, 65.0, 65.0, 65.0, 65.0, 65.0, # 0~9\n 62.5, 60.3, 58.65, 57.0, 55.8, 54.6, 53.65, 52.7, 51.0, 51.3] # 10~19\n if scv_number > len(mining_rate_per_scv_min):\n scv_number = len(mining_rate_per_scv_min)\n return mining_rate_per_scv_min[scv_number]*scv_number/60.0\n\n\ndef mine_mineral(env, mineral_container, command_center, building_list):\n while True:\n yield env.timeout(1)\n yield mineral_container.put(mining_rate(command_center.unit_number))\n # print(f\"{env.now}\\t\"\n # f\"\\t{mineral_container.level}\\t\"\n # f\"\\t{command_center.supply_container.level}\\t\"\n # f\"\\t{[x.unit_number for x in building_list]}\\t\"\n # f\"mining_scv_number\\t{command_center.mining_number}\\t\"\n # f\"scv_number\\t{command_center.unit_number}\\t\"\n # f\"production_slot\\t{[x.build_slot.count for x in building_list]}\\t\"\n # )\n\n\ndef build_unit(env, building):\n with building.build_slot.request() as req:\n yield req\n yield env.process(building.build_unit())\n\n\ndef build_building(env: simpy.Environment, building, building_list: list, command_center: CommandCenter, barracks_store):\n command_center.mining_number -= 1\n yield env.timeout(building.build_time)\n building.building_no = len(building_list)\n building_list.append(building)\n if building.building_type == 'b':\n barracks_store.put(len(building_list)-1)\n command_center.mining_number += 1\n\n\ndef setup(env, order_string):\n global csv_output, end_production_time\n building_list = []\n mineral_container = simpy.Container(env=env, init=50)\n supply_container = simpy.Container(env=env, init=6)\n barracks_store = simpy.Store(env=env)\n building_list.append(CommandCenter(env, mineral_container, supply_container))\n env.process(mine_mineral(env=env, mineral_container=mineral_container, command_center=building_list[0],\n building_list=building_list))\n\n for next_product in order_string:\n if next_product == 's': # Add SCV\n yield mineral_container.get(50)\n yield supply_container.get(1)\n env.process(build_unit(env, building_list[0]))\n\n elif next_product == 'b': # Add Barracks\n yield mineral_container.get(150)\n env.process(build_building(env, Barracks(env, mineral_container, supply_container, barracks_store), building_list,\n building_list[0], barracks_store))\n elif next_product == 'm': # Add Marine\n while len(building_list) == 1: # wait until first barracks\n yield env.timeout(1)\n yield mineral_container.get(50)\n yield supply_container.get(1)\n building_no = yield barracks_store.get()\n env.process(build_unit(env, building_list[building_no]))\n end_production_time = building_list[building_no].end_time + building_list[building_no].unit_build_time\n elif next_product == 'u': # Add Supply Depot\n yield mineral_container.get(100)\n env.process(\n build_building(env, SupplyDepot(env=env, mineral_container=mineral_container), building_list,\n building_list[0], barracks_store))\n supply_container.put(8)\n # csv_output = csv_output.append({'order': order_string, 'end_time': end_production_time}, ignore_index=True)\n print(order_string, f\"\\t{end_production_time}\", end='')\n\n\n\n# #\nSIM_TIME = 10*30\n\nend_production_time = 800\nenv = simpy.Environment()\ninput_string = \"bbmmbmmmummm\"\nenv.process(setup(env, input_string))\nenv.run(until=SIM_TIME)\n\nprint(f\"\\t{end_production_time}\", end='')\n\n#\n#\n# marine_no = 8\n# for barracks_no in range(1, 5):\n# for scv_no in range(6-barracks_no):\n# supply_no = 1\n# orders = pd.read_csv(f'./input/m{marine_no}b{barracks_no}s{scv_no}u{supply_no}.txt')\n# order_no = 0\n# total_order = len(orders['order'])\n# csv_output = pd.DataFrame(columns=[\"order\", \"end_time\"])\n# for i in orders['order']:\n# env = simpy.Environment()\n# env.process(setup(env, i))\n# env.run(until=SIM_TIME)\n# print(f\"\\t{order_no}/{total_order}\\t\", barracks_no, scv_no)\n# order_no += 1\n# csv_output.to_csv(rf'./output2/m{marine_no}b{barracks_no}s{scv_no}u{supply_no}.csv', index=False)\n#\n#\n# print(csv_output)\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7054,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"99125821","text":"#!/usr/bin/python\nimport os\nimport sys\nimport numpy as np\nimport rospy\nfrom common.policies import build_policy\nfrom common.rollout import RolloutWorker\nfrom acer import Model, Acer\nfrom collections import deque\n\nNODE = \"RLAgent\"\nMODE = 'acer_mlp' # 'il' # nfq\n# MODEL_SAVE_PATH = os.path.join(os.environ['HOME'], 'grablab-ros/src/projects/sliding_policies/models/' + MODE + '/')\nMODEL_SAVE_PATH = os.path.join(os.environ['HOME'], 'grablab-ros/src/external/rl-texplore-ros-pkg/src/rl_agent/src/Agent/')\n\n\ndef train(model, rollout_worker, n_epochs, n_batches, demo_file):\n Q_history = deque()\n q_hist, critic_loss_hist, actor_loss_hist, ent_hist, bc_loss_hist = [], [], [], [], []\n if model.bc_loss == 1:\n model.initDemoBuffer(demo_file)\n for epoch in range(n_epochs):\n #print('ok')\n if rollout_worker.compute_Q:\n episode, mean_Q = rollout_worker.generate_rollouts()\n else:\n episode = rollout_worker.generate_rollouts()\n # TODO Check how store_episode will go\n model.store_episode(episode)\n critic_loss_que, actor_loss_que, ent_que = [], [], []\n bc_loss_que = []\n for i in range(n_batches): # update q-values\n critic_loss, actor_loss, ent, bc_loss_np = model.train()\n critic_loss_que.append(critic_loss); actor_loss_que.append(actor_loss)\n ent_que.append(ent); bc_loss_que.append(bc_loss_np)\n # print(\"n_batch: {}, critic_loss: {}, actor_loss: {}\".format(i, critic_loss, actor_loss))\n print(\"Mean Q-value: {}\".format(mean_Q))\n mean_critic_loss = np.mean(critic_loss_que)\n mean_actor_loss = np.mean(actor_loss_que)\n mean_ent = np.mean(ent_que)\n mean_bc_loss = np.mean(bc_loss_que)\n print(\"Mean critic loss: {}\".format(mean_critic_loss))\n print(\"Mean actor loss: {}\".format(mean_actor_loss))\n print(\"Mean bc loss: {}\".format(mean_bc_loss))\n print(\"Mean entopy: {}\".format(mean_ent))\n q_hist.append(mean_Q)\n critic_loss_hist.append(mean_critic_loss)\n actor_loss_hist.append(mean_actor_loss)\n ent_hist.append(mean_ent)\n bc_loss_hist.append(mean_bc_loss)\n #model.update_target_net() # update the target net less frequently\n np.save('/home/grablab/grablab-ros/src/external/rl-texplore-ros-pkg/src/rl_agent/src/Agent/results/q_val.npy', np.array(q_hist))\n np.save('/home/grablab/grablab-ros/src/external/rl-texplore-ros-pkg/src/rl_agent/src/Agent/results/cri_loss.npy', np.array(critic_loss_hist))\n np.save('/home/grablab/grablab-ros/src/external/rl-texplore-ros-pkg/src/rl_agent/src/Agent/results/actor_loss.npy', np.array(actor_loss_hist))\n np.save('/home/grablab/grablab-ros/src/external/rl-texplore-ros-pkg/src/rl_agent/src/Agent/results/ent.npy', np.array(ent_hist))\n np.save('/home/grablab/grablab-ros/src/external/rl-texplore-ros-pkg/src/rl_agent/src/Agent/results/bc_loss.npy', np.array(bc_loss_hist))\n save_loc = model.save_model()\n print('saved model at : {} after {} epochs'.format(save_loc, epoch+1))\n\ndef learn(model, runner, nenvs, nsteps, replay_start, replay_ratio, total_timesteps):\n log_interval = 10 # this is not used for now\n acer = Acer(runner, model, log_interval)\n nbatch = nenvs*nsteps\n for acer.steps in range(0, total_timesteps, nbatch):\n acer.call(on_policy=True) # TODO: Modify generate_rollout in rollout.py for HER.\n if model.buffer.has_atleast(replay_start):\n n = np.random.poisson(replay_ratio)\n for _ in range(n):\n acer.call(on_policy=False) # no rollout with T42 in this\n return model\n\ndef save_episode(episode, i):\n obs = episode['o']\n print(obs)\n SAVE_DIR = \"/home/grablab/grablab-ros/src/external/rl-texplore-ros-pkg/src/rl_agent/src/Agent/data-init-goal/original\"\n file_path = os.path.join(SAVE_DIR, 'episode_'+str(i)+'.out')\n obs_reshaped = np.squeeze(obs)\n np.savetxt(file_path, obs_reshaped, delimiter=',')\n\ndef save_episode_keyboard(episode, i):\n obs = episode['o'][0]\n actions = episode['u'][0]\n print(\"In save_episode_keyboard...obs.shape: {}, u.shape: {}\".format(obs.shape, actions.shape))\n obs_actions_combined = np.concatenate((obs, actions), axis=1)\n SAVE_DIR = \"/home/grablab/grablab-ros/src/external/rl-texplore-ros-pkg/src/rl_agent/src/Agent/data-init-goal/keyboard_demo\"\n file_path = os.path.join(SAVE_DIR, 'episode_'+str(i)+'.out')\n obs_actions_combined = np.squeeze(obs_actions_combined)\n np.savetxt(file_path, obs_actions_combined, delimiter=',')\n\n\ndef collect_random_rl_data(runner):\n i = 1\n while True:\n print(\"Episode: {}\".format(i))\n episode = runner.generate_rollouts()\n if episode['drop'][0][0][0] == 1 or episode['stuck'][0][0][0] == 1:\n print(\"Drop happened at time step 1. Ignoring this episode...\")\n continue\n save_episode(episode, i)\n i += 1\n\ndef record_demonstration_w_keyboard(runner):\n i = 1\n while True:\n print(\"Episode: {}\".format(i))\n # Do I need to limit the number of rollouts?\n episode = runner.generate_rollouts_w_keyboard()\n if episode['drop'][0][0][0] == 1 or episode['stuck'][0][0][0] == 1:\n print(\"Drop happened at time step 1. Ignoring this episode...\")\n continue\n save_episode_keyboard(episode, i)\n i += 1\n\n\nif __name__ == '__main__':\n rospy.init_node(NODE)\n rospy.loginfo('started RLAgent node')\n dims = {'o': 13, 'u': 9}\n model_name = 'il_policy_for_a2c' #'Jun2714152018_eps1_Jun2714312018_eps1_Jul816002018_eps1'\n checkpoint_path = os.path.join(MODEL_SAVE_PATH, model_name)\n n_epochs = 100000\n random_eps = 0.1\n bc_loss = True #False\n nenvs = 2 # the batch size in training. Something we can treat in parallel.\n nsteps = 40 # This should just be the number of steps in a sampled trajectories. Should be dealt in def call() in Acer()\n batch_size = 40 # Check if these guys matter at all in this new setup; might be from old scripts\n # This acutually matters for ReplayBuffer. This should be the number of steps in a sampled trajectory\n demo_batch_size = 40 # Check if these guys matter at all in this new setup; might be from old scripts\n # bc_loss = True # See def configure_mlp in config.py too\n num_rollouts = 50 # This is a new variable. Should only be used in rollout.py and ReplayBuffer. Remember that the T as in the episode batch shape is this num_rollouts.\n network = 'mlp'\n network_kargs = {}\n policy = build_policy(network, estimate_q=True, **network_kargs)\n #TODO: Test this ILRL_acer.py upto here now that I changed the observation dimension.\n\n '''\n def __init__(self, policy, num_states, num_actions, nenvs, nsteps,\n ent_coef, q_coef, gamma, max_grad_norm, lr,\n rprop_alpha, rprop_epsilon, total_timesteps, lrschedule,\n c, trust_region, alpha, delta): \n '''\n\n ent_coef =0.01 ; q_coef=0.5 ; gamma=0.99 ; max_grad_norm=10 ;\n rprop_alpha=0.99 ; rprop_epsilon=1e-5 ; total_timesteps=int(10e5) ;\n trust_region=False; alpha=0.99 ; delta =1 ; # what are alpha and delta again?\n lrschedule='linear' ; c =10.0 ; lr =7e-4\n buffer_size=10000; bc_loss=False\n model = Model(policy, num_states=dims['o'], num_actions=dims['u'], nenvs=nenvs, nsteps=nsteps, num_rollouts=num_rollouts,\n ent_coef=ent_coef, q_coef=q_coef, gamma=gamma, max_grad_norm=max_grad_norm, lr=lr,\n rprop_alpha=rprop_alpha, rprop_epsilon=rprop_epsilon, total_timesteps=total_timesteps,\n lrschedule=lrschedule, c=c, trust_region=trust_region, alpha=alpha, delta=delta,\n buffer_size=buffer_size, bc_loss=bc_loss)\n# bc_loss=bc_loss,\n# batch_size=40, demo_batch_size=20,\n# model_name=model_name, save_path=MODEL_SAVE_PATH, checkpoint_path=checkpoint_path, restore=True)\n print('gggggggggggg')\n print(model)\n print('gggggggggggg')\n\n record_demo_data_w_keyboard=True\n rollout_worker = RolloutWorker(model, dims, num_rollouts, use_target_net=True, compute_Q=True, random_eps=random_eps, record_demo_data_w_keyboard=True)\n\n # n_batches = 10 #2\n demo_file = '/home/grablab/grablab-ros/src/external/rl-texplore-ros-pkg/src/rl_agent/src/Agent/data/demodata.npy'\n #train(model=model, rollout_worker=rollout_worker, n_epochs=n_epochs, n_batches=n_batches, demo_file=demo_file)\n replay_start = 2 # 1000 # int, the sampling from the replay buffer does not start until replay buffer has at least that many samples\n replay_ratio = 4 # int, how many (on averages) batches of data fo sample from the replay buffer take after batch from the environment\n\n #collect_random_rl_data(runner=rollout_worker)\n record_demonstration_w_keyboard(runner=rollout_worker)\n\n '''\n learn(model=model, runner=rollout_worker, nenvs=nenvs, nsteps=nsteps, replay_start=replay_start,\n replay_ratio=replay_ratio, total_timesteps=total_timesteps)\n '''","sub_path":"src/rl_agent/src/Agent/ILRL_acer.py","file_name":"ILRL_acer.py","file_ext":"py","file_size_in_byte":9103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"364211738","text":"import serial\nfrom time import sleep\nimport glob\n\n\nclass cnc():\n\n def __init__(self, serial_port = None):\n # Default values in case not set by user:\n self.settings = {\n \"cameraOffset\": [55.05, -3.64],\n \"zCamera\": None,\n \"zContact\": None,\n \"zDrillDepth\": 0,\n \"zSeparation\": 5,\n \"zFastMargin\": 0.5,\n \"DrillFeedRate\": 100,\n \"drillSpeed\": 250,\n \"vG0\": 2000,\n \"vG1\": 300,\n \"PLaser\": 0.02\n }\n # Find valid serial ports with Smoothies connected:\n self.get_serial_ports(keyword=\"usbmodem\", query=\"\\n\", response=\"ok\")\n self.set_serial_port(serial_port)\n\n def set_serial_port(self, serport):\n try:\n self.ser = serial.Serial('/dev/tty.' + serport, 9600)\n if self.ser.is_open and self.query_response(\"\\n\",\"ok\"):\n self.is_valid = True\n self.set_units_mm()\n self.set_G0_speed()\n self.set_G1_speed()\n except:\n self.is_valid = False\n\n def get_serial_ports(self, keyword = \"\", query = None, response = None):\n serial_ports = [s.split('.')[1] for s in glob.glob('/dev/tty.*') if keyword in s]\n self.serial_ports = []\n for serial_port in serial_ports:\n try:\n self.ser = serial.Serial('/dev/tty.' + serial_port, 9600)\n if self.ser.is_open:\n if self.query_response(query, response):\n self.serial_ports = self.serial_ports + [serial_port]\n self.ser.close()\n except:\n pass\n\n def query_response(self, query = None, response = None):\n if query is None or response is None:\n return True\n self.ser.read_all()\n self.ser.write(bytes(query,'utf-8'))\n s = self.ser.readline().decode('utf-8')\n if s.__contains__(response):\n return True\n else:\n return False\n\n def set_units_mm(self):\n if self.is_valid:\n self.ser.write(b'G21\\n')\n\n def motors_off(self):\n if self.is_valid:\n self.ser.write(b'M18\\n')\n\n def set_G0_speed(self,v=None):\n if v is None:\n v = self.settings[\"vG0\"]\n if self.is_valid:\n self.ser.write(b'G0 F%f\\n' % (v))\n\n def set_G1_speed(self,v=None):\n if v is None:\n v = self.settings[\"vG1\"]\n if self.is_valid:\n self.ser.write(b'G1 F%f\\n' % (v))\n\n def set_laser_power(self,P=None):\n if P is None:\n P = self.settings[\"PLaser\"]\n if self.is_valid:\n self.ser.write(b'G0 S%f\\n' % (P))\n\n def move_rel_mm(self,x = None, y = None, z = None):\n if self.is_valid:\n coords = \" \".join(\n [axis + str(offset) for axis, offset in zip([\"X\", \"Y\", \"Z\"], [x, y, z]) if offset is not None])\n print(\"Moving by %s ...\" % (coords))\n self.ser.write((\"G91\\nG0 \" + coords + \"\\nG90\\n\").encode('UTF-8'))\n\n def move_rel_z_mm(self,z):\n if self.is_valid:\n self.move_rel_mm(z=z)\n\n def move_abs_mm(self, x = None, y = None, z = None):\n if self.is_valid:\n coords = \" \".join(\n [axis + str(offset) for axis, offset in zip([\"X\", \"Y\", \"Z\"], [x, y, z]) if offset is not None])\n print(\"Moving to %s ...\" % (coords))\n self.ser.write((\"G90\\nG0 \" + coords + \"\\n\").encode('UTF-8'))\n\n def move_abs_z_mm(self,z):\n if self.is_valid:\n self.move_abs_mm(z=z)\n\n def move_abs_feed_mm(self, x = None, y = None, z = None, f=None):\n if self.is_valid:\n speed_string = \"\"\n if f is not None:\n speed_string = (\"F%f \" % f)\n coords = \" \".join(\n [axis + str(offset) for axis, offset in zip([\"X\", \"Y\", \"Z\"], [x, y, z]) if offset is not None])\n print(\"Moving to %s ...\" % (coords))\n self.ser.write((\"G90\\nG1 \" + speed_string + coords + \"\\n\").encode('UTF-8'))\n\n def move_abs_z_feed_mm(self, z = None, f = None):\n if self.is_valid:\n self.move_abs_feed_mm(z=z, f=f)\n\n def get_state(self):\n try:\n self.ser.read_all()\n self.ser.write(b'?')\n s=self.ser.readline().decode('utf-8')\n if s.__contains__('|'):\n vs = s.strip('<>\\n').split('|')\n result = {v.split(':')[0]:[float(d) for d in v.split(':')[1].split(',')] for v in vs[1:]}\n result['Status'] = vs[0]\n elif s.__contains__('<') and s.__contains__('>'):\n vs = s.strip('<>\\n\\r').replace('MPos:', '').replace('WPos:', '').split(',')\n result = {'Status': vs[0], 'MPos': [float(v) for v in vs[1:4]], 'WPos': [float(v) for v in vs[4:7]], 'F':[float('nan')]*2}\n else:\n result = {'Status': 'undefined', 'MPos': [float('nan')] * 3, 'WPos': [float('nan')] * 3, 'F': [float('nan')] * 2}\n except:\n result = {'Status':'undefined', 'MPos':[float('nan')]*3, 'WPos':[float('nan')]*3, 'F':[float('nan')]*2}\n return result\n\n def get_pos_mm(self):\n return self.get_state()['WPos']\n\n def get_progress(self):\n try:\n self.ser.read_all()\n self.ser.write(b'progress\\n')\n s = self.ser.readline().decode('utf-8')\n percent = int(s.split(\", \")[1].split(\" % \")[0])\n elapsed = s.split(\", \")[2].split(\": \")[-1].rstrip()\n remaining = s.split(\", \")[3].split(\": \")[-1].rstrip()\n return percent, elapsed, remaining\n except:\n return 0, \"na\", \"na\"\n\n def set_zContact(self):\n if self.is_valid:\n x0,y0,z0=self.get_pos_mm()\n self.settings[\"zContact\"]=z0\n print('zContact set to %fmm' % (self.settings[\"zContact\"]))\n\n def set_zCamera(self):\n if self.is_valid:\n x0,y0,z0=self.get_pos_mm()\n self.settings[\"zCamera\"]=z0\n print('zCamera set to %fmm' % (self.settings[\"zCamera\"]))\n\n def home_z(self):\n if self.is_valid:\n print('Homing z-axis ... ')\n self.ser.write(b'G28 Z\\n')\n while (not self.is_idle()):\n sleep(0.05)\n self.motors_off()\n print('done. ')\n\n def home(self):\n if self.is_valid:\n print('Homing all axes ... ')\n self.ser.write(b'G28\\n')\n while (not self.is_idle()):\n sleep(0.05)\n self.motors_off()\n print('done. ')\n\n def set_coordinates(self,x=None, y=None, z=None):\n if self.is_valid:\n coords = \" \".join([axis+str(offset) for axis,offset in zip([\"X\",\"Y\",\"Z\"],[x,y,z]) if offset is not None])\n print(\"Setting %s ...\" % (coords))\n self.ser.write((\"G92 \" + coords + \"\\n\").encode('UTF-8'))\n\n def drill_on(self,speed=50):\n if self.is_valid:\n print('Turn drill on (speed %f)' % (speed))\n ramp_template = list(range(5,30,5))+list(range(50,255,50))\n ramp = [s for s in ramp_template if s chrs.index(fields2[2]):\n D.setdefault(k2, [])\n D[k2].append([int(fields2[3]), int(fields1[3])])\n elif k1 in D:\n D[k1].append([int(fields1[3]), int(fields2[3])])\n elif k2 in D:\n D[k2].append([int(fields2[3]), int(fields1[3])])\n else:\n break\nouFile = open(sys.argv[1]+'.sorted', 'w')\n\ndef cmp_fun(x , y):\n if x[0] < y[0]:\n return -1\n elif x[0] > y[0]:\n return 1\n else:\n if x[1] < y[1]:\n return -1\n elif x[1] > y[1]:\n return 1\n else:\n return 0\ndef cmp_fun2(x, y):\n if chrs.index(x[0].split('\\t')[0]) < chrs.index(y[0].split('\\t')[0]):\n return -1\n elif chrs.index(x[0].split('\\t')[0]) > chrs.index(y[0].split('\\t')[0]):\n return 1\n else:\n if chrs.index(x[0].split('\\t')[1]) < chrs.index(y[0].split('\\t')[1]):\n return -1\n elif chrs.index(x[0].split('\\t')[1]) > chrs.index(y[0].split('\\t')[1]):\n return 1\n else:\n return 0\n\nd = D.items()\nd.sort(cmp = lambda x,y :cmp_fun2(x,y))\nfor item in d:\n item[1].sort(cmp=lambda x,y:cmp_fun(x,y))\n for it in item[1]:\n ouFile.write(item[0] + '\\t' + str(it[0]) + '\\t' +str(it[1]) + '\\n')\n\ninFile.close()\nouFile.close()\n","sub_path":"DayDayCoding/pySV/2.sort.py","file_name":"2.sort.py","file_ext":"py","file_size_in_byte":2101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"587558161","text":"\n\"\"\"\nModule to create topo and qinit data files for this example.\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom clawpack.geoclaw.topotools import Topography\nfrom numpy import *\n\ndef maketopo():\n \"\"\"\n Output topography file for the entire domain\n \"\"\"\n nxpoints = 201\n nypoints = 201\n xlower = -1000.e0\n xupper = 1000.e0\n yupper = 1000.e0\n ylower = -1000.e0\n outfile= \"bowl.topotype2\" \n\n topography = Topography(topo_func=topo)\n topography.x = linspace(xlower,xupper,nxpoints)\n topography.y = linspace(ylower,yupper,nypoints)\n topography.write(outfile, topo_type=2, Z_format=\"%22.15e\")\n\ndef makeqinit():\n \"\"\"\n Create qinit data file\n \"\"\"\n nxpoints = 101\n nypoints = 101\n xlower = -100.e0\n xupper = 100.e0\n yupper = 100.e0\n ylower = -100.e0\n outfile= \"hump.xyz\" \n\n topography = Topography(topo_func=qinit)\n topography.x = linspace(xlower,xupper,nxpoints)\n topography.y = linspace(ylower,yupper,nypoints)\n topography.write(outfile, topo_type=1)\n\ndef topo(x,y):\n \"\"\"\n Parabolic bowl\n \"\"\"\n # value of z at origin: Try zmin = 80 for shoreline or 250 for no shore\n zmin = 80.\n z = 1.e-2*(x**2 + y**2) - zmin\n\n # r = x**2 + y**2\n # z = where(r<80**2, -zmin, zmin)\n return z\n\n\ndef qinit(x,y):\n \"\"\"\n Gaussian hump:\n \"\"\"\n from numpy import where\n ze = -((x+0e0)**2 + (y+0e0)**2)/100\n z = where(ze>-10, 4.0*exp(ze), 0.)\n return z\n\nif __name__=='__main__':\n maketopo()\n makeqinit()\n","sub_path":"examples/multi-layer/bowl-radial/maketopo.py","file_name":"maketopo.py","file_ext":"py","file_size_in_byte":1518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"563993330","text":"from sklearn.datasets import load_iris\r\ndata = load_iris()\r\nx = data.data\r\ny = data.target\r\n\r\n\r\n\r\nfrom sklearn import model_selection\r\nfrom sklearn.metrics import classification_report,confusion_matrix\r\n\r\nxtrain, xtest, ytrain, ytest = model_selection.train_test_split(x,y,test_size=0.25,random_state=0)\r\n\r\n# # inbuilt naive bayes\r\nfrom sklearn.naive_bayes import MultinomialNB\r\nclf = MultinomialNB()\r\nclf.fit(xtrain,ytrain)\r\nypred = clf.predict(xtest)\r\nprint(\"Score for algorithm : \",clf.score(xtest,ypred))\r\nprint(classification_report(ytest,ypred))\r\nprint(confusion_matrix(ytest,ypred))\r\n\r\n\r\n\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\nplt.plot(xtrain,ytrain, color ='r',label = 'Trained data')\r\n\r\nplt.ylabel('Y axis')\r\nplt.xlabel('X axis')\r\nplt.legend()\r\n\r\nplt.show()\r\n\r\n\r\nimport matplotlib.pyplot as plt\r\nplt.plot(xtest,ypred, color ='g',label = 'Predicted data',linewidth = 9)\r\n\r\n\r\nplt.ylabel('Y axis')\r\nplt.xlabel('X axis')\r\nplt.legend()\r\n\r\nplt.show()\r\n\r\nplt.plot(xtest,ytest, color ='r',label = 'Test data')\r\n\r\n\r\nplt.ylabel('Y axis')\r\nplt.xlabel('X axis')\r\nplt.legend()\r\n\r\nplt.show()\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":"continous.py","file_name":"continous.py","file_ext":"py","file_size_in_byte":1113,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"7970517","text":"# flask and other extensions instantiated here.\n\nfrom flask import Flask\nimport logging\nfrom pymongo import MongoClient\n\n# -------------------- logger stuff ------------------------------\n\n\n# set all the custom logging information needed\nlogging.basicConfig(filename='main.log',level=logging.DEBUG)\n\n# define a Handler which writes INFO messages or higher to the sys.stderr\nconsole = logging.StreamHandler()\nconsole.setLevel(logging.INFO)\n# set a format which is simpler for console use\nformatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')\n# tell the handler to use this format\nconsole.setFormatter(formatter)\n# add the handler to the root logger\nlogging.getLogger('').addHandler(console)\n\n\n# create the main app for flask\napp = Flask(__name__)\n\n\n# -------------------- database stuff ------------------------------\n\nmongo = MongoClient('mongodb://localhost:27017/cpf');\ndb = mongo.get_default_database();\n\n\n\n\n\n","sub_path":"server/extensions.py","file_name":"extensions.py","file_ext":"py","file_size_in_byte":932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"514075430","text":"import sys\nimport re\n\nif len(sys.argv) < 2:\n print(\"version file must be set\")\n exit(1)\n\nver_pattern = re.compile(r\"\\d+(\\.\\d+){3}(_\\w+)?\")\n\nwith open(sys.argv[1], \"r\") as vf:\n vs = vf.read().replace(\"\\n\", \"\")\n\nif not ver_pattern.fullmatch(vs):\n print(\"version format is uncorrect\")\n exit(1)\n\nwith open(sys.argv[1], \"w\") as vf:\n vn = vs.split(\"_\")\n if len(vn) > 0:\n vnn = vn[0].split(\".\")\n vf.write(vnn[0] + \".\" + vnn[1] + \".\" + vnn[2] + \".\" + str(int(vnn[3]) + 1))\n if len(vn) > 1:\n vf.write(\"_\" + vn[1])\n","sub_path":"sampleplugin/build-tools/version_plus.py","file_name":"version_plus.py","file_ext":"py","file_size_in_byte":550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"34"} +{"seq_id":"223586360","text":"# Duration\n\nimport numpy as np\nimport pandas as pd\nimport plotly.express as px\nimport plotly.graph_objects as go\nfrom plotly.subplots import make_subplots\n\ndf: pd.DataFrame\n\n\n\ndef get_duration_per_year(year_range, month_range, si_range, area_range, map_size_radio_items, hours_range,\n country_list, interval_radio_items):\n filtered_df = filter_events(year_range, month_range, si_range, area_range, map_size_radio_items, hours_range, country_list)\n if filtered_df.size == 0:\n return {}\n\n event_property = 'event_length'\n plot1, plot2, plot3, scale = build_plots(event_property, filtered_df, interval_radio_items)\n\n return plot_property_per_time_scale(plot1, plot2, plot3, 'Year', 'Duration', 'Duration over time', scale)\n\n\ndef get_severity_per_year(year_range, month_range, si_range, area_range, map_size_radio_items, hours_range,\n country_list, interval_radio_items):\n filtered_df = filter_events(year_range, month_range, si_range, area_range, map_size_radio_items, hours_range, country_list)\n if filtered_df.size == 0:\n return {}\n\n event_property = 'event_si'\n plot1, plot2, plot3, scale = build_plots(event_property, filtered_df,interval_radio_items)\n\n return plot_property_per_time_scale(plot1, plot2, plot3, 'Year', 'Severity', 'Severity over time', scale)\n\n\ndef get_area_per_year(year_range, month_range, si_range, area_range, map_size_radio_items, hours_range,\n country_list, interval_radio_items):\n filtered_df = filter_events(year_range, month_range, si_range, area_range, map_size_radio_items, hours_range, country_list)\n if filtered_df.size == 0:\n return {}\n\n event_property = 'event_area'\n plot1, plot2, plot3, scale = build_plots(event_property, filtered_df, interval_radio_items)\n\n return plot_property_per_time_scale(plot1, plot2, plot3, 'Year', 'Area', 'Area over time', scale)\n\n\ndef get_precipitation_per_year(year_range, month_range, si_range, area_range, map_size_radio_items, hours_range,\n country_list, interval_radio_items):\n filtered_df = filter_events(year_range, month_range, si_range, area_range, map_size_radio_items, hours_range, country_list)\n if filtered_df.size == 0:\n return {}\n\n event_property = 'event_pre'\n plot1, plot2, plot3, scale = build_plots(event_property, filtered_df, interval_radio_items)\n\n return plot_property_per_time_scale(plot1, plot2, plot3, 'Year', 'Precipitation', 'Precipitation over time', scale)\n\n\ndef get_events_per_year(year_range, month_range, si_range, area_range, map_size_radio_items, hours_range,\n country_list, grouped_by_country, interval_radio_items):\n filtered_df = filter_events(year_range, month_range, si_range, area_range, map_size_radio_items, hours_range, country_list)\n if filtered_df.size == 0:\n return {}\n\n events_filtered = filtered_df.drop_duplicates(subset=['event_id'], keep='first')\n events_filtered = add_year_cluster(interval_radio_items, events_filtered)\n\n events_per_year = events_filtered.groupby('event_year')['event_id'].nunique().reset_index()\n events_mean = events_per_year.event_id.mean()\n\n events_per_cluster = events_filtered.groupby('year_cluster')['event_id'].count()\n events_per_cluster = pd.DataFrame(events_per_cluster)\n events_per_cluster['avg_per_cluster'] = events_per_cluster.event_id / interval_radio_items\n events_per_cluster.reset_index(inplace=True)\n\n year_min = events_filtered.event_year.min()\n year_max = events_filtered.event_year.max()\n df_avg = pd.DataFrame(index=np.arange(year_max - year_min + 1), columns=['avg'])\n df_avg.index = df_avg.index + year_min\n df_avg['avg'] = events_mean\n\n plot1: Plot\n plot3: Plot\n if grouped_by_country:\n events_per_year_country = events_filtered.groupby(['event_year', 'country'])['event_id'].nunique().reset_index()\n events_per_year_country.country[~events_per_year_country.country.isin(['DE', 'CZ', 'IT', 'INT', 'TN'])] = 'other'\n plot1 = Plot(events_per_year_country.event_year, events_per_year_country.event_id, 'Per year',\n events_per_year_country.country)\n plot3 = Plot(events_per_cluster.year_cluster, events_per_cluster.avg_per_cluster, 'avg per interval')\n \n else:\n plot1 = Plot(events_per_cluster.year_cluster, events_per_cluster.avg_per_cluster, 'avg per interval')\n plot3 = None\n\n plot2 = Plot(df_avg.index, df_avg.avg, 'Overall average')\n\n return plot_property_per_time_scale(plot1, plot2, plot3, 'Month', 'Events', 'Events average per Year', 'linear')\n\n\ndef get_events_per_month(year_range, month_range, si_range, area_range, map_size_radio_items, hours_range,\n country_list):\n events_filtered = filter_events(year_range, month_range, si_range, area_range, map_size_radio_items, hours_range, country_list)\n if events_filtered.size == 0:\n return {}\n\n events_per_month_country = events_filtered.groupby(['event_month', 'country'])['event_id'].nunique().reset_index()\n events_per_month_country = pd.DataFrame(events_per_month_country)\n events_per_month_country.country[~events_per_month_country.country.isin(['DE', 'CZ', 'IT', 'INT', 'TN'])] = 'other'\n\n events_per_month = events_filtered.groupby('event_month')['event_id'].nunique().reset_index()\n avg = events_per_month.event_id.mean()\n\n plot1 = Plot(events_per_month_country.event_month, events_per_month_country.event_id, 'Per month',\n events_per_month_country.country)\n\n df_avg = pd.DataFrame(index=np.arange(13), columns=['avg'])\n df_avg = df_avg.drop(df_avg.index[0])\n df_avg['avg'] = avg\n\n plot2 = Plot(df_avg.index, df_avg.avg, 'Overall average')\n plot3 = None\n\n return plot_property_per_time_scale(plot1, plot2, plot3, 'Month', 'Events', 'Events average per Month', 'linear')\n\n\ndef init_data():\n global df\n # df = pd.read_pickle(\"../dash_v1/event_filtered.pickle\")\n df = pd.read_pickle(\"event_filtered.pickle\")\n df.reset_index(inplace=True, drop=True)\n\n # mean precipitation as extra column\n # tmp = df.groupby(['event_id']).meanPre.mean()\n # tmp = pd.DataFrame(tmp).reset_index()\n # tmp = tmp.rename(columns={'event_id': 'event_id', 'meanPre': 'event_pre'})\n # df = pd.merge(tmp, df, on='event_id', how='right')\n\n # exrtacting day from start date and capturing as extra column\n df['day'] = [e.strftime('%Y-%m-%d') for e in df.event_start]\n df['event_si'] = df['event_si'] * 100\n df['event_area'] = df['event_area'] * 10\n df = df[\n ['event_id', 'event_start', 'event_area', 'event_length', 'event_si', 'event_pre', 'event_year', 'event_month',\n 'day', 'country']]\n\n\n# read once at initialization of webserver and on every change\ndef filter_events(year_range, month_range, si_range, area_range, map_size_radio_items, hours_range, country_list):\n filtered_data = df[df[\"country\"].isin(country_list)]\n filtered_data = filtered_data[\n (filtered_data['event_year'] >= year_range[0]) & (filtered_data['event_year'] <= year_range[1])]\n filtered_data = filtered_data[\n (filtered_data['event_month'] >= month_range[0]) & (filtered_data['event_month'] <= month_range[1])]\n filtered_data = filtered_data[\n (filtered_data['event_si'] >= si_range[0]) & (filtered_data['event_si'] <= si_range[1])]\n filtered_data = filtered_data[\n (filtered_data['event_area'] >= area_range[0]) & (filtered_data['event_area'] <= area_range[1])]\n filtered_data = filtered_data[\n (filtered_data['event_length'] >= hours_range[0]) & (filtered_data['event_length'] <= hours_range[1])]\n return filtered_data\n\n\ndef add_year_cluster(interval_radio_items, filtered_df):\n events_filtered = filtered_df.sort_values(by=['event_year'])\n events_filtered = events_filtered.reset_index(drop=True)\n year = events_filtered['event_year'].min()\n j = year + round(interval_radio_items / 2)\n\n df_length = len(events_filtered.index)\n for i in range(df_length):\n tmp = events_filtered['event_year'].values[i]\n if year < tmp:\n delta_year = tmp - year\n quotient_interval = delta_year / interval_radio_items\n j = j + (np.math.trunc(quotient_interval) * interval_radio_items)\n year = year + (np.math.trunc(quotient_interval) * interval_radio_items)\n\n events_filtered.at[i, 'year_cluster'] = j\n\n return events_filtered\n\n\ndef build_plots(event_property, filtered_df, interval_radio_items):\n avg_area = get_avg(filtered_df, event_property)\n max_area = get_max(filtered_df, event_property)\n\n if max_area[event_property].max() - avg_area[event_property].min() > 20:\n scale = \"log\"\n else:\n scale = \"linear\"\n\n\n plot1 = Plot(avg_area.event_year, avg_area[event_property], 'Average')\n plot2 = Plot(max_area.event_year, max_area[event_property], 'Max')\n\n plot3 = None\n if interval_radio_items > 1:\n cluster_area = get_cluster(filtered_df, event_property, interval_radio_items)\n plot3 = Plot(cluster_area.year_cluster, cluster_area.avg_per_cluster, \"avg every {} years\".format(interval_radio_items))\n\n return plot1, plot2, plot3, scale\n\n\ndef get_max(filtered_df, event_property):\n max_ = filtered_df.groupby(['event_year'])[event_property].max()\n max_ = pd.DataFrame(max_)\n max_['event_year'] = max_.index\n max_.reset_index(drop=True, inplace=True)\n return max_\n\n\ndef get_avg(filtered_df, event_property):\n avg = filtered_df.groupby(['event_year'])[event_property].mean()\n avg = pd.DataFrame(avg)\n avg['event_year'] = avg.index\n avg.reset_index(drop=True, inplace=True)\n return avg\n\n\ndef get_cluster(filtered_df, event_property, interval_radio_items):\n events_filtered = add_year_cluster(interval_radio_items, filtered_df)\n events_per_cluster = events_filtered.groupby('year_cluster')['event_id'].count()\n events_per_cluster = pd.DataFrame(events_per_cluster)\n\n avg_per_cluster = events_filtered.groupby('year_cluster')[event_property].sum()\n avg_per_cluster = pd.DataFrame(avg_per_cluster)\n avg_per_cluster['avg_per_cluster'] = avg_per_cluster[event_property] / events_per_cluster.event_id\n avg_per_cluster.reset_index(inplace=True)\n return avg_per_cluster\n\n\ndef plot_property_per_time_scale(plot1, plot2, plot3, x_title, y_title, table_title, scale):\n #color_set = ['#72d499','#cbabff','#fcc168','#f08686','#88ccee','#b5e66c','#d41313']\n color_set = ['#e8a531','#004080','#7f3c99','#b0341e','#88ccee','#097061','#0f5dab']\n if plot1.stacked is None:\n figure = make_subplots(specs=[[{\"secondary_y\": True}]])\n figure.add_bar(x=plot1.x, y=plot1.y, name=plot1.name, marker_color=color_set[1])\n else:\n figure = px.bar(x=plot1.x, y=plot1.y, title=plot1.name, color=plot1.stacked, color_discrete_sequence=color_set)\n\n if plot2 is not None:\n figure.add_trace(\n go.Scatter(x=plot2.x, y=plot2.y, name=plot2.name, mode='lines', marker_color=color_set[0]))\n\n if plot3 is not None:\n figure.add_trace(go.Scatter(x=plot3.x, y=plot3.y, name=plot3.name, marker_color=color_set[2]))\n\n figure.update_xaxes(title_text=x_title)\n figure.update_yaxes(title_text=y_title)\n get_layout(figure, table_title, scale)\n return figure\n\n\ndef get_layout(figure, title, scale):\n figure.update_layout(\n #autosize=True,\n #automargin=True,\n #margin=dict(l=30, r=30, b=20, t=40),\n plot_bgcolor=\"#e4ebf2\",\n paper_bgcolor=\"#e4ebf2\",\n title_text=title,\n yaxis_type=scale,\n hovermode=\"x\",\n hoverdistance=100, # Distance to show hover label of data point\n spikedistance=1000,\n legend=dict(font=dict(size=12), orientation=\"h\",y=-0.25),\n\n # Distance to show spike\n xaxis=dict(\n showspikes=True, # Show spike line for X-axis\n spikethickness=2,\n spikedash=\"dot\",\n spikecolor=\"#999999\",\n spikemode=\"across\",\n ),\n )\n\n\n\ninit_data()\n\n\nclass Plot:\n def __init__(self, x, y, name, stacked=None):\n self.x = x\n self.y = y\n self.name = name\n self.stacked = stacked\n","sub_path":"dash_final/data_builder.py","file_name":"data_builder.py","file_ext":"py","file_size_in_byte":12272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"34"} +{"seq_id":"172850613","text":"DEFAULT_OUT = \"problema_carteiro_16.txt\"\nDEFAULT_SEED = None\n\nDEFAULT_N_START = 1\nDEFAULT_N_STOP = 1\nDEFAULT_N_STEP = 1\nDEFAULT_TRIALS = 3\n\nfrom subprocess import Popen, PIPE\nfrom time import sleep, time\nfrom multiprocessing import Process\nimport shlex\nimport json\n\n\nimport time\nimport sys\nimport os\nimport argparse\nimport logging\nimport subprocess\n\nfrom math import sqrt, log\nimport random, decimal\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.optimize as opt\nimport matplotlib.colors as colors\nimport matplotlib.cm as cmx\n\nimport timeit\n\nprint(\"Problema do Carteiro\")\n\n\nf = open(\"bairros 16\", \"r\")\nl_bairros = f.read().split()\nf.close()\nbairros = {} # dicionario com a posicao de todos os bairros {'bairro_numero':[posX, posY]}\n\nfor x in range(0, len(l_bairros), 3): # preenche o dicionario com os bairros e posicoes\n bairros[l_bairros[x]] = [float(l_bairros[x + 1]), float(l_bairros[x + 2])]\n\n\ndef distancia(xyA, xyB): # calcula a distancia reta entre dois pontos\n xA, xB, yA, yB = (xyA[0]), (xyB[0]), (xyA[1]), (xyB[1])\n d = sqrt((xB - xA) ** 2 + (yB - yA) ** 2)\n return round(d, 12)\n\n\nbairros_custo = {} # dicionario com o custo de cada travessia {('bairroA_numero','bairroB_numero'): distancia}\nfor k in range(1, 17):\n for c in range(1, 17):\n bairros_custo[(str(k), str(c))] = distancia(bairros[str(k)], bairros[str(c)])\n\n\ndef custo_total(lista_bairros): # retorna o custo total de uma solucao\n custo = 0\n for bairro in range(len(lista_bairros)):\n if bairro == len(lista_bairros) - 1: # se chegou no ultimo bairro soma o custo com a origem\n custo += bairros_custo[(str(lista_bairros[bairro]), str(lista_bairros[0]))]\n else:\n custo += bairros_custo[(str(lista_bairros[bairro]), str(lista_bairros[bairro + 1]))]\n return custo\n\n\ndef vizinho(solucao):\n solucao_anterior = solucao.copy()\n while True:\n posA = random.randint(0, 15)\n posB = random.randint(0, 15)\n a = solucao[posA]\n b = solucao[posB]\n solucao[posA] = b\n solucao[posB] = a\n\n posC = random.randint(0, 15)\n posD = random.randint(0, 15)\n c = solucao[posC]\n d = solucao[posD]\n solucao[posC] = d\n solucao[posD] = c\n if solucao != solucao_anterior:\n break\n return solucao\n\n\ndef probabilidade(custo_antigo, custo_novo, temperatura): # calcula a probabilidade de aceitacao da nova solucao\n decimal.getcontext().prec = 100\n diferenca_custo = custo_antigo - custo_novo\n custo_temp = diferenca_custo / temperatura\n p = decimal.Decimal(0)\n e = decimal.Decimal(2.71828)\n n_custo_temp = decimal.Decimal(-custo_temp)\n try:\n p = e ** n_custo_temp\n resultado = repr(p)\n except decimal.Overflow:\n # print(\"Error decimal Overflow\")\n return 0.0\n\n try: # caso o numero tenha casas decimais\n fim = resultado.find(\"')\")\n resultado = round(float(resultado[9:fim - 1]), 3)\n\n except: # numero n tem casas decimais\n resultado = round(float(resultado[9:-2]))\n return resultado\n\n\ndef annealing(solucao, tempo, alfa):\n print(\"Calculando rotas.....\\n\")\n custo_antigo = custo_total(solucao)\n # tempo = entrada_tempo()\n tempo_minimo = 0.0001\n # alfa = entrada_alfa()\n melhor_solucao, melhor_custo = solucao[::], custo_antigo\n while tempo > tempo_minimo:\n i = 1\n while i <= 500:\n nova_solucao = vizinho(solucao)\n novo_custo = custo_total(nova_solucao)\n p = probabilidade(custo_antigo, novo_custo, tempo)\n if novo_custo < melhor_custo:\n melhor_solucao = nova_solucao[::]\n melhor_custo = novo_custo\n if p > round(random.random(), 3):\n solucao = nova_solucao[::]\n custo_antigo = novo_custo\n i += 1\n\n tempo = tempo * alfa\n return melhor_solucao, melhor_custo\n\n\ndef gerar_solucao(): # gera uma solucao aleatoria\n solucao_aleatoria = [x for x in range(1, 17)]\n random.shuffle(solucao_aleatoria)\n return solucao_aleatoria\n\n\ndef problema_carteiro():\n solucao_inicial = gerar_solucao()\n\n solucao_final, custo = annealing(solucao_inicial, 1.0, 0.5)\n print(solucao_final, \"Solução Final \\n\", custo, \"Custo Final\")\n return custo\n\n\ndef main():\n # Definição de argumentos\n parser = argparse.ArgumentParser(description='Problema Carteiro N=16')\n help_msg = \"arquivo de saída. Padrão:{}\".format(DEFAULT_OUT)\n parser.add_argument(\"--out\", \"-o\", help=help_msg, default=DEFAULT_OUT, type=str)\n\n help_msg = \"semente aleatória. Padrão:{}\".format(DEFAULT_SEED)\n parser.add_argument(\"--seed\", \"-s\", help=help_msg, default=DEFAULT_SEED, type=int)\n\n help_msg = \"n máximo. Padrão:{}\".format(DEFAULT_N_STOP)\n parser.add_argument(\"--nstop\", \"-n\", help=help_msg, default=DEFAULT_N_STOP, type=int)\n\n help_msg = \"n mínimo. Padrão:{}\".format(DEFAULT_N_START)\n parser.add_argument(\"--nstart\", \"-a\", help=help_msg, default=DEFAULT_N_START, type=int)\n\n help_msg = \"n passo. Padrão:{}\".format(DEFAULT_N_STEP)\n parser.add_argument(\"--nstep\", \"-e\", help=help_msg, default=DEFAULT_N_STEP, type=int)\n\n help_msg = \"tentativas. Padrão:{}\".format(DEFAULT_N_STEP)\n parser.add_argument(\"--trials\", \"-t\", help=help_msg, default=DEFAULT_TRIALS, type=int)\n\n # Lê argumentos from da linha de comando\n args = parser.parse_args()\n\n trials = args.trials\n f = open(args.out, \"w\")\n f.write(\"#Problema Carteiro N=82\\n\")\n f.write(\"#n average turn-around time and average slowndown (for {} trials)\\n\".format(trials))\n m = 100\n np.random.seed(args.seed)\n for n in range(args.nstart, args.nstop + 1, args.nstep): # range(1, 100):\n resultados = [0 for i in range(trials)]\n tempos = [0 for i in range(trials)]\n for trial in range(trials):\n print(\"\\n-------\")\n print(\"n: {} trial: {}\".format(n, trial + 1))\n tempo_inicio = timeit.default_timer()\n resultados[trial] = problema_carteiro()\n tempo_fim = timeit.default_timer()\n tempos[trial] = tempo_fim - tempo_inicio\n print(\"Saída: {}\".format(resultados[trial]))\n print('Tempo: {} s'.format(tempos[trial]))\n print(\"\")\n\n tempos_avg = np.average(tempos) # calcula média\n tempos_std = np.std(a=tempos, ddof=False) # ddof=calcula desvio padrao de uma amostra?\n\n resultados_avg = np.average(resultados) # calcula média\n resultados_std = np.std(a=resultados, ddof=False) # ddof=calcula desvio padrao de uma amostra?\n\n f.write(\"{} {} {} {} {} \\n\".format(n, tempos_avg, tempos_std, resultados_avg, resultados_std))\n f.close()\n\n\nif __name__ == '__main__':\n sys.exit(main())\n","sub_path":"scripts/ProblemaCarteiro16.py","file_name":"ProblemaCarteiro16.py","file_ext":"py","file_size_in_byte":6853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"34"} +{"seq_id":"377215767","text":"import socketio\nfrom aiohttp import web\nfrom collections import defaultdict\nimport itertools\n\nclass PredictionServer:\n\n # finger_name_to_finger_number = {\n # \"left_pinky\": 0,\n # \"left_ring\": 1,\n # \"left_middle\": 2,\n # \"left_index\": 3,\n # \"thumb\": 4,\n # \"right_index\": 5,\n # \"right_middle\": 6,\n # \"right_ring\": 7,\n # \"right_pinky\": 8,\n # \"left_squeeze\": 9,\n # \"right_squeeze\": 10,\n # \"left_and_right_squeeze\": 11\n # }\n \n # maps from finger number to possible finger letters\n # finger_number_to_letters = {\n # \"0\": [\"q\", \"a\", \"z\"],\n # \"1\": [\"w\", \"s\", \"x\"],\n # \"2\": [\"e\", \"d\", \"c\"],\n # \"3\": [\"r\", \"f\", \"v\", \"t\", \"g\", \"b\"],\n # \"4\": [\" \"],\n # \"5\": [\"y\", \"h\", \"n\", \"u\", \"j\", \"m\"],\n # \"6\": [\"i\", \"k\", \",\"],\n # \"7\": [\"o\", \"l\", \".\"],\n # \"8\": [\"p\", \";\", \":\", \"'\", '\"', \"/\"],\n # \"9\": [\"0\"],\n # \"10\": [\"\\\\x7f\"],\n # \"11\": [\"\\\\x03\"]\n # }\n \n finger_name_to_finger_number = {\n \"left_pinky\": 9,\n \"left_ring\": 8,\n \"left_middle\": 7,\n \"left_index\": 6,\n \"thumb\": 1,\n \"right_index\": 2,\n \"right_middle\": 3,\n \"right_ring\": 4,\n \"right_pinky\": 5,\n \"left_squeeze\": 10,\n \"right_squeeze\": 11,\n \"left_and_right_squeeze\": 12\n }\n \n # maps from finger number to possible finger letters\n finger_number_to_letters = {\n \"9\": [\"q\", \"a\", \"z\"],\n \"8\": [\"w\", \"s\", \"x\"],\n \"7\": [\"e\", \"d\", \"c\"],\n \"6\": [\"r\", \"f\", \"v\", \"t\", \"g\", \"b\"],\n \"1\": [\" \"],\n \"2\": [\"y\", \"h\", \"n\", \"u\", \"j\", \"m\"],\n \"3\": [\"i\", \"k\", \",\"],\n \"4\": [\"o\", \"l\", \".\"],\n \"5\": [\"p\", \";\", \":\", \"'\", '\"', \"/\"],\n \"10\": [\"0\"],\n \"11\": [\"\\\\x7f\"],\n \"12\": [\"\\\\x03\"]\n }\n\n # maps from letter to finger number\n letters_to_finger_numbers = {}\n for number, letters in finger_number_to_letters.items():\n for letter in letters:\n letters_to_finger_numbers[letter] = number\n\n # create a translator for translating from english to fingers\n english_letters = \"qazwsxedcrfvtgbyhnujmikolp\"\n # finger_letters = \"00011122233333355555566778\"\n finger_letters = \"99988877766666622222233445\"\n english_to_finger_table = \"\".maketrans(english_letters, finger_letters)\n\n # translate from english to finger word\n @staticmethod\n def english_to_finger_word(word):\n return word.lower().translate(PredictionServer.english_to_finger_table)\n\n # build dictionary to translate from fingers to english\n # keys are finger words\n # values are lists of potential english words\n # parameter is a list of common english words\n @staticmethod\n def get_finger_number_to_word_map(word_list):\n word_groupings = defaultdict(list)\n for word in word_list:\n word_groupings[PredictionServer.english_to_finger_word(word)].append(word)\n return word_groupings\n\n # Data analysis\n\n # print data on number of conflict counts\n # for words of varying lengths\n @staticmethod\n def get_conflict_counts(word_list):\n word_groupings = defaultdict(list)\n for word in word_list:\n word_groupings[PredictionServer.english_to_finger_word(word)].append(word)\n\n conflict_count = defaultdict(int)\n for group, words in word_groupings.items():\n group_size = len(words)\n conflict_count[group_size] += 1\n # conflict_count[group_size] += 1\n\n # for key, val in conflict_count.items():\n # conflict_count[key] = val * key\n return conflict_count\n\n # print the top finger words\n @staticmethod\n def calculate_average_word_distance_by_length(word_list, plot_results=False):\n # key: length of finger word\n # value: list of finger words of length key\n finger_word_length_dictionary = defaultdict(list)\n for word in word_list:\n finger_word = PredictionServer.english_to_finger_word(word)\n finger_word_length_dictionary[len(finger_word)].append(finger_word)\n # word_groupings.setdefault(len(finger_word), []).append(finger_word)\n\n # Function to return the minimum number of\n # operations to convert string A to B\n def minOperations(word1, word2):\n count = 0\n for index, letter in enumerate(word1):\n if letter != word2[index]:\n count += 1\n return count\n\n # key: length of finger word\n # value: average min distance of words\n distance_dict = {}\n for length, words in sorted(finger_word_length_dictionary.items()):\n # print(length)\n min_dist_dict = defaultdict(lambda: 100)\n if len(words) > 1:\n for word1, word2 in itertools.combinations((set(words)), 2):\n min_dist_dict[word1] = min(min_dist_dict[word1], minOperations(word1, word2))\n distance_dict[length] = {\n \"average_min_distance\": sum(min_dist_dict.values()) / len(min_dist_dict),\n \"count\": len(min_dist_dict)\n }\n # if plot_results:\n # plt.hist(min_dist_dict.values(), bins=range(length))\n # plt.show()\n\n return distance_dict\n\n def __init__(self, queue, word_groupings, server_mode=False, finger_mode=False):\n self.queue = queue\n self.word_groupings = word_groupings\n self.server_mode = server_mode\n self.finger_mode = finger_mode\n\n self.sio = socketio.AsyncServer(async_mode='aiohttp', cors_allowed_origins=\"*\", sync_handlers=True)\n self.app = web.Application()\n self.sio.attach(self.app)\n\n # @staticmethod\n # @sio.event\n # def connect(sid, environ):\n # print(\"Client connected\", sid)\n\n # @staticmethod\n # @sio.event\n # def disconnect(sid):\n # print(\"Disconnect\")\n\n # gets finger number from prediction algorithm\n\n async def get_finger_number(self):\n # print(\"Pulling from queue\")\n while self.queue.empty():\n # print(\"Waiting on empty queue\")\n await self.sio.sleep(0.01)\n\n queueItem = self.queue.get()\n\n if self.finger_mode:\n # get character prediction\n if self.server_mode:\n for key, value in queueItem.items():\n # print(key, value)\n await self.sio.emit(key, {key: value})\n \n finger_number = str(queueItem[\"Finger\"])\n\n else:\n # get character from keyboard\n try:\n finger_number = PredictionServer.letters_to_finger_numbers[queueItem]\n except Exception as e:\n print(f\"Invalid key: {queueItem}\")\n return await self.get_finger_number()\n\n print(finger_number)\n return finger_number\n\n # send most likely words\n async def send_most_likely_words(self, words):\n print(words)\n await self.sio.emit('options', {\"words\": words})\n\n # trigger word selection mode\n async def send_word_selection_mode(self):\n await self.sio.emit('selection', None)\n\n # trigger word capture\n async def send_word_capture(self, word):\n await self.sio.emit('word', {\"word\": word})\n\n # trigger delete word\n async def send_delete_word(self):\n print(\"deleting a word\")\n await self.sio.emit('delete', None)\n\n # leave typing mode\n def send_leave_typing_mode(self):\n pass\n\n # send error code\n def send_error_code(self):\n pass\n\n # Interactive mode\n # server_mode indicates that we should send messages to the frontend\n async def interactive_mode(self):\n # finger_word stores the word that the user is building\n finger_word = \"\"\n\n # sentence stores the words the user has built\n sentence = \"\"\n\n async def handle_most_likely_words(potential_words):\n if (len(potential_words) != 0):\n tmp_res = \"\"\n for index, potential_word in enumerate(potential_words):\n tmp_res += f\"{index}: {potential_word}, \"\n print(f\"Possible words: {tmp_res}\")\n else:\n print(\"Could not translate\")\n\n if self.server_mode:\n await self.send_most_likely_words(potential_words)\n\n async def handle_word_selection_mode(potential_words):\n nonlocal finger_word, sentence\n\n potential_words_display = \"\"\n for index, potential_word in enumerate(potential_words):\n potential_words_display += f\"{index}: {potential_word}, \"\n\n print(\"Word Selection Mode. Please select a word:\")\n print(potential_words_display)\n\n if self.server_mode:\n await self.send_word_selection_mode()\n\n finger_number = await self.get_finger_number()\n\n number = int(finger_number)\n\n try:\n selected_word = potential_words[number]\n except Exception as e:\n print(f\"Key out of selection range: {number}\")\n return\n\n print(f\"Selected word: {selected_word}\")\n await handle_word_capture(selected_word)\n\n async def handle_word_capture(english_word):\n nonlocal finger_word, sentence\n finger_word = \"\"\n sentence += english_word + \" \"\n\n print(f\"Your Sentence: {sentence}\")\n\n if self.server_mode:\n await self.send_word_capture(english_word)\n\n async def handle_delete_word():\n nonlocal finger_word, sentence\n sentence = sentence.rsplit(' ', 1)[0]\n\n if self.server_mode:\n await self.send_delete_word()\n\n def handle_leave_typing_mode():\n if self.server_mode:\n self.send_leave_typing_mode()\n else:\n exit()\n\n def handle_error_code(code):\n # add options for continuing or resetting\n if code == \"could_not_enter_word_selection_mode\":\n print(\"Could not enter word selection mode. No potential words\")\n\n if self.server_mode:\n self.send_error_code(code)\n \n was_baseline = False\n started = False\n \n # continuously read characters\n while True:\n \n \n finger_number = await self.get_finger_number()\n \n if self.finger_mode:\n if finger_number == \"0\":\n was_baseline = True\n elif not was_baseline:\n print(\"Skipping\")\n continue\n else:\n was_baseline = False\n \n await self.sio.emit('finger', {'number': finger_number})\n \n if not started:\n if finger_number == \"1\":\n started = True\n continue\n \n # type C-c to exit (left and right squeeze)\n # if finger_number == \"12\":\n if finger_number == \"10\": # right squeeze, reset finger word\n print(\"Word reset\")\n finger_word = \"\"\n # handle_leave_typing_mode()\n\n # type space to select the first word (thumb)\n elif finger_number == \"1\":\n try:\n selected_word = self.word_groupings[finger_word][0]\n await handle_word_capture(selected_word)\n except Exception as e:\n print(f\"No word to select\")\n # finger_word = \"\"\n\n # type backspace to go back a character (left squeeze)\n elif finger_number == \"11\":\n print(\"Deleting\")\n if (len(finger_word) == 0):\n # remove last word from the sentence\n await handle_delete_word()\n else:\n # remove last char from the word\n finger_word = finger_word[:-1]\n await handle_most_likely_words(self.word_groupings[finger_word])\n\n # type 0 to enter word selection mode (left squeeze)\n # elif finger_number == \"10\":\n elif finger_number == \"12\": # (left and right squeeze)\n if finger_word in self.word_groupings:\n await handle_word_selection_mode(self.word_groupings[finger_word])\n else:\n handle_error_code(\"could_not_enter_word_selection_mode\")\n\n # other characters are interpretted as typing\n elif finger_number != \"0\":\n finger_word += finger_number\n print(finger_word)\n await handle_most_likely_words(self.word_groupings[finger_word])\n\n # print(f\"Your Sentence: {sentence}\")\n print(\"\")\n\n def startServer(self):\n self.sio.start_background_task(self.interactive_mode)\n web.run_app(self.app, host='0.0.0.0', port='4002')\n","sub_path":"src/dashboard/backend/real_time/prediction_server.py","file_name":"prediction_server.py","file_ext":"py","file_size_in_byte":13187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"34"} +{"seq_id":"229148009","text":"# -*- coding: utf-8 -*-\n\nfrom openerp import api, models, fields\nfrom static_data import facebook_graph_api_url\nimport requests\n\nimport logging\n\nlogger = logging.getLogger(__name__)\n\n\nclass CrmFacebookPage(models.Model):\n _name = 'crm.facebook.page'\n _inherit = ['mail.thread']\n\n name = fields.Char(required=True, string=\"Facebook Page Name\")\n fb_page_id = fields.Char(required=True, string=\"Facebook Page ID\")\n fb_page_access_token = fields.Char(required=True, string='Page Access Token')\n crm_form_ids = fields.One2many('crm.facebook.form', 'crm_page_id', string='Lead Forms')\n\n # SQL CONSTRAINTS\n _sql_constraints = [\n ('fb_fb_page_id', 'unique(fb_page_id)', 'Facebook page id must be unique')\n ]\n\n @api.multi\n def import_facebook_forms(self):\n crm_facebook_form_obj = self.env['crm.facebook.form']\n\n for r in self:\n facebook_forms = requests.get(facebook_graph_api_url + self.fb_page_id + \"/leadgen_forms\",\n params={'access_token': self.fb_page_access_token}).json()\n for fb_form in facebook_forms['data']:\n # HINT: Search for inactive forms too, so archived forms are not created over and over again\n crm_form_rec = crm_facebook_form_obj.search([('fb_form_id', '=', fb_form['id']),\n '|', ('active', '=', True), ('active', '=', False)])\n if not crm_form_rec:\n crm_facebook_form_obj.create({\n 'name': fb_form.get('name') or fb_form['id'],\n 'fb_form_id': fb_form['id'],\n 'fb_form_locale': fb_form.get('locale'),\n 'fb_form_status': fb_form.get('status'),\n 'crm_page_id': r.id,\n }).import_facebook_lead_fields()\n else:\n if fb_form['status'].lower() != 'active':\n crm_form_rec.write({'active': False})\n\n @api.multi\n def write(self, vals):\n res = super(CrmFacebookPage, self).write(vals)\n\n # Recompute the state of all existing forms if the page access token field gets changed!\n if res and 'fb_page_access_token' in vals:\n for r in self:\n if r.crm_form_ids:\n r.crm_form_ids.compute_state()\n\n return res\n","sub_path":"addons-own/crm_facebook_leads/models/crm_facebook_page.py","file_name":"crm_facebook_page.py","file_ext":"py","file_size_in_byte":2413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"43385732","text":"import math\nimport sys\n\nfrom PyQt5 import QtGui\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtWidgets import *\n\n\nclass DrawPoints(QWidget):\n\n def __init__(self):\n super(DrawPoints, self).__init__()\n self.init()\n\n def init(self):\n self.setGeometry(300, 300, 300, 300)\n self.setWindowTitle('draw sin line')\n\n def paintEvent(self, a0: QtGui.QPaintEvent) -> None:\n painter = QPainter()\n painter.begin(self)\n\n painter.setPen(Qt.red)\n\n size = self.size()\n\n for i in range(1000):\n x = 100 * (-1 + 2.0 * i / 1000) + size.width() / 2\n y = -50 * math.cos((x - size.width() / 2.0) * math.pi / 50) + size.height() / 2.0\n painter.drawPoint(x, y)\n\n painter.end()\n\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n main = DrawPoints()\n main.show()\n sys.exit(app.exec_())\n","sub_path":"src/DrawPoints.py","file_name":"DrawPoints.py","file_ext":"py","file_size_in_byte":909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"243481612","text":"# To run the script type python classifier.py or python3 classifier.py (this depends on your OS)\n# The script expects the dataset to have been extracted in a folder called data in the same directory\n# as classifier.py\n\n# The script requires the latest versions of pandas and sklearn to run\nimport os\nimport joblib\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom scipy import stats\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.impute import SimpleImputer\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.compose import ColumnTransformer\nfrom sklearn.preprocessing import OrdinalEncoder, OneHotEncoder, StandardScaler\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.metrics import precision_score, accuracy_score\nfrom sklearn.metrics import confusion_matrix, plot_confusion_matrix\nfrom sklearn.svm import LinearSVC\n\n# Init filepaths for the dataset CSV files\nASSESSMENTS_FPATH = os.path.join(os.getcwd(), 'data', 'assessments.csv')\nCOURSES_FPATH = os.path.join(os.getcwd(), 'data', 'courses.csv')\nSTUDENT_ASSESS_FPATH = os.path.join(\n os.getcwd(), 'data', 'studentAssessment.csv')\nSTUDENT_INFO_FPATH = os.path.join(os.getcwd(), 'data', 'studentInfo.csv')\nSTUDENT_REG_FPATH = os.path.join(\n os.getcwd(), 'data', 'studentRegistration.csv')\nSTUDENT_VLE_FPATH = os.path.join(os.getcwd(), 'data', 'studentVle.csv')\nVLE_FPATH = os.path.join(os.getcwd(), 'data', 'vle.csv')\n\n\n# function ordinally encodes the final results\n# ordered ascending from withdrawn 0 to Distinction 3\ndef ordinal_final_result(student_info):\n mod_res = student_info.sort_values(by=['id_student'])\n mod_res = mod_res[['final_result']]\n mod_res.loc[mod_res['final_result'] == 'Withdrawn', 'final_result'] = 0\n mod_res.loc[mod_res['final_result'] == 'Fail', 'final_result'] = 1\n mod_res.loc[mod_res['final_result'] == 'Pass', 'final_result'] = 2\n mod_res.loc[mod_res['final_result'] == 'Distinction', 'final_result'] = 3\n return mod_res\n\n\n# function calculates the spearman rank correlation coefficient\n# between final result and students total assessment mark\ndef assess_mark_corr(student_info):\n # open dataset files and load the data\n mod_res = ordinal_final_result(student_info)\n stud_assess = pd.read_csv(STUDENT_ASSESS_FPATH)\n assess = pd.read_csv(ASSESSMENTS_FPATH)\n # join assessment and studen assessment tables on id_assessment\n stud_assess = pd.merge(stud_assess, assess, on='id_assessment')\n # isolate relevant student info columns for the correlation calc\n features = student_info[['id_student', 'code_module', 'code_presentation']]\n # join tables on student id and module codes\n stud_assess_merged = pd.merge(features, stud_assess, on=[\n 'id_student', 'code_module', 'code_presentation'], how='left')\n # assume any missing entries are 0 scores\n stud_assess_merged = stud_assess_merged.fillna(0)\n # total up student assessment marks for each module and student\n stud_assess_merged = stud_assess_merged.groupby(\n ['id_student', 'code_module', 'code_presentation'])['score'].sum()\n stud_assess_merged.fillna(0, inplace=True)\n # calculate spearmans rank correlation coefficient\n res = stats.spearmanr(stud_assess_merged, mod_res)\n print('Correlation between total assessment mark for module and module' +\n ' result')\n print('Coefficient=', res[0], '\\np_value=', res[1])\n print('################################################################' +\n '########')\n\n\n# Calculates spearmans rank correlation coefficient\n# between studen reg data and final result\ndef reg_data_corr(student_info):\n mod_res = ordinal_final_result(student_info)\n # load relevant CSV files\n stud_reg = pd.read_csv(STUDENT_REG_FPATH)\n # join tables on student id and module codes\n features = pd.merge(student_info, stud_reg, on=[\n 'id_student', 'code_module', 'code_presentation'])\n features = features.sort_values(by=['id_student'])\n features.fillna(0, inplace=True)\n # calculate correlation coefficient\n res = stats.spearmanr(features[['date_registration']], mod_res)\n print('Correlation between registration date and module result')\n print('Coefficient=', res[0], '\\np_value=', res[1])\n print('################################################################' +\n '########')\n\n\n# calulates spearmans rank correlation correlation\n# between unregistration data and final result\ndef unreg_data_corr(student_info):\n mod_res = ordinal_final_result(student_info)\n # load relevant CSV files\n stud_reg = pd.read_csv(STUDENT_REG_FPATH)\n # join tables on student id and module codes\n features = pd.merge(student_info, stud_reg, on=[\n 'id_student', 'code_module', 'code_presentation'])\n features = features.sort_values(by=['id_student'])\n features.fillna(0, inplace=True)\n # calculate correlation coefficient\n res = stats.spearmanr(features[['date_unregistration']], mod_res)\n print('Correlation between de-registration date and module result')\n print('Coefficient=', res[0], '\\np_value=', res[1])\n print('################################################################' +\n '########')\n\n\n# calculates spearmans rank correlation coefficient\n# between prev module attempts and final result\ndef prev_attempts_corr(student_info):\n mod_res = ordinal_final_result(student_info)\n sort_data = student_info.sort_values(by=['id_student'])\n # calculate correlation coefficient\n res = stats.spearmanr(sort_data[['num_of_prev_attempts']], mod_res)\n print('Correlation between previous module attempts and module result')\n print('Coefficient=', res[0], '\\np_value=', res[1])\n print('################################################################' +\n '########')\n\n\n# calculates spearmans rank correlation coefficient\n# between module credits and final result\ndef stud_credits_corr(student_info):\n mod_res = ordinal_final_result(student_info)\n sort_data = student_info.sort_values(by=['id_student'])\n # calculate correlation coefficient\n res = stats.spearmanr(sort_data[['studied_credits']], mod_res)\n print('Correlation between studied credits for module and module result')\n print('Coefficient=', res[0], '\\np_value=', res[1])\n print('################################################################' +\n '########')\n\n\n# calulates spearmans rank correlation coefficient\n# between course length and final_result\ndef course_length_corr(student_info):\n mod_res = ordinal_final_result(student_info)\n # load relevant CSV files\n courses = pd.read_csv(COURSES_FPATH)\n # join tables on module codes\n features = pd.merge(student_info, courses, on=[\n 'code_presentation', 'code_module'])\n features = features.sort_values(by=['id_student'])\n # calculate correlation coefficient\n res = stats.spearmanr(\n features[['module_presentation_length']], mod_res)\n print('Correlation between course length and module result')\n print('Coefficient=', res[0], '\\np_value=', res[1])\n print('################################################################' +\n '########')\n\n\n# performs a chi squared association test beween\n# student gender and final result\ndef gender_association(student_info):\n freq = student_info[['gender', 'final_result']]\n # create contingency table for test\n freq = freq.groupby(['gender', 'final_result']).size().unstack()\n # perform test\n res = stats.chi2_contingency(freq)\n print('Association between gender and module result')\n print('Test stat=', res[0], '\\np_value=', res[1])\n print('################################################################' +\n '########')\n\n\n# performs chi squared association test between\n# student imd band and final result\ndef imd_association(student_info):\n freq = student_info[['imd_band', 'final_result']]\n # create contingency table\n freq = freq.groupby(['imd_band', 'final_result']).size().unstack()\n # perform test\n res = stats.chi2_contingency(freq)\n print('Association between imd and module result')\n print('Test stat=', res[0], '\\np_value=', res[1])\n print('################################################################' +\n '########')\n\n\n# performs chi squared test between\n# students highest level of education and final result\ndef higher_ed_association(student_info):\n freq = student_info[['highest_education', 'final_result']]\n # creat contingency table\n freq = freq.groupby(['highest_education', 'final_result']).size().unstack()\n # perform test\n res = stats.chi2_contingency(freq)\n print('Association between highest education level and module result')\n print('Test stat=', res[0], '\\np_value=', res[1])\n print('################################################################' +\n '########')\n\n\n# performs chi squared test between\n# students home region and final result\ndef region_association(student_info):\n freq = student_info[['region', 'final_result']]\n # creat contingency table\n freq = student_info.groupby(['region', 'final_result']).size().unstack()\n # perform test \n res = stats.chi2_contingency(freq)\n print('Association between student region and module result')\n print('Test stat=', res[0], '\\np_value=', res[1])\n print('################################################################' +\n '########')\n\n\n# performs chi squared test between\n# student disability classification and final result\ndef disability_association(student_info):\n freq = student_info[['disability', 'final_result']]\n # create contingency table\n freq = student_info.groupby(\n ['disability', 'final_result']).size().unstack()\n # perform test\n res = stats.chi2_contingency(freq)\n print('Association between disability and module result')\n print('Test stat=', res[0], '\\np_value=', res[1])\n print('################################################################' +\n '########')\n\n\n# perform chi squared test between\n# students age band and final_result\ndef age_band_association(student_info):\n freq = student_info[['age_band', 'final_result']]\n # create contingency table\n freq = student_info.groupby(\n ['age_band', 'final_result']).size().unstack()\n # perform test\n res = stats.chi2_contingency(freq)\n print('Association between age and module result')\n print('Test stat=', res[0], '\\np_value=', res[1])\n print('################################################################' +\n '########')\n\n\n# joines tables with chosen features for model training\ndef join_tables(student_info):\n # open relevant CSV files\n stud_reg = pd.read_csv(STUDENT_REG_FPATH)\n courses = pd.read_csv(COURSES_FPATH)\n # join student reg table and course table\n merged = pd.merge(student_info, courses, on=[\n 'code_module', 'code_presentation'])\n # join result with student info table\n merged = pd.merge(merged, stud_reg, on=[\n 'id_student', 'code_presentation', 'code_module'])\n return merged\n\n\n# split data set into features table and labels table\ndef transform_for_model(data):\n features = data.drop('final_result', axis=1)\n labels = list(data['final_result'])\n # return tuple\n return (features, labels)\n\n\n# creates a data pipe to transform feature table into acceptable input\n# for the models\ndef create_data_pipe(features):\n # isolate categorical features\n cat_features = features[['gender', 'highest_education',\n 'age_band', 'region', 'disability']]\n # isolate numerical features\n num_features = features[['num_of_prev_attempts', 'studied_credits',\n 'module_presentation_length',\n 'date_registration']]\n # isolate 2 features that need some special processing\n imd_features = features[['imd_band']]\n unreg_feature = features[['date_unregistration']]\n # numerical features have missin values replaced with median\n # and are scaled about 0 to have a near normal distribution\n num_pipeline = Pipeline([\n ('imputer', SimpleImputer(strategy='median')),\n ('scaler', StandardScaler())\n ])\n # unreg date has unknowns replaced by a constant value instead\n # as this obviously signifies withdrawal. Also scaled\n unreg_pipeline = Pipeline([\n ('imputer', SimpleImputer(strategy='constant', fill_value=999)),\n ('scaler', StandardScaler())\n ])\n # categorical values are replaced by most frequent and one hot encoded\n cat_pipeline = Pipeline([\n ('imputer', SimpleImputer(strategy='most_frequent')),\n ('enc', OneHotEncoder())\n ])\n # imd is same as above but ordinally encoded because the categories\n # are clearly ordered\n imd_pipe = Pipeline([\n ('imputer', SimpleImputer(strategy='most_frequent')),\n ('enc', OrdinalEncoder())\n ])\n # Merge transformed features back into one table\n comp_pipe = ColumnTransformer([\n ('num', num_pipeline, list(num_features)),\n ('reg', unreg_pipeline, list(unreg_feature)),\n ('cat', cat_pipeline, list(cat_features)),\n ('imd', imd_pipe, list(imd_features))\n ])\n return comp_pipe\n\n\ndef process_data(train_set):\n # data analysis\n assess_mark_corr(train_set)\n prev_attempts_corr(train_set)\n stud_credits_corr(train_set)\n course_length_corr(train_set)\n reg_data_corr(train_set)\n unreg_data_corr(train_set)\n gender_association(train_set)\n imd_association(train_set)\n higher_ed_association(train_set)\n region_association(train_set)\n disability_association(train_set)\n age_band_association(train_set)\n\n\n# train the random forrest classifier on a training set\ndef train_forest(train_set):\n print('Training random forest')\n # get features and labels from training set\n joined = join_tables(train_set)\n features, labels = transform_for_model(joined)\n # get a data pipe\n data_pipe = create_data_pipe(features)\n for_class = RandomForestClassifier()\n # parameters for grid search hyperparamter tuning\n # only optimal values are here as I have already carried out the tuning\n params = [\n {'n_estimators': [54], 'max_features':[3]},\n ]\n # create grid search using micro averaged precision as scoring measure\n g_search = GridSearchCV(for_class, params, cv=10, scoring=[\n 'precision_micro', 'recall_micro'],\n return_train_score=True, refit='precision_micro')\n # add data pipe and grid search to pipe so model will transform data\n # before predicting\n forest_pipe = Pipeline([\n ('data_pipe', data_pipe),\n ('grid', g_search)\n ])\n # train the model on the training set\n forest_pipe.fit(features, labels)\n # print best hyperparamters\n print(forest_pipe['grid'].best_params_)\n results = forest_pipe['grid'].cv_results_\n res_tuple = zip(results['mean_test_precision_micro'],\n results['mean_test_recall_micro'], results['params'])\n # print micro averaged precision and recall scores for each set of hyperparamters\n for prec, rec, params in res_tuple:\n print('Prec=', prec, 'Recall=', rec, 'Params=', params)\n # save a local copy of the saved model\n save_model(forest_pipe, 'forest_pipe.pkl')\n return forest_pipe\n\n\n# train support vector classifier model on training set\ndef train_svc(train_set):\n print('Training SVC')\n joined = join_tables(train_set)\n # get features and labels from train set\n features, labels = transform_for_model(joined)\n # get a data pipe to transform the featues\n data_pipe = create_data_pipe(features)\n svc = LinearSVC()\n # hyperparamters for grid search, only optimal values here as\n # hyperparamter tuning has already been done\n params = [\n {'C': [0.11], 'dual':[False]},\n ]\n # grid search with micro averaged precision as scoring metric\n g_search = GridSearchCV(svc, params, cv=10, scoring=[\n 'precision_micro', 'recall_micro'],\n return_train_score=True, refit='precision_micro')\n # combine data pipe and grid search to create combined model pipe\n svc_pipe = Pipeline([\n ('data_pipe', data_pipe),\n ('grid', g_search)\n ])\n # train model\n svc_pipe.fit(features, labels)\n # print best hyperparamters\n print(svc_pipe['grid'].best_params_)\n results = svc_pipe['grid'].cv_results_\n res_tuple = zip(results['mean_test_precision_micro'],\n results['mean_test_recall_micro'], results['params'])\n # print results for all hyperparamter sets tested\n for prec, rec, params in res_tuple:\n print('Prec=', prec, 'Recall=', rec, 'Params=', params)\n # save local copy of the model\n save_model(svc_pipe, 'svc_pipe.pkl')\n return svc_pipe\n\n\n# test model on test set\ndef test_model(model, test_data, name):\n print('Testing',name,'on test set')\n joined = join_tables(test_data)\n # get features and labels from test set\n features, labels = transform_for_model(joined)\n # get list of predictions from model\n preds = model.predict(features)\n # score the resulting predictions using the micro averaged precision as the metric\n precision = precision_score(labels, preds, average='micro')\n # calculate accuracy metric (this is actually the same as micro averaged precision)\n accuracy = accuracy_score(labels, preds)\n # print text based confusion_matrix\n conf = confusion_matrix(labels, preds)\n # plot graphical confusion_matrix\n conf_plot = plot_confusion_matrix(model, features, labels, normalize=None,\n values_format='.9g', cmap=plt.cm.Blues)\n conf_plot.ax_.set_title(name)\n # print scores and confusion_matrix\n print('Precision=', precision, '\\nAccuracy=', accuracy)\n print('Confusion Matrix:')\n print(conf)\n\n\n# save a model to a local file\ndef save_model(model, name):\n joblib.dump(model, name)\n\n\n# load a model from a local file\ndef load_model(name):\n model = joblib.load(name)\n return model\n\n\ndef main():\n # load student_info\n student_info = pd.read_csv(STUDENT_INFO_FPATH)\n # split data into train and test set 80, 20 split using stratified sampling on highest_education\n train_set, test_set = train_test_split(\n student_info, test_size=0.2, random_state=42,\n stratify=student_info['highest_education'])\n # perform data analysis\n process_data(train_set)\n # train random forest \n rand_forest = train_forest(train_set)\n # test random forest\n test_model(rand_forest, test_set, 'Forest')\n # train support vector classifier\n svc = train_svc(train_set)\n # test support vector classifier\n test_model(svc, test_set, 'SVC')\n plt.show()\n\n\nmain()\n","sub_path":"classifier.py","file_name":"classifier.py","file_ext":"py","file_size_in_byte":18876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"287306095","text":"\nclass Solution:\n def smallerNumbersThanCurrent(self, nums):\n ans = []\n for i in nums :\n count = 0\n for j in nums :\n if j < i :\n count = count + 1\n ans.append(count)\n return ans\n\ndef execute():\n nums = [6,3,2,1]\n solution = Solution()\n print(solution.smallerNumbersThanCurrent(nums))\n\nexecute()\n","sub_path":"How_Many_Numbers_Are_Smaller_Than_the_Current_Number.py","file_name":"How_Many_Numbers_Are_Smaller_Than_the_Current_Number.py","file_ext":"py","file_size_in_byte":399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"386477992","text":"#!/usr/bin/env python3\n\n#this script classifies the ASM modules\n#Shihao Shen. 05/18/18\n\nimport re,os,sys\n\n#read the IsoExon format\nifile = open(sys.argv[1]);\nilines = ifile.readlines();\nasm_class = {};\nthis_pattern = {};\nasm_list=[];class_list=[];\nfor i in ilines:\n\telements=re.findall('[^\\t\\n]+',i);\n\tif 'ASM#' in elements[0]:\n\t\tasm_list+=[elements[0]];\n\t\tthis_pattern=list(this_pattern.keys());\n\t\tthis_pattern.sort();\n\t\twrite_pattern = '';\n\t\tfor k in this_pattern:\n\t\t\twrite_pattern = write_pattern + k + ':';\n\t\tif not(write_pattern in asm_class):\n\t\t\tasm_class[write_pattern]=1;\n\t\telse:\n\t\t\tasm_class[write_pattern]=asm_class[write_pattern]+1;\n\t\tclass_list+=[write_pattern];\n\t\tthis_pattern={};\n\t\tskip = 1;\n\t\texon_count=int(elements[1]);\n\telse:\n\t\tif skip == 1:\n\t\t\tskip = 0;\n\t\t\texon_newindex=0;exon_add='A';\n\t\t\texon_newindex_dic={};\n\t\t\tk = 0;left=0;\n\t\t\twhile k < exon_count-1:\n\t\t\t\tfirst=re.findall('[^,]+',elements[k])\n\t\t\t\tsecond=re.findall('[^,]+',elements[k+1])\n\t\t\t\tleft=max([left,int(first[1])]);\t\t\t\t\n\t\t\t\t#overlapped exons\n\t\t\t\tif left > int(second[0]):\n\t\t\t\t\tif not(k in exon_newindex_dic):\n\t\t\t\t\t\texon_newindex_dic[k]=str(exon_newindex)+exon_add;\n\t\t\t\t\texon_add+='A'\n\t\t\t\t\tif not(k+1 in exon_newindex_dic):\n\t\t\t\t\t\texon_newindex_dic[k+1]=str(exon_newindex)+exon_add;\n\t\t\t\t\tleft=max([left,first[1],second[1]]);\n\t\t\t\telse:\n\t\t\t\t\tleft=0;\n\t\t\t\t\tif not(k in exon_newindex_dic):\n\t\t\t\t\t\texon_newindex_dic[k]=str(exon_newindex)\n\t\t\t\t\texon_add='A';\n\t\t\t\t\texon_newindex+=1;\n\t\t\t\tk+=1;\n\t\t\tif not(k in exon_newindex_dic):\n\t\t\t\texon_newindex_dic[k]=str(exon_newindex)\n\t\telse:\n\t\t\t#print(exon_newindex_dic);\n\t\t\tfor juc in range(len(elements[1:-1])):\n\t\t\t\tthis_pattern[exon_newindex_dic[int(elements[juc+1])]+'-'+exon_newindex_dic[int(elements[juc+2])]]=0;\nifile.close();\n\n#write the pattern summary\nofile=open(sys.argv[2],'w'); skip = 0;\nfor i in asm_class.keys():\n\tif skip == 0:\n\t\tskip = 1; continue;\n\tofile.write(i+'\\t'+str(asm_class[i])+'\\n');\nofile.close();\n\n#write the pattern for each asm\nofile=open(sys.argv[3],'w');\nfor i in range(len(asm_list)-1):\n\tofile.write(asm_list[i]+'\\t'+class_list[i+1]+'\\n');\nofile.close();\n\n","sub_path":"ISOClassify/IsoClass.py","file_name":"IsoClass.py","file_ext":"py","file_size_in_byte":2097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"480615175","text":"import json\nimport copy\nfrom utils.quentin_test import list_quests, list_q\n\nfrom clickhouse_driver import Client\nclient = Client('localhost')\n\ndef gen_keyboard(buttons=()):\n keyboard = {\n 'one_time': True,\n 'buttons': []\n }\n\n one_button = {\n 'action': {\n 'type': 'text',\n 'payload': json.dumps({'buttons': 'next'}),\n 'label': 'Next Question'\n },\n 'color': 'default'\n }\n\n manage_button = [{\n 'action': {\n 'type': 'text',\n 'payload': json.dumps({'buttons': 'rights'}),\n 'label': 'rights'\n },\n 'color': 'primary'\n },\n {\n 'action': {\n 'type': 'text',\n 'payload': json.dumps({'buttons': 'statistic'}),\n 'label': 'statistic'\n },\n 'color': 'primary'\n }]\n quest = [{\n 'action': {\n 'type': 'text',\n 'payload': json.dumps({'buttons': 'question'}),\n 'label': 'question'\n },\n 'color': 'positive'\n }]\n\n keyboard['buttons'].append(manage_button)\n keyboard['buttons'].append(quest)\n for b in buttons:\n one_button['action']['payload'] = json.dumps({'id_qwst': b.get('id_qwst'), 'id_answ': b.get('id_answ')})\n one_button['action']['label'] = b.get('answer')\n keyboard['buttons'].append([copy.deepcopy(one_button)])\n return keyboard\n\ndef find_next_quest(id_q, user_id):\n #its not all q in this day. else return -1\n #select * from user_quest where user = user_id and state is not True order by indx limit 1\n id_q += 1\n question = list_q.get(str(id_q))\n return question, id_q\n\ndef update_state(id_a, id_q, user_id):\n #select ransw, score\n # from user_quest\n # where user = user_id\n # and id_quest = id_q\n # limit 1\n\n #update user_quest\n # set state = new_state\n # , date = current_date\n # where where user = user_id\n # and id_quest = id_q\n\n #update user\n # set score = score + quest_score\n # where where user = user_id\n # and id_quest = id_q\n\n quest = list_q.get(str(id_q))\n return quest.get('ransw'), quest.get('score')\n\n\ndef get_next_answer(payload, user_id):\n ind_qwst = 0\n r_answ = ''\n if payload and payload.get('id_qwst') and payload.get('id_qwst').isdigit():\n id_q = int(payload.get('id_qwst'))\n id_a = payload.get('id_answ')\n r_answ, score = update_state(id_a, id_q, user_id)\n else:\n id_q = 0\n\n qwst, id_new_q = find_next_quest(id_q, user_id)\n btn_ids = []\n if qwst is None:\n message = 'quests finished'\n else:\n message = qwst.get('message')\n print(qwst)\n answ = qwst.get('answ')\n btn_ids = [{'answer': aw, 'id_answ': aw, 'id_qwst': str(id_new_q)} for aw in answ]\n\n print(btn_ids)\n\n ms_question = 'Right answ was: {r_answ} \\n New qwst: {new_quest}'.format(r_answ=r_answ, new_quest=message)\n return ms_question, id_new_q, btn_ids\n","sub_path":"utils/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"122598291","text":"#!/usr/bin/env python3\n# Copyright 2014 The Chromium Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style license that can be\n# found in the LICENSE file.\n\n\"\"\"\nChecks out a downstream branch from the currently checked out branch. If there\nis more than one downstream branch, then this script will prompt you to select\nwhich branch.\n\"\"\"\n\nfrom __future__ import print_function\n\nimport argparse\nimport sys\n\nimport gclient_utils\nfrom git_common import current_branch, branches, upstream, run, hash_one\nimport metrics\n\n\n@metrics.collector.collect_metrics('git nav-downstream')\ndef main(args):\n parser = argparse.ArgumentParser()\n parser.add_argument('--pick',\n help=(\n 'The number to pick if this command would '\n 'prompt'))\n opts = parser.parse_args(args)\n\n upfn = upstream\n cur = current_branch()\n if cur == 'HEAD':\n def _upfn(b):\n parent = upstream(b)\n if parent:\n return hash_one(parent)\n upfn = _upfn\n cur = hash_one(cur)\n downstreams = [b for b in branches() if upfn(b) == cur]\n if not downstreams:\n print(\"No downstream branches\")\n return 1\n\n if len(downstreams) == 1:\n run('checkout', downstreams[0], stdout=sys.stdout, stderr=sys.stderr)\n else:\n high = len(downstreams) - 1\n while True:\n print(\"Please select a downstream branch\")\n for i, b in enumerate(downstreams):\n print(\" %d. %s\" % (i, b))\n prompt = \"Selection (0-%d)[0]: \" % high\n r = opts.pick\n if r:\n print(prompt + r)\n else:\n r = gclient_utils.AskForData(prompt).strip() or '0'\n if not r.isdigit() or (0 > int(r) > high):\n print(\"Invalid choice.\")\n else:\n run('checkout', downstreams[int(r)], stdout=sys.stdout,\n stderr=sys.stderr)\n break\n return 0\n\n\nif __name__ == '__main__':\n with metrics.collector.print_notice_and_exit():\n sys.exit(main(sys.argv[1:]))\n","sub_path":"third_party/depot_tools/git_nav_downstream.py","file_name":"git_nav_downstream.py","file_ext":"py","file_size_in_byte":1971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"411042248","text":"\"\"\"project URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.8/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Add an import: from blog import urls as blog_urls\n 2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))\n\"\"\"\nfrom django.conf import settings\nfrom django.conf.urls import patterns, include, url\nfrom django.contrib import admin\nfrom django.conf.urls.static import static\nfrom django.contrib.staticfiles.urls import staticfiles_urlpatterns\n\nurlpatterns = [\n\n url(r'^$','security.views.quiz',name='home'),\n url(r'^edit/','security.views.edit',name='edit'),\n url(r'^delete/','security.views.delete',name='delete'),\n url(r'^publish/','security.views.publish',name='publish'),\n url(r'^republish/','security.views.republish',name='re_publish'),\n url(r'^delete_post/','security.views.deletepost',name='delete_post'),\n\n url(r'^chats/', include('chat.urls'),name='chats'),\n url(r'^register/complete/$','security.views.registration_complete',name='registration_complete'),\n url(r'^admin/', include(admin.site.urls)),\n url(r'^accounts/', include('registration.backends.simple.urls')),\n\n]\nif settings.DEBUG:\n urlpatterns+= static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)\n urlpatterns+= static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n urlpatterns += staticfiles_urlpatterns()\n\n","sub_path":"project/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"514304208","text":"from utils import control, mirror_control, manager_stat, check\r\n\r\n\r\ndef menu():\r\n try:\r\n while 1:\r\n mode = input(\"1.新增镜像\\n2.镜像管理\\n3.Manager状态\\n\")\r\n if mode:\r\n mode = int(mode)\r\n else:\r\n break\r\n if mode == 1:\r\n name = input(\"输入mirror名称(不能重复):\")\r\n mirror_control(name).add()\r\n elif mode == 2:\r\n control()\r\n elif mode == 3:\r\n manager_stat()\r\n else:\r\n return 0\r\n except KeyboardInterrupt:\r\n return 0\r\n\r\n\r\nif __name__ == \"__main__\":\r\n if check():\r\n menu()\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"346262304","text":"import numpy as np\nimport scipy.sparse as sp\nimport scipy.sparse.linalg as linalg\nimport scipy.integrate as integrate\nimport time\nimport matplotlib.pyplot as plt\n\n\ndef gquad_colloc(n):\n \"\"\"Function to return collocation position (zeta) and gaussian weights (w)\n\n Input:\n n -- number of collocation points\n Return:\n zeta -- n vector of collocation abscissa\n w -- n vector of gaussian weights at collocation points\n \"\"\"\n zeta = []\n w = []\n if n == 2:\n zeta = np.array([-0.577350269189626,\n 0.577350269189626])\n w = np.array([1,\n 1])\n elif n == 3:\n zeta = np.array([0,\n -0.7745966692414834,\n 0.7745966692414834])\n w = np.array([0.8888888888888888,\n 0.5555555555555556,\n 0.5555555555555556])\n elif n == 4:\n zeta = np.array([-0.3399810435848563,\n 0.3399810435848563,\n -0.8611363115940526,\n 0.8611363115940526])\n w = np.array([0.6521451548625461,\n 0.6521451548625461,\n 0.3478548451374538,\n 0.3478548451374538])\n elif n == 5:\n zeta = np.array([0,\n -0.5384693101056831,\n 0.5384693101056831,\n -0.9061798459386640,\n 0.9061798459386640])\n w = np.array([0.5688888888888889,\n 0.4786286704993665,\n 0.4786286704993665,\n 0.2369268850561891,\n 0.2369268850561891])\n else:\n print(\"Higher order not yet implemented.\")\n return zeta, w\n\n\ndef gquad(function, a, b, n=2):\n \"\"\"Function for n point gaussian quadrature\n\n Input:\n function -- function to be integrated\n a -- lower bound for integration\n b -- upper bound for integration\n n -- n-point gaussian quadrature. Default = 2\n Return:\n result -- integration value\n \"\"\"\n result = 0\n zeta, w = gquad_colloc(n)\n x = (b - a) / 2 * zeta + (b + a) / 2\n for (xc, wc) in zip(x, w):\n result += wc * function(xc)\n result *= (b - a) / 2\n return result\n\n\ndef fem_solver(v, elem, elas, load, b, bc, order=1, solver='sparse'):\n \"\"\"Function for finite element method solver for diff eqn in hw1\n\n Input:\n v -- #v by 1 position of vertices (nodes)\n elem -- #elem by 2 position of elements. Contain vertex ids\n elas -- function for elasticity\n load -- function for load\n b -- #b by 1 id of boundary nodes\n bc -- #b by 1 value at corresponding boundary nodes\n Return:\n u -- solution on nodes\n \"\"\"\n n_node = v.shape[0]\n n_elem = elem.shape[0]\n # construct element-wise stiffness matrix\n # construct element-wise load matrix\n k_e = np.zeros([n_elem, order + 1, order + 1])\n r_e = np.zeros([n_elem, order + 1])\n for e in range(n_elem): # loop through elements\n x_elem = v[elem[e, :]]\n # stiffness and load\n k_e[e, :, :], r_e[e, :] = kr_ij(elas, load, x_elem, order)\n if solver == 'sparse':\n u = sparse_solve(v, elem, k_e, r_e, b, bc)\n else:\n u = pcg_solve(v, elem, k_e, r_e, b, bc)\n\n return u\n\n\ndef kr_ij(elas, load, x, order=1):\n \"\"\"Function to calculate the local stiffness matrix\n Input:\n elas -- elasticity function\n x -- vector of actual physical position of nodes in element\n order -- order of polynomial\n Return:\n kij_e -- k matrix for the eth element\n rij_e -- r vector for the eth element\n \"\"\"\n # n = order + 1 # Gaussian integration order\n n = 5 # Gaussian integration order\n kij_e = np.zeros([order + 1, order + 1])\n rij_e = np.zeros([order + 1])\n if order == 1:\n x_zeta = lambda zeta: 0.5 * (x[0] + x[-1]) + zeta / 2 * (x[-1] - x[0])\n dzeta_dx = lambda zeta: 2 / (x[-1] - x[0])\n # k matrix\n f_00 = lambda zeta: 1 / 4 * elas(x_zeta(zeta)) * dzeta_dx(zeta)\n kij_e[0, 0] = gquad(f_00, -1, 1, n=n)\n kij_e[1, 1] = kij_e[0, 0]\n kij_e[1, 0] = -kij_e[0, 0]\n kij_e[0, 1] = -kij_e[0, 0]\n # r vector\n f_0 = lambda zeta: (0.5 * (1 - zeta) * load(x_zeta(zeta))) / dzeta_dx(zeta)\n f_1 = lambda zeta: (0.5 * (1 + zeta) * load(x_zeta(zeta))) / dzeta_dx(zeta)\n rij_e[0] = gquad(f_0, -1, 1, n=n)\n rij_e[1] = gquad(f_1, -1, 1, n=n)\n elif order == 2:\n x_zeta = lambda zeta: x[0] * (-0.5 * zeta * (1 - zeta)) + x[1] * (1 - zeta ** 2) \\\n + x[2] * (0.5 * zeta * (1 + zeta))\n dzeta_dx = lambda zeta: 1 / (zeta * (x[0] - 2 * x[1] + x[2]) + 0.5 * (x[2] - x[0]))\n # k matrix\n f_00 = lambda zeta: (zeta - 0.5) ** 2 * elas(x_zeta(zeta)) * dzeta_dx(zeta)\n f_01 = lambda zeta: (zeta - 0.5) * (-2 * zeta) * elas(x_zeta(zeta)) * dzeta_dx(zeta)\n f_02 = lambda zeta: (zeta - 0.5) * (zeta + 0.5) * elas(x_zeta(zeta)) * dzeta_dx(zeta)\n f_11 = lambda zeta: (-2 * zeta) ** 2 * elas(x_zeta(zeta)) * dzeta_dx(zeta)\n f_12 = lambda zeta: (-2 * zeta) * (zeta + 0.5) * elas(x_zeta(zeta)) * dzeta_dx(zeta)\n f_22 = lambda zeta: (zeta + 0.5) ** 2 * elas(x_zeta(zeta)) * dzeta_dx(zeta)\n kij_e[0, 0] = gquad(f_00, -1, 1, n=n)\n kij_e[0, 1] = gquad(f_01, -1, 1, n=n)\n kij_e[0, 2] = gquad(f_02, -1, 1, n=n)\n kij_e[1, 1] = gquad(f_11, -1, 1, n=n)\n kij_e[1, 2] = gquad(f_12, -1, 1, n=n)\n kij_e[2, 2] = gquad(f_22, -1, 1, n=n)\n kij_e[1, 0] = kij_e[0, 1]\n kij_e[2, 0] = kij_e[0, 2]\n kij_e[2, 1] = kij_e[1, 2]\n # r vector\n f_0 = lambda zeta: (-0.5 * zeta * (1 - zeta) * load(x_zeta(zeta))) / dzeta_dx(zeta)\n f_1 = lambda zeta: ((1 - zeta ** 2) * load(x_zeta(zeta))) / dzeta_dx(zeta)\n f_2 = lambda zeta: (0.5 * zeta * (1 + zeta) * load(x_zeta(zeta))) / dzeta_dx(zeta)\n rij_e[0] = gquad(f_0, -1, 1, n=n)\n rij_e[1] = gquad(f_1, -1, 1, n=n)\n rij_e[2] = gquad(f_2, -1, 1, n=n)\n elif order == 3:\n # basis functions\n phi_0 = lambda zeta: (-9 / 16) * (zeta + 1 / 3) * (zeta - 1 / 3) * (zeta - 1)\n phi_1 = lambda zeta: (27 / 16) * (zeta + 1) * (zeta - 1 / 3) * (zeta - 1)\n phi_2 = lambda zeta: (-27 / 16) * (zeta + 1) * (zeta + 1 / 3) * (zeta - 1)\n phi_3 = lambda zeta: (9 / 16) * (zeta + 1) * (zeta + 1 / 3) * (zeta - 1 / 3)\n dphi_0 = lambda zeta: 1 / 16 * (-27 * zeta ** 2 + 18 * zeta + 1)\n dphi_1 = lambda zeta: 9 / 16 * (9 * zeta ** 2 - 2 * zeta - 3)\n dphi_2 = lambda zeta: -9 / 16 * (9 * zeta ** 2 + 2 * zeta - 3)\n dphi_3 = lambda zeta: 1 / 16 * (27 * zeta ** 2 + 18 * zeta - 1)\n\n x_zeta = lambda zeta: x[0] * phi_0(zeta) + x[1] * phi_1(zeta) + x[2] * phi_2(zeta) + x[3] * phi_3(zeta)\n dzeta_dx = lambda zeta: 1 / (\n x[0] * dphi_0(zeta) + x[1] * dphi_1(zeta) + x[2] * dphi_2(zeta) + x[3] * dphi_3(zeta))\n # k matrix\n f_00 = lambda zeta: dphi_0(zeta) * dphi_0(zeta) * elas(x_zeta(zeta)) * dzeta_dx(zeta)\n f_01 = lambda zeta: dphi_0(zeta) * dphi_1(zeta) * elas(x_zeta(zeta)) * dzeta_dx(zeta)\n f_02 = lambda zeta: dphi_0(zeta) * dphi_2(zeta) * elas(x_zeta(zeta)) * dzeta_dx(zeta)\n f_03 = lambda zeta: dphi_0(zeta) * dphi_3(zeta) * elas(x_zeta(zeta)) * dzeta_dx(zeta)\n f_11 = lambda zeta: dphi_1(zeta) * dphi_1(zeta) * elas(x_zeta(zeta)) * dzeta_dx(zeta)\n f_12 = lambda zeta: dphi_1(zeta) * dphi_2(zeta) * elas(x_zeta(zeta)) * dzeta_dx(zeta)\n f_13 = lambda zeta: dphi_1(zeta) * dphi_3(zeta) * elas(x_zeta(zeta)) * dzeta_dx(zeta)\n f_22 = lambda zeta: dphi_2(zeta) * dphi_2(zeta) * elas(x_zeta(zeta)) * dzeta_dx(zeta)\n f_23 = lambda zeta: dphi_2(zeta) * dphi_3(zeta) * elas(x_zeta(zeta)) * dzeta_dx(zeta)\n f_33 = lambda zeta: dphi_3(zeta) * dphi_3(zeta) * elas(x_zeta(zeta)) * dzeta_dx(zeta)\n kij_e[0, 0] = gquad(f_00, -1, 1, n=n)\n kij_e[0, 1] = gquad(f_01, -1, 1, n=n)\n kij_e[0, 2] = gquad(f_02, -1, 1, n=n)\n kij_e[0, 3] = gquad(f_03, -1, 1, n=n)\n kij_e[1, 1] = gquad(f_11, -1, 1, n=n)\n kij_e[1, 2] = gquad(f_12, -1, 1, n=n)\n kij_e[1, 3] = gquad(f_13, -1, 1, n=n)\n kij_e[2, 2] = gquad(f_22, -1, 1, n=n)\n kij_e[2, 3] = gquad(f_23, -1, 1, n=n)\n kij_e[3, 3] = gquad(f_33, -1, 1, n=n)\n kij_e[1, 0] = kij_e[0, 1]\n kij_e[2, 0] = kij_e[0, 2]\n kij_e[3, 0] = kij_e[0, 3]\n kij_e[2, 1] = kij_e[1, 2]\n kij_e[3, 1] = kij_e[1, 3]\n kij_e[3, 2] = kij_e[2, 3]\n # r vector\n f_0 = lambda zeta: (phi_0(zeta) * load(x_zeta(zeta))) / dzeta_dx(zeta)\n f_1 = lambda zeta: (phi_1(zeta) * load(x_zeta(zeta))) / dzeta_dx(zeta)\n f_2 = lambda zeta: (phi_2(zeta) * load(x_zeta(zeta))) / dzeta_dx(zeta)\n f_3 = lambda zeta: (phi_3(zeta) * load(x_zeta(zeta))) / dzeta_dx(zeta)\n rij_e[0] = gquad(f_0, -1, 1, n=n)\n rij_e[1] = gquad(f_1, -1, 1, n=n)\n rij_e[2] = gquad(f_2, -1, 1, n=n)\n rij_e[3] = gquad(f_3, -1, 1, n=n)\n\n return kij_e, rij_e\n\n\ndef error_metric(u_num, du_true, v, elem, elas, order=1, vec=False):\n \"\"\"Function to evaluate error metric for fem calculation\n\n Input:\n u_num -- #v fem solution on nodes\n du_true -- function for true solution derivative\n v -- #v by 1 position of vertices (nodes)\n elem -- #elem by 2 position of elements. Contain vertex ids\n elas -- function for elasticity\n Return:\n err -- numerical error from fem solution\n \"\"\"\n\n assert (order == 1 or order == 2 or order == 3)\n\n f_denom = lambda x: elas(x) * du_true(x) ** 2\n denom, _ = integrate.quad(f_denom, np.min(v), np.max(v), limit=10000) # denominator\n\n # Function for derivative evaluation\n def du_num(x):\n # find element where probe location is\n inelem = np.nonzero((x >= v[elem[:, 0]]) * (x <= v[elem[:, -1]]))[0][0]\n x_elem = v[elem[inelem, :]]\n u_elem = u_num[elem[inelem, :]]\n if order == 1:\n dphi_0 = lambda x: 1/(x_elem[0]-x_elem[1])\n dphi_1 = lambda x: 1/(x_elem[1]-x_elem[0])\n val = u_elem[0]*dphi_0(x)+u_elem[1]*dphi_1(x)\n elif order == 2:\n dphi_0 = lambda x: (2 * x - x_elem[1] - x_elem[2]) / ((x_elem[0] - x_elem[1]) * (x_elem[0] - x_elem[2]))\n dphi_1 = lambda x: (2 * x - x_elem[0] - x_elem[2]) / ((x_elem[1] - x_elem[0]) * (x_elem[1] - x_elem[2]))\n dphi_2 = lambda x: (2 * x - x_elem[0] - x_elem[1]) / ((x_elem[2] - x_elem[0]) * (x_elem[2] - x_elem[1]))\n val = u_elem[0] * dphi_0(x) + u_elem[1] * dphi_1(x) + u_elem[2] * dphi_2(x)\n elif order == 3:\n x0, x1, x2, x3 = x_elem[0], x_elem[1], x_elem[2], x_elem[3]\n dphi_0 = lambda x: (3 * x ** 2 - 2 * x * (x1 + x2 + x3) + (x1 * x2 + x2 * x3 + x1 * x3)) / \\\n ((x0 - x1) * (x0 - x2) * (x0 - x3))\n dphi_1 = lambda x: (3 * x ** 2 - 2 * x * (x0 + x2 + x3) + (x0 * x2 + x2 * x3 + x0 * x3)) / \\\n ((x1 - x0) * (x1 - x2) * (x1 - x3))\n dphi_2 = lambda x: (3 * x ** 2 - 2 * x * (x1 + x0 + x3) + (x1 * x0 + x0 * x3 + x1 * x3)) / \\\n ((x2 - x1) * (x2 - x0) * (x2 - x3))\n dphi_3 = lambda x: (3 * x ** 2 - 2 * x * (x1 + x2 + x0) + (x1 * x2 + x2 * x0 + x1 * x0)) / \\\n ((x3 - x1) * (x3 - x2) * (x3 - x0))\n val = u_elem[0] * dphi_0(x) + u_elem[1] * dphi_1(x) + u_elem[2] * dphi_2(x) + u_elem[3] * dphi_3(x)\n return val\n\n f_num = lambda x: (du_true(x) - du_num(x)) ** 2 * elas(x)\n if not vec:\n numerator, _ = integrate.quad(f_num, np.min(v), np.max(v), limit=10000) # numerator\n err = np.sqrt(numerator / denom)\n return err\n else:\n L = np.max(v)-np.min(v)\n err = np.zeros(elem.shape[0])\n for i in range(elem.shape[0]):\n h_i = np.abs(np.max(v[elem[i, :]]) - np.min(v[elem[i, :]]))\n num_i, _ = integrate.quad(f_num, np.min(v[elem[i, :]]), np.max(v[elem[i, :]]), limit=10000)\n err[i] = np.sqrt(L/h_i*num_i/denom)\n return err\n\n\ndef mesh_setup(x_0=0, L=1, n_elem=3, v=[], order=1):\n \"\"\"Function to setup the uniform mesh of a given order\n\n Input:\n n_elem -- #elem\n order -- #order of polynomial\n Return:\n v -- #v by 1 position of vertices (nodes)\n elem -- #elem by polyOrder+1 position of elements. Contain vertex ids in each element\n \"\"\"\n if v == []:\n v = np.linspace(x_0, L, order * n_elem + 1) # uniform nodes\n else:\n n_elem = v.shape[0] - 1\n elem = np.zeros([n_elem, order + 1], dtype=int) # connectivity\n for col in range(order + 1):\n elem[:, col] = np.arange(col, col + order * (n_elem - 1) + 1, order, dtype=int)\n return v, elem\n\n\ndef u_eval(x, u, v, elem):\n \"\"\"Function to evaluate the value of the FEM solution given solution order\n Input:\n x -- array or value of physical position to probe the solution\n u -- #v FEM solution at node points\n v -- #v FEM node point locations\n elem -- #elem by order+1 element connectivity matrix\n Output:\n u_ev -- #x solution evaluation at evaluation points\n \"\"\"\n order = elem.shape[1]-1\n assert (order == 1 or order == 2 or order == 3)\n try:\n n_eval = x.shape[0]\n u_ev = np.zeros(x.shape)\n vec = True\n except:\n n_eval = 1\n u_ev = 0\n vec = False\n if vec:\n for i in range(n_eval):\n # find element where probe location is\n inelem = np.nonzero((x[i] >= v[elem[:, 0]]) * (x[i] <= v[elem[:, -1]]))[0][0]\n x_elem = v[elem[inelem, :]]\n u_elem = u[elem[inelem, :]]\n if order == 1:\n phi_0 = lambda X: (X-x_elem[1])/(x_elem[0]-x_elem[1])\n phi_1 = lambda X: (X-x_elem[0])/(x_elem[1]-x_elem[0])\n u_ev[i] = u_elem[0]*phi_0(x[i])+u_elem[1]*phi_1(x[i])\n elif order == 2:\n phi_0 = lambda X: (X - x_elem[1])*(X - x_elem[2]) / ((x_elem[0] - x_elem[1])*(x_elem[0] - x_elem[2]))\n phi_1 = lambda X: (X - x_elem[0])*(X - x_elem[2]) / ((x_elem[1] - x_elem[0])*(x_elem[1] - x_elem[2]))\n phi_2 = lambda X: (X - x_elem[0])*(X - x_elem[1]) / ((x_elem[2] - x_elem[0])*(x_elem[2] - x_elem[1]))\n u_ev[i] = u_elem[0] * phi_0(x[i]) + u_elem[1] * phi_1(x[i]) + u_elem[2] * phi_2(x[i])\n elif order == 3:\n phi_0 = lambda X: (X - x_elem[1]) * (X - x_elem[2]) * (X - x_elem[3]) \\\n / ((x_elem[0] - x_elem[1]) * (x_elem[0] - x_elem[2]) * (x_elem[0] - x_elem[3]))\n phi_1 = lambda X: (X - x_elem[0]) * (X - x_elem[2]) * (X - x_elem[3]) \\\n / ((x_elem[1] - x_elem[0]) * (x_elem[1] - x_elem[2]) * (x_elem[1] - x_elem[3]))\n phi_2 = lambda X: (X - x_elem[0]) * (X - x_elem[1]) * (X - x_elem[3]) \\\n / ((x_elem[2] - x_elem[0]) * (x_elem[2] - x_elem[1]) * (x_elem[2] - x_elem[3]))\n phi_3 = lambda X: (X - x_elem[0]) * (X - x_elem[1]) * (X - x_elem[2]) \\\n / ((x_elem[3] - x_elem[0]) * (x_elem[3] - x_elem[1]) * (x_elem[3] - x_elem[2]))\n u_ev[i] = u_elem[0] * phi_0(x[i]) + u_elem[1] * phi_1(x[i]) \\\n + u_elem[2] * phi_2(x[i]) + u_elem[3] * phi_3(x[i])\n else:\n # find element where probe location is\n inelem = np.nonzero((x >= v[elem[:, 0]]) * (x <= v[elem[:, -1]]))[0][0]\n x_elem = v[elem[inelem, :]]\n u_elem = u[elem[inelem, :]]\n if order == 1:\n phi_0 = lambda X: (X - x_elem[1]) / (x_elem[0] - x_elem[1])\n phi_1 = lambda X: (X - x_elem[0]) / (x_elem[1] - x_elem[0])\n u_ev = u_elem[0] * phi_0(x) + u_elem[1] * phi_1(x)\n elif order == 2:\n phi_0 = lambda X: (X - x_elem[1]) * (X - x_elem[2]) / (x_elem[0] - x_elem[1]) * (x_elem[0] - x_elem[2])\n phi_1 = lambda X: (X - x_elem[0]) * (X - x_elem[2]) / (x_elem[1] - x_elem[0]) * (x_elem[1] - x_elem[2])\n phi_2 = lambda X: (X - x_elem[0]) * (X - x_elem[1]) / (x_elem[2] - x_elem[0]) * (x_elem[2] - x_elem[1])\n u_ev = u_elem[0] * phi_0(x) + u_elem[1] * phi_1(x) + u_elem[2] * phi_2(x)\n elif order == 3:\n phi_0 = lambda X: (X - x_elem[1]) * (X - x_elem[2]) * (X - x_elem[3]) \\\n / ((x_elem[0] - x_elem[1]) * (x_elem[0] - x_elem[2]) * (x_elem[0] - x_elem[3]))\n phi_1 = lambda X: (X - x_elem[0]) * (X - x_elem[2]) * (X - x_elem[3]) \\\n / ((x_elem[1] - x_elem[0]) * (x_elem[1] - x_elem[2]) * (x_elem[1] - x_elem[3]))\n phi_2 = lambda X: (X - x_elem[0]) * (X - x_elem[1]) * (X - x_elem[3]) \\\n / ((x_elem[2] - x_elem[0]) * (x_elem[2] - x_elem[1]) * (x_elem[2] - x_elem[3]))\n phi_3 = lambda X: (X - x_elem[0]) * (X - x_elem[1]) * (X - x_elem[2]) \\\n / ((x_elem[3] - x_elem[0]) * (x_elem[3] - x_elem[1]) * (x_elem[3] - x_elem[2]))\n u_ev = u_elem[0] * phi_0(x) + u_elem[1] * phi_1(x) \\\n + u_elem[2] * phi_2(x) + u_elem[3] * phi_3(x)\n return u_ev\n\n\ndef sparse_solve(v, elem, k_e, r_e, b, bc):\n \"\"\"Function to solve for FEM solution by building sparse global matrix using Scipy's datastructure\n Input:\n v -- #v FEM node point locations\n elem -- #elem by order+1 element connectivity matrix\n k_e -- k matrix for the eth element\n r_e -- r vector for the eth element\n b -- #b by 1 id of boundary nodes\n bc -- #b by 1 value at corresponding boundary nodes\n Output:\n u -- #v FEM solution at node points\n \"\"\"\n n_node = v.shape[0]\n n_elem = elem.shape[0]\n # construct global sparse stiffness matrix\n # construct global load vector\n k_global = sp.dok_matrix((n_node, n_node))\n r_global = np.zeros([n_node])\n for e in range(n_elem): # iterate through element\n for i in range(k_e.shape[1]):\n for j in range(k_e.shape[2]):\n k_global[elem[e, i], elem[e, j]] += k_e[e, i, j]\n for i in range(r_e.shape[1]):\n r_global[elem[e, i]] += r_e[e, i]\n\n # apply boundary conditions\n for i in range(b.shape[0]):\n r_global[b[i]] = bc[i]\n # pad with ones and zeros\n k_global[b[i], :] = np.zeros(n_node)\n k_global[b[i], b[i]] = 1\n\n k_global = k_global.tocsc()\n u = linalg.spsolve(k_global, r_global)\n return u\n\n\ndef pcg_solve(v, elem, k_e, r_e, b, bc, tol=1e-6, itmax=1e7):\n \"\"\"Function to solve for FEM solution using local stiffness matrix and preconditioned conjugate gradient method\n (As required in HW3)\n Input:\n v -- #v FEM node point locations\n elem -- #elem by order+1 element connectivity matrix\n k_e -- k matrix for the eth element\n r_e -- r vector for the eth element\n b -- #b by 1 id of boundary nodes\n bc -- #b by 1 value at corresponding boundary nodes\n Output:\n u -- #v FEM solution at node points\n \"\"\"\n n_node = v.shape[0]\n n_elem = elem.shape[0]\n p = elem.shape[1]-1\n # find k_global's diagonal elements\n k_diag, R_e, R_p = np.zeros(n_node), np.zeros(n_node), np.zeros(n_node)\n for e in range(n_elem):\n k_diag[elem[e, :]] += k_e[e, :, :].diagonal()\n # apply boundary condition to k_e matrix\n for bi, bval in zip(b, bc):\n ei, ii = np.where(elem == bi)[0], np.where(elem == bi)[1]\n k_e[ei, ii, :] = np.zeros(p + 1)\n k_e[ei, ii, ii] = 1\n r_e[ei, ii] = bval\n # precondition local stiffness matrix and load vector\n for e in range(n_elem):\n temp = np.dot((k_diag[elem[e, :]].reshape([-1, 1])), (k_diag[elem[e, :]].reshape([1, -1])))\n temp = 1/np.sqrt(temp)\n k_p, r_p = k_e, r_e\n k_p[e, :, :] = np.multiply(temp, k_e[e, :, :])\n r_p[e, :] = np.multiply(1/np.sqrt(k_diag[elem[e, :]]), r_e[e, :])\n R_e[elem[e, :]] += r_e[e, :]\n R_p[elem[e, :]] += r_p[e, :]\n\n def ke_multiply(a):\n \"\"\"Subroutine to do matrix multiplication using elemental stiffness matrix (not global)\n Multiply k_e matrix by vector a to produce vector r\n \"\"\"\n ka = np.zeros(n_node)\n for e in range(n_elem):\n ka[elem[e, :]] += np.dot(k_e[e, :, :], a[elem[e, :]])\n return ka\n\n def kp_multiply(a):\n \"\"\"Subroutine to do matrix multiplication using elemental stiffness matrix (not global)\n Multiply k_p matrix by vector a to produce vector r\n \"\"\"\n ka = np.zeros(n_node)\n for e in range(n_elem):\n ka[elem[e, :]] += np.dot(k_p[e, :, :], a[elem[e, :]])\n return ka\n\n # iterate to solve matrix system using conjugate gradient method\n it, err = 1, 100\n u = np.random.normal(0, 1e-16, size=[n_node]) # Initialize u with a random guess with normal distribution\n r = R_p-kp_multiply(u)\n z = R_p-kp_multiply(u)\n lbd = np.dot(z.transpose(), r)/np.dot(z.transpose(), kp_multiply(z))\n u += lbd*z\n while it < itmax and err > tol:\n r = R_p-kp_multiply(u)\n theta = -np.dot(r.transpose(), kp_multiply(z))/np.dot(z.transpose(), kp_multiply(z))\n z = r+theta*z\n lbd = np.dot(z.transpose(), r) / np.dot(z.transpose(), kp_multiply(z))\n u += lbd*z\n # Evaluate error\n err = lbd*np.sqrt(np.dot(z.transpose(), ke_multiply(z)))/np.sqrt(np.dot(u, ke_multiply(u)))\n it += 1\n if it >= itmax:\n print(\"PCG SOLVER: Warning: Did not converge in maximum number of iterations. Error value at exit: \", err)\n j = 0.5*np.dot(u.transpose(), ke_multiply(u))-np.dot(u.transpose(), R_e)\n print(\"PCG SOLVER: Error at exit: \", err, \" n_iter = \", it, \"potential energy = \", j)\n u = np.multiply(1/np.sqrt(k_diag), u)\n return u\n","sub_path":"ME280/Homework/fem.py","file_name":"fem.py","file_ext":"py","file_size_in_byte":22229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"551096800","text":"class Solution:\n def canPartitionKSubsets(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: bool\n \"\"\"\n from itertools import permutations\n t, r = divmod(sum(nums), k)\n if r != 0: return False\n def dfs(nums, ck):\n visited = set()\n if ck == 1:\n return sum(nums) == t\n for ll in range(1, len(nums)):\n for l in permutations(nums, ll):\n if tuple(l) in visited:\n continue\n visited.add(tuple(l))\n if sum(l) == t:\n left_nums = nums.copy()\n for v in l:\n left_nums.remove(v)\n res = dfs(left_nums, ck-1)\n if res: return True\n return False\n return dfs(nums, k)\n # time: k ^ n, more pricisely, (k-1)! * k ^ (n-k)\n # space: k + n\n def canPartitionKSubsets(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: bool\n \"\"\"\n buckets = [0] * k\n target, remain = divmod(sum(nums), k)\n if remain != 0: return False\n n = len(nums)\n nums.sort(reverse=True)\n \n def dfs(i):\n if i == n:\n return len(set(buckets)) == 1\n for j in range(k):\n buckets[j] += nums[i]\n if buckets[j] <= target and dfs(i+1):\n return True\n buckets[j] -= nums[i]\n # for the num > target\n if buckets[j] == 0:\n break\n return False\n return dfs(0)\n ","sub_path":"python/leetcode/backtracking/698_Partition_to_K_Equal_Sum_Subsets.py","file_name":"698_Partition_to_K_Equal_Sum_Subsets.py","file_ext":"py","file_size_in_byte":1744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"392617215","text":"\"\"\"Provide function for shuffling\"\"\"\n\nimport numpy as np\nimport time\n\ndef shuffle(times, offset_lim, iterations, **kwargs):\n '''\n Increment the provided time series by a random period of time in order to \n destroy the correlation between spike times and animal behaviour.\n \n The increment behaves circularly\n \n * Initially, we have two time series, Tracking and SpikeTimes, both with \n values in the range `[t0, t1]`. \n * After incrementing the SpikeTimes by T, we have Tracking in `[t0, t1]`\n and SpikeTimes in `[t0+T, t1+T]`.\n * Take all spike times in the range `[t1, t1+T]` and map back to `[t0, t0+T]`\n by subtracting `(t1-t0)`\n \n The end result should be a series of times also in the range [t0, t1], \n with the same intervals between times, but the exact value of those times\n has changed. if tracking_range not provided, then two spikes (previously \n first, last) will noe have zero spacing\n \n The random numbers are drawn from a pseudorandom, uniform, distribution in \n the range `[offset_lim, t1-offset_lim]`\n \n \n Parameters\n ----------\n times: np.ndarray\n 1D array of times to be shuffled\n offset_lim: float\n Defines the range of values by which each iteration can be offset. Each\n iteration will have an offset in `[offset_lim, max(times)-offset_lim]`\n iterations: int\n How many copies of times should be returned (each copy incremented by a\n random offset limited by `offset_lim`)\n tracking_range: array_like, optional\n The time range over which tracking behaviour exists, defining the\n times at which spike indexes are looped back on themselves\n This can be provided either as a 2-element tuple `[t0, t1]`, or as \n the entire list of tracking timestamps. In each case, the min and \n max values are used as `t0`, `t1`.\n If no values are provided, then the first and last spike times\n are used. This is not desirable behaviour, since it will then guarantee \n that in the shuffled output, two spikes will occur simultaneously\n debug: bool, optional\n Enable additional debugging output\n \n Returns\n -------\n output: np.ndarray\n iterations x N array of times. To access a single iteration, output[i,:] or output[i]\n increments : np.ndarray\n 1D array of offset values used.\n \n Notes\n --------\n BNT.+scripts.shuffling around line 350\n \n Copyright (C) 2019 by Simon Ball\n '''\n \n # Check values\n if type(times) != np.ndarray:\n times = np.array(times)\n if times.ndim != 1:\n raise ValueError(\"You must provide a 1D array of times. You provided a\"\\\n \" %d-dimensional array\" % times.ndim)\n if times.size == 0:\n raise ValueError(\"Your spike_times array is empty\")\n if np.isnan(times).any():\n raise ValueError(\"You have NaN values in your times array\")\n debug = kwargs.get('debug', False)\n tr = kwargs.get('tracking_range', None)\n try:\n if tr is not None:\n t0 = np.nanmin(tr)\n t1 = np.nanmax(tr)\n if (t0 > np.nanmin(times)) or (t1 < np.nanmax(times)):\n raise ValueError(\"Your times cover a larger span of time than your\"\\\n \" tracking information\")\n except ValueError as e:\n print(e)\n print(times)\n else:\n t0 = np.nanmin(times)\n t1 = np.nanmax(times)\n \n \n if offset_lim >= 0.5*(t1-t0):\n raise ValueError(\"offset_lim must be less than half of the time-span\"\\\n \" covered. You provided %.2g and a time span of %.2g\"\\\n % (offset_lim, t1-t0))\n\n \n # Initialise Numpy's random number generator with a new seed based on the \n # user's local computer OS methods\n t_min = t0 + offset_lim\n t_max = t1 - offset_lim\n \n \n increments = np.random.RandomState().rand(iterations) # Uniformmly distrbuted in [0, 1]\n increments = t_min + (increments * (t_max-t_min)) # uniformly distributed in [t_min, t_max]\n \n num_spikes = np.size(times)\n \n if debug:\n print(\"Number of spikes provided: %d\" % num_spikes)\n print(\"Spikes in time range [%d, %d]\" % (t0, t1))\n print(\"Iterations requested: %d\" % iterations)\n print(\"Increments in range [%.2f, %.2f]\" % (np.min(increments), np.max(increments)))\n \n \n # Generate 2D arrays by repeating over the correct axis\n # Want to duplicate the whole list of times for each repeat\n # Want to duplicate the *same* increment for each repeat. Hence the transpose. \n all_times = np.repeat(times[:,np.newaxis], iterations, axis=1) \n all_inc = np.repeat(increments[:, np.newaxis], times.size, axis=1).transpose()\n new_times = all_times + all_inc\n \n \n \n to_shift = (new_times > t1) # Binary array of the elements that need to be moved to the beginning. Each column is different\n time_idx = num_spikes - np.count_nonzero(to_shift, axis=0) # indicies of the first time in each iteration which must be moved\n if debug:\n print(\"New time range: [%d, %d]\" % (np.min(new_times), np.max(new_times)))\n print(\"Indexes exceeding value t1: %s\" % to_shift)\n \n output = np.zeros(new_times.shape)\n\n a0 = time.time()\n for i in range(iterations):\n # Circular buffer. We have alread identified the index at which elements \n # need to be moved (time_idx[i]). So take those end elements, and move \n # them to the start\n # Turns out, this is actually faster than fancy array indexing with np.ix_(time_idx, iter_idx), by nearly 100x (!) in testing\n \n # Elements that are still within the time range[t0+T, t1]\n a = new_times[0:time_idx[i], i]\n \n # Elements that are in the time range [t1, t1+T]\n # len(b) == num_spikes-time_idx[i]\n b = new_times[time_idx[i]:, i]\n \n # Elements in b should have their values reduced to fit in the range [t0, t0+T] \n b = b - t1 + t0\n \n # Insert elements into output in the correct order: b first, then a filling in the blanks after\n output[0:num_spikes-time_idx[i], i] = b\n output[num_spikes-time_idx[i]:, i] = a\n\n a1 = time.time()\n if debug:\n print(\"Final time range: [%d, %d]\" % (np.min(output), np.max(output)))\n print(\"method 1 took %dms\" % ((a1-a0)*1000))\n print(np.diff(times))\n print(np.diff(output[:,0]))\n \n # Want to return such that each row of the output is a single time-shifted iteration\n # This will allow a single iteration of ShuffledUnitSikeTimes to be accessed as output[i]\n output = output.transpose()\n \n return output, increments\n \n#if __name__ == '__main__':\n# times = [2, 12, 27, 54, 82, 113, 115, 207, 300]\n# t_min = 20\n# iterations = 3\n# s = shuffle(times, t_min, iterations, debug=False, tracking_range=(0,349))\n# #print(s)\n\n ","sub_path":"opexebo/general/shuffle.py","file_name":"shuffle.py","file_ext":"py","file_size_in_byte":7032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"522991261","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Oct 25 11:40:03 2018\n\n@author: ztw1e12\n\"\"\"\n\nimport pandas as pd\n\nfrom sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer\n\nfrom sklearn.model_selection import train_test_split\n\nfrom sklearn.linear_model import LogisticRegression\n\n\ndf = pd.read_csv(\"sentiment labelled sentences/yelp_labelled.txt\", names=['sentence', 'label'], sep=\"\\t\")\n\n\n# Splitting the data (sentence and labbels) into training and testing data \n\nsentences = df['sentence'].values\ny = df['label'].values\n\nsentences_train, sentences_test, y_train, y_test = train_test_split(sentences, y, test_size=0.25, random_state=1000)\n\nprint (sentences_train.shape)\n\n\n# vectorizing and tokonizing text; this is followed by fitting the data\nvectorizer = TfidfVectorizer()\nvectorizer.fit(sentences_train)\n\nX_train = vectorizer.transform(sentences_train)\nX_test = vectorizer.transform(sentences_test)\n\nprint (X_train.shape)\n\n\n# Training model LogisticRegression using data tokenized with CountVector \n\nclassifier = LogisticRegression()\ntst=classifier.fit(X_train, y_train)\nscore = classifier.score(X_test, y_test)\n\nprint(\"Test Accuracy:\",score)","sub_path":"Challenge Zenawi/nlppractice.py","file_name":"nlppractice.py","file_ext":"py","file_size_in_byte":1184,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"495342255","text":"import sys, json\nfrom collections import OrderedDict\nfrom operator import getitem\nfrom re import search\n\n'''\nClass to raise error if everything there is some problem in processing even if everyting is syntactically correct. \n'''\nclass LeaderbaordError(Exception):\n def __init__(self,message):\n self.message = message\n super().__init__(self.message)\n\n\n'''\nTakes existing data of JSON file, username and PR information as input and adds a record to the JSON file\nand returns the data of updated JSON file.\n'''\ndef add_record(data,username,pr_dict):\n # Check if record exists\n if (username in data.keys()):\n raise LeaderbaordError(\"Record already exists please create a new issue to update the contributions.\")\n\n # Add new record\n data[username] = {\"count\": len(pr_dict),\n \"contributions\": pr_dict\n }\n # Sort records in reverse order\n data = OrderedDict(sorted(data.items(), \n key = lambda x: getitem(x[1], 'count'),reverse=True))\n # Write sorted records in JSON file\n with open(\"community-contributions.json\",\"w\") as write_file:\n json.dump(data,write_file,indent=2)\n return data\n\n\n'''\nTakes existing data of JSON file, username and PR information as input and updates a record to the JSON file\nand returns the data of updated JSON file.\n'''\ndef update_record(data,username,pr_dict):\n # Check if record exists\n if (username not in data.keys()):\n raise LeaderbaordError(\"Record does not exists please create a new issue to add a contribution.\")\n\n # Update count \n data[username][\"count\"] += len(pr_dict)\n # Add new contributions\n for name,link in pr_dict.items():\n data[username][\"contributions\"][name] = link\n # Sort records in reverse order\n data = OrderedDict(sorted(data.items(), \n key = lambda x: getitem(x[1], 'count'),reverse=True))\n # Write sorted records in JSON file\n with open(\"community-contributions.json\",\"w\") as write_file:\n json.dump(data,write_file,indent=2)\n\n return data\n\n'''\nUpdates the leaderboard\n'''\n\ndef update_leaderboard(data,start_marker,end_marker,file_name):\n\n with open(file_name,\"r\") as read_file:\n read_data = read_file.read()\n # Get index of starting of leaderboard records\n start = read_data.index(start_marker)+len(start_marker) \n # Get index of ending of leaderboard records\n end = read_data.index(end_marker)\n write_data = read_data[:start]\n \n # Updating leaderboard from JSON file data\n # An empty list to store all the records\n records= []\n # Building string for record \n for usr,info in contr_data.items():\n records.append(f\"| [@{usr}](https://github.com/{usr}) | {info['count']} |

List of Contributions \")\n for pr, link in info[\"contributions\"].items():\n records.append(f\" - [{pr}]({link})
\")\n records.append(\"
|\\n\")\n \n # Combining all the records in a final string\n write_data = write_data+ \"\".join(records) + read_data[end:]\n\n # Writing on README file\n with open(file_name,\"w\") as write_file:\n write_file.write(write_data)\n\nif __name__ == \"__main__\":\n\n try:\n \n issue_head = sys.argv[1].strip()\n issue_bod = sys.argv[2].strip() \n # Get records from JSON file\n with open(\"community-contributions.json\",\"r\") as read_file:\n contr_data = json.load(read_file)\n\n # Create a dictionary\n pr_dict = {}\n for pr in issue_bod.split(\"\\n\"):\n # Assigning PR variables for PR name and link\n link = pr.split('|')[1].strip()\n link = (link.lstrip(\"**Link**: \")).strip()\n # If link is not valid\n if(search(r\"^https://github.com/.+/.+/pull/\\d+$\",link) == None):\n raise LeaderbaordError(\"Link is not valid please create another issue with valid link.\")\n\n pr_name = pr.split('|')[0].strip()\n pr_name = (pr_name.lstrip(\"**Name**: \")).strip()\n # Adding PR to the dictionary\n pr_dict[pr_name] = link\n \n # For adding new record \n if issue_head.split(\"|\")[0].lower() == \"add\":\n contr_data = add_record(contr_data,issue_head.split(\"|\")[1],pr_dict)\n \n # For updating existing record\n elif issue_head.split(\"|\")[0].lower() == \"update\":\n contr_data = update_record(contr_data,issue_head.split(\"|\")[1],pr_dict)\n \n # Update the leader board \n update_leaderboard(contr_data, 'Link of Contribution|\\n| --- | --- | --- |\\n', '